/*Por Francisco Olmedo*/

function traspasa(sel){
	var input_contacto = $(sel.value);
	for (var i = 0; i < sel.options.length; i++) {
		var obj = $(sel.options[i].value);
		if (!obj){
			continue;
		}
		obj.style.display = "none";
		obj.style.visibility = "hidden";

	}
	if (!input_contacto) {
		return true;
	}
	input_contacto.style.display = "";
	input_contacto.style.visibility = "visible";
}

function agregar_cont(){
    var test = document.getElementById('contacto2');
	var contac3 = document.getElementById('contacto3');
	var cto2 = document.getElementById("sel_cto2");
	var cto3 = document.getElementById("sel_cto3");
    var sp2 = document.getElementById('span_eli_2');
    var sp3 = document.getElementById('span_eli_3');
    
    if (test.style.visibility == "hidden") {
        test.style.visibility = "visible";
        cto2.style.visibility = "visible";
		cto2.name = cto2.id;
        sp2.style.visibility = "visible";
		test.name =  test.id;
    }
    else {
        contac3.style.visibility = "visible";
        cto3.style.visibility = "visible";
		alert(cto3.id);
		cto3.name = cto3.id;
		alert(cto3.name);
        sp3.style.visibility = "visible";
		contac3.name = contac3.id;
    }
    /*
    
     sel_cto3
    
     contacto3
    
     span_eli_3
    
     */
    
}

function quitar_cont(numero){
    var ct3 = document.getElementById('contacto3');
    var sp3 = document.getElementById('span_eli_3');
    var ct2 = document.getElementById('contacto2');
    var sp2 = document.getElementById('span_eli_2');
	var selcto2 = document.getElementById("sel_cto2")
	var selcto3 = document.getElementById("sel_cto3")
    if (numero == 3) {
        ct3.style.visibility = "hidden";
        ct3.value = "";
        ct3.form.sel_cto3.style.visibility = "hidden";
        ct3.form.sel_cto3.selectedIndex = 0;
		ct3.name = "";
        sp3.style.visibility = "hidden";
    }
    else { //es numero 2
        if (ct3.style.visibility == "visible") { //si contacto 3 est� , traspasa valores a contacto 2, 3 se borra
            ct2.value = ct3.value;
            ct2.form.sel_cto2.selectedIndex = ct3.form.sel_cto3.selectedIndex;
			ct2.name = "";
            quitar_cont(3);
        }
        else {
            ct2.value = "";
            ct2.style.visibility = "hidden";
            ct2.form.sel_cto2.selectedIndex = 0;
            ct2.form.sel_cto2.style.visibility = "hidden";
			ct2.name = "";
            sp2.style.visibility = "hidden";
        }
    }
}

function validaSolCons(boton, anon, palabra){
	if ($("esConsulta").checked == false && $("esQueja").checked == false && $("esSatisfaccion").checked == false){
		alert("Debe indicar si es una consulta, reclamo o felicitación");
		return false;
	}
 	try{
		var codigo = document.getElementById('codigo');
	}
	catch (e){
		anon = 0;
	}
	if (codigo==null){
		anon = 0;
	}
    var formu = boton.form;
    formu.setAttribute("method","post");
	var texto = "Debe ingresar:";
	var la_consulta = document.getElementById('la_consulta');
	var dest_servicio = document.getElementById('id_destinatario_servicio');	
	var nombre = document.getElementById('nombre');
	var region = document.getElementById('region');
	var pais = document.getElementById('pais');
    var aux = 0;

    if (anon == 1) {
	
		if (dest_servicio.value == "-1" && $('esUsuarioCongreso').value == 'True') {
			texto = texto + "\n- Campo Destinatario Servicio";
			aux = 1;
		}
		if (trim(la_consulta.value) == "") {
			texto = texto + "\n- Texto de la consulta o reclamo";
			aux = 1;
		}
		
		if (trim(nombre.value) == "") {
			texto = texto + "\n- Nombre";
			aux = "\n- ";
		}
		if (pais[pais.selectedIndex].value == -1 && $('esUsuarioCongreso').value == 'False') {
			texto = texto + "\n- Campo País";
			aux = 1;
		}
		
		if (formu.contacto1.value == "") {
			texto = texto + "\n- Contacto obligatorio";
			aux = 1;
		}
		if (formu.codigo.value == "") {
			texto = texto + "\n- Codigo Verificador";
			aux = 1;
		}
		if ((formu.sel_cto2.selectedIndex == 0 && formu.sel_cto2.style.visibility == "visible" && formu.contacto2.value != "") || (formu.sel_cto3.selectedIndex == 0 && formu.sel_cto3.style.visibility == "visible" && formu.contacto3.value != "")) {
			texto = texto + "\n- Tipo de contacto";
			aux = 1;
		}
		if (revisa_correos(formu)) {
			if (aux != 0) 
				texto = texto + "\n- Modifique formato de correo electronico";
			else 
				texto = "Modifique formato de correo electronico";
		}
		
		if (formu.codigo.value.toLowerCase() != palabra && formu.codigo.value != palabra) {
			if (aux != 1) 
				texto = texto + "\n- Codigo no coincide";
			
		}
		
		if (texto == "Debe ingresar:") {
			formOnOff('on');
			activaDestinatario($('id_destinatario_servicio'));
			formu.submit();
		}
		else {
			alert(texto);
		}
	}
	else {
	
		if (dest_servicio.value == "-1" && $('esUsuarioCongreso').value == 'True') {
			texto = texto + "\n- Campo Destinatario Servicio";
			aux = 1;
		}
		if (pais[pais.selectedIndex].value == -1 && $('esUsuarioCongreso').value == 'False') {
			texto = texto + "\n- Campo País";
			aux = 1;
		}
		if (formu.la_consulta.value == "") {
			texto = texto + "\n- Texto de la consulta o reclamo";
			aux = 1;
		}
		if (trim(nombre.value) == "") {
			texto = texto + "\n- Nombre";
			aux = "\n- ";
		}
		if (texto == "Debe ingresar:") {
			formOnOff('on');
			activaDestinatario_al_enviar($('id_destinatario_servicio'));
			formu.submit();
		}
		else {
			alert(texto);
		}
	}
    
    
    
}

function val_email(email){
    var expresion = /^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/ //  /^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/;
    if (expresion.test(email)) {
        return false; //ok
    }
    return true;
}

function validaCorreoConsulta(id_obj){
	objeto = document.getElementById(id_obj);
	objeto.value = objeto.value.toLowerCase();
	correo = objeto.value;
	
	if (!correo || correo == ''){
		return true;
	}
    var regex = /^(([\-\w]+)\.?)+@(([\-\w]+)\.?)+\.[a-zA-Z]{2,4}$/;
    if(!regex.test(correo)){
		alert("Formato de Correo Electrónico incorrecto.\nEjemplo correo válido: nombre@aaa.cl");
		setTimeout("document.getElementById('"+id_obj+"').focus();",100);
        return false;
    }
    return true;
}

function revisa_correos_bak(formu){
	var bool1 = bool2 = bool3 = false;
	bool1 = validaCorreoConsulta('contacto1'); //formu.contacto1.value;
	if (formu.sel_cto2.selectedIndex == 1) 
		bool2 = validaCorreoConsulta('contacto2');  //formu.contacto2.value;
	if (formu.sel_cto3.selectedIndex == 1) 
		bool3 = validaCorreoConsulta('contacto3');  //formu.contacto3.value;
	var ret = bool1 || bool2 || bool3;
	alert(ret);
	return ret;
}

function revisa_correos(formu){
    var bool1 = bool2 = bool3 = false;
    bool1 = val_email(formu.contacto1.value);
    if (formu.sel_cto2.selectedIndex == 1) 
        bool2 = val_email(formu.contacto2.value);
    if (formu.sel_cto3.selectedIndex == 1) 
        bool3 = val_email(formu.contacto3.value);
    var ret = bool1 || bool2 || bool3;
    return ret;
}

function formOnOff(onoff){
    var formm = document.getElementById("frmConsulta");
    var inputs = formm.getElementsByTagName("input");
    var selects = formm.getElementsByTagName("select");
    switch (onoff) {
        case 'off':
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].disabled = true;
            }
            for (var i = 0; i < selects.length; i++) {
                selects[i].disabled = true;
            }
            document.getElementById("addCto").innerHTML = "";
            break;
        case 'on':
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].disabled = false;
            }
            for (var i = 0; i < selects.length; i++) {
                selects[i].disabled = false;
            }
        //default:
        //	alert("error onoff");	
    }
    
    
    
    
}

function selAct(act){
    var selact = document.getElementById('actividad');
    for (var i = 0; i < selact.length; i++) {
        if (selact.options[i].value.toLowerCase() == act.toLowerCase()) {
            selact.options[i].selected = true;
            break;
        }
    }
}


function ltrim(s) {
   return s.replace(/^\s+/, "");
}

function rtrim(s) {
   return s.replace(/\s+$/, "");
}

function trim(s) {
   return rtrim(ltrim(s));
}

function activaDestinatario_al_enviar(select){
	if (!select){
		return 
	}
	
	var valor = select.value;
	var valor_original = valor;	
	
	if (valor==2){
		valor=1;
	}
	var div = 'divDestinatario_' + valor;
	for(var i=1;i<8;i++){
		if (i==2){continue;}
		var div2 = 'divDestinatario_' + i;
		document.getElementById(div2).style.display='none'; 
		var hijos2 = document.getElementById(div2).childNodes;
		disableHijos(hijos2);
	}

	if(valor==-1){
		return
	}
	
	document.getElementById(div).style.display='block';
	var hijos = document.getElementById(div).childNodes;
	enableHijos(hijos);
	
	/*
	if(div=='divDestinatario_3'){
		$('comision_camara').disabled = 'disabled';
	}
	*/
	
	/*
 	if(valor_original == 1 || valor_original == 2){
		activarSenadorDiputado(valor_original);
	}
	*/
}


function activaDestinatario(select){
	if (!select){
		return 
	}
	
	var valor = select.value;
	var valor_original = valor;	
	
	if (valor==2){
		valor=1;
	}
	var div = 'divDestinatario_' + valor;
	for(var i=1;i<8;i++){
		if (i==2){continue;}
		var div2 = 'divDestinatario_' + i;
		document.getElementById(div2).style.display='none'; 
		var hijos2 = document.getElementById(div2).childNodes;
		disableHijos(hijos2);
	}

	if(valor==-1){
		return
	}
	
	document.getElementById(div).style.display='block';
	var hijos = document.getElementById(div).childNodes;
	enableHijos(hijos);
	
	/*
	if(div=='divDestinatario_3'){
		$('comision_camara').disabled = 'disabled';
	}
	*/
	
	if(valor_original == 1 || valor_original == 2){
		activarSenadorDiputado(valor_original);
	}
}

function eligeOpcion(idDiv, idOpcion){
	var sel = $(idDiv);
	for(var i=0;i<sel.length;i++){
		if(sel[i].value == idOpcion){
			sel[i].selected = true;
			return true;
		}
	}
	return false;
}

function eligeRegion(id_region){
	var sel = $('region');
	for(var i=0;i<sel.length;i++){
		
		if(sel[i].value == id_region){
			sel[i].selected = true;
			return true;
		}
	}
	return false;
}

function eligePais(nom_pais){
	var sel = $('pais');
	for(var i=0;i<sel.length;i++){
		if(sel[i].value == nom_pais){
			sel[i].selected = true;
			return true;
		}
	}
	return false;
}


function eligeParlaAsociado(id){
	/*
	$('parlamentarioAsociado').selectedIndex = 0;
	var sel = $('parlamentarioAsociado');
	for(var i=0;i<sel.length;i++){
		if(sel[i].value == parseInt(id)){
			sel[i].selected = true;
			break;
		}
	}*/
	
	/* nuevo */

	// resetea select de parlamentarioAsociado antes elegir la opcion
	reseteaSelectParlaAsociado();
		
	var sel2 = $('parlamentarioAsociado');
	sel2.options.length=1;

	var all_par = $('lista_parlamentarios');
	var ids_parla_asociados = $('ids_parla_asociados').value.split(';');

	for (var j = 0; j < ids_parla_asociados.length; j++) {
		for (var i = 0; i < all_par.length; i++) {
			if (all_par[i].value == parseInt(ids_parla_asociados[j])) {
				sel2.options[sel2.length] = all_par[i]; //new Option(all_par[i].text, all_par[i].value);
			}
		}
	}

	$('correo_envio').value = "";		
	if ($('parlamentarioAsociado').length == 2) {  // un solo parlamentario asociado
		$('parlamentarioAsociado').size = 2;
		$('parlamentarioAsociado').selectedIndex = 0;
		$('parlamentarioAsociado').disabled = false;
	}
	else if ($('parlamentarioAsociado').length > 2) {  // mas de un parla asociado
		$('parlamentarioAsociado').size = $('parlamentarioAsociado').length;
		$('parlamentarioAsociado').selectedIndex = 0;
		$('parlamentarioAsociado').disabled = false;

	}
	else{  // ningun parla asociado, se muestra la lista completa
		$('parlamentarioAsociado').size = 1;
		$('parlamentarioAsociado').selectedIndex = 0;
		$('parlamentarioAsociado').length = 1;				
		$('parlamentarioAsociado').disabled = false;
	}		
}


function activarSenadorDiputado(valor){
	var camara 				= (valor==1)?"CAMARA":"SENADO";
	var palamentario_back 	= $('parlamentario_back');
	var parlamentario 		= $('parlamentario');

	parlamentario.options.length = 1;

	for (var i = 0; i < palamentario_back.options.length; i++) {
		var opt = palamentario_back.options[i];
		if (opt.getAttribute("camara").toUpperCase() == camara){
			var newOpt = new Option(opt.innerHTML, opt.value);
			parlamentario.options[parlamentario.options.length] = newOpt;
		}
	}
}


function enableHijos(lista){
	for (var i=0; i < lista.length; i++) {
		if (chequea_tipo_obj(lista[i]) == true) {
			lista[i].disabled = false;
		}
	}
}

function disableHijos(lista){
	for (var i=0; i < lista.length; i++) {
		if (chequea_tipo_obj(lista[i]) == true) {
			lista[i].disabled = true;
		}
	}
}

function chequea_tipo_obj(obj){
	tag_name = obj.tagName;
	 
	if (tag_name){
		tag_name = tag_name.toLowerCase();
	}	
	
	if (tag_name=='select' || tag_name=='input'){
		return true;
	}
	else{
		return false;
	}
}

function enable_div_destinatario_servicio(){
	$('id_destinatario_servicio').disabled = false;
	var radios = document.getElementsByName('indicador_demanda_oferta');
    for (var i = 0; i < radios.length; i++) {
		radios[i].disabled = false;
	}	
}

function muestra_div_destinatario_servicio(){
	var identif_usuario = $('contacto1');
	if (identif_usuario.value != '') {
		$('div_destinatario_servicio').style.display = "block";
	}
	
	
}

function activaComision(check_value){
	var comision_back 	= $('comision_back');
	var comision 		= $('comision');
	
	comision.length = 1;
	
	for(var i=0; i<comision_back.options.length;i++){
		var tipo = comision_back.options[i].getAttribute("tipo");
		if (tipo.toLowerCase() == check_value.toLowerCase()){
			var option = new Option(comision_back.options[i].innerHTML,comision_back.options[i].getAttribute("value"));		
			comision.options[comision.options.length] = option;
		}
	}	
	/*
	if (check_value == 'senado') {
		document.getElementById('comision_senado').style.display = 'block';
		document.getElementById('comision_senado').disabled = false;	
		document.getElementById('comision_camara').style.display = 'none';
		document.getElementById('comision_camara').disabled = true;
	}
	else {
		document.getElementById('comision_camara').style.display = 'block';
		document.getElementById('comision_camara').disabled = false;
		document.getElementById('comision_senado').style.display = 'none';
		document.getElementById('comision_senado').disabled = true;		
	}*/
}


function modificaOptionsSelectDestServ(){
	var select = $('id_destinatario_servicio');
	var institucion = $('institucion');
	
	if (institucion.value == ''){
		return;
	}
	
	for (var i=0; i<select.options.length;i++){
		
		if (institucion.value.toLowerCase() == 'bcn') {
			// si es 'FuncionarioBCN', se modifica la opcion y se elimina la siguiente que es 'FuncionarioCongreso'
			if (select.options[i].text == 'FuncionarioBCN') {
				select.options[i].text = 'Funcionario BCN';
				select.options[i].value = '6';
				select.options[i + 1] = null;
				continue;
			}
			// si ya se cambio y es 'Funcionario Congreso', solo se modifica la opcion
			if (select.options[i].text == 'Funcionario Congreso') {
				select.options[i].text = 'Funcionario BCN';
				select.options[i].value = '6';
				continue;
			}			
		}
		
		if (institucion.value.toLowerCase() != 'bcn'){
			// si es 'FuncionarioCongreso', se modifica la opcion y se elimina la anterior que es 'FuncionarioBCN'
			if (select.options[i].text == 'FuncionarioCongreso') {
				select.options[i].text = 'Funcionario Congreso';
				select.options[i].value = '7';
				select.options[i - 1] = null;
				continue;
			}
			// si ya se cambio y es 'Funcionario BCN', solo se modifica la opcion
			if (select.options[i].text == 'Funcionario BCN') {
				select.options[i].text = 'Funcionario Congreso';
				select.options[i].value = '7';
				continue;
			}						
		}		
	}
}

function reseteaSelectParlaAsociado(){
	// resetea select de parlamentarioAsociado antes elegir la opcion
	respaldo_all_par = $('respaldo_lista_parlamentarios');
	all_par = $('lista_parlamentarios');
	sel = $('parlamentarioAsociado');
	for (var i = 0; i < respaldo_all_par.length; i++) {
		all_par.options[i] = new Option(respaldo_all_par[i].text, respaldo_all_par[i].value);
		all_par.options[i].setAttribute("camara", respaldo_all_par[i].getAttribute("camara"));
		all_par.options[i].setAttribute("correo", respaldo_all_par[i].getAttribute("correo"));		
		sel.options[sel.length] = new Option(respaldo_all_par[i].text, respaldo_all_par[i].value);
		sel.options[i].setAttribute("camara", respaldo_all_par[i].getAttribute("camara"));
		sel.options[i].setAttribute("correo", respaldo_all_par[i].getAttribute("correo"));		
	}
}		


function restringePorInstitucion(){
		select = $('institucion');
		if (select.value == 'BCN') {
			$('parlamentarioAsociado').selectedIndex = 0;
			$('parlamentarioAsociado').options.length = 1;
			$('parlamentarioAsociado').disabled = true;
			$('botones_parla_asociado').disabled = true;
			$('lista_parlamentarios').disabled = true;
			$('areaBcn').disabled = false;
			$('clasif_Funcionario').disabled = false;
			$('tipoAtencion').value = '2';
			if ($F('edicionActivaDesactiva') == 'activada') {
				$('botones_parla_asociado').style.display = 'none';
				$('lista_parlamentarios').style.display = 'none';
			}
		}
		else {
			$('areaBcn').selectedIndex = 0;
			$('areaBcn').disabled = true;
			$('clasif_Funcionario').selectedIndex = 0;
			$('clasif_Funcionario').disabled = true;
			$('parlamentarioAsociado').selectedIndex = 0;
			$('parlamentarioAsociado').disabled = false;
			$('botones_parla_asociado').disabled = false;
			$('lista_parlamentarios').disabled = false;
			$('tipoAtencion').value = '1';
			if ($F('edicionActivaDesactiva') == 'activada') {
				$('botones_parla_asociado').style.display = '';
				$('lista_parlamentarios').style.display = '';
			}
		}
}

function desabilita_region(){
	if ($('pais').value == 'Chile' || $('pais').value == -1){
		$('tr_region').style.display = '';
	}	
	else{
		$('region').selectedIndex = 0;
		$('tr_region').style.display = 'none';
	}
}


function clasifica_contacto(obj){
	var consulta 	 = $("esConsulta");
	var queja 	 	 = $("esQueja");
	var satisfaccion = $("esSatisfaccion");
	
	$("la_consulta").disabled = true;
	if (consulta.checked){
		$("la_consulta").disabled = false;
	}else{
	}
	if (satisfaccion.checked){
		$("la_consulta").disabled = false;
		(!queja.checked)?$('felicitacion_10').checked = true:'';
	}else{
	}
	if (queja.checked){
		$("label_queja").style.display = "";
		if (obj.id == "esQueja"){
			$("la_consulta").disabled = true;
		}
	}else{
		$("label_queja").style.display = "none";
		limpia_radios("tipo_queja");
	}

/*	if (obj.value == 'Consulta') {
		$("label_consulta").style.display = "";
		$("label_satisfaccion").style.display = "none";
		$("label_queja").style.display = "none";
		$("la_consulta").disabled = false;
	}
	else {
		$("la_consulta").disabled = true;
		if (obj.value == 'Queja') {
			$("label_consulta").style.display = "none";
			$("label_satisfaccion").style.display = "none";
			$("label_queja").style.display = "";
			$("otra_queja").style.display = "none";
			limpia_radios("tipo_queja");
		}
		else {
			if (obj.value == 'Satisfaccion') {
				$("label_consulta").style.display = "none";
				$("label_queja").style.display = "none";
				$("label_satisfaccion").style.display = "";
				limpia_radios("tipo_queja");
				$("la_consulta").disabled = false;
				$('felicitacion_10').checked = true;
			}
		}
	}
	*/
}
function clasifica_queja(obj){
	$("la_consulta").disabled = false;
	if (obj.value == '6'){
		$("otra_queja").style.display = "";
		$("otra_queja").value = "";
	}
	else{
		$("otra_queja").style.display = "none";
	}
}

function limpia_radios(radio_name){
	elements = document.getElementsByName(radio_name);
	for (var i=0; i<elements.length; i++){
		elements[i].checked = false;
		elements[i].disabled = false;
	}	
}

function checkEsQueja(){
	$("esConsulta").disabled = false;
	$("esQueja").disabled = false;

	if ($("activaQueja").value == 1){
		$("esQueja").checked = true;
		clasifica_contacto($("esQueja"));
		$('contacto1').value = $('usuario').value;
		$('contacto1').focus();
		$("esQueja").focus();
	}
}

function restringe_caracteres(obj,e) {
	var texto = obj.value;
	if ($('esQueja').checked){
		var largo_max = 250;
	}else{
		var largo_max = 4000;
	}
	var texto_length = texto.length + 1;
	if (texto_length > largo_max ) { 
		if (navigator.appName == "Netscape") {
			var tecla = e.which
		}
		else {
			var tecla = e.keyCode
		}
		if (tecla != 8) {
			alert("Cantidad máxima de caracteres");
			obj.value = obj.value.substring(0,largo_max);
			return false
		}
	}

	var x   = largo_max  - texto_length;
	var msg = "Quedan "+x+" caracteres";
	$('cantidad_caracteres').innerHTML = msg;
	
	return true 
} 
function changePaisByRegion(region){
	if (region == 0){
		$('pais').value = "Extranjero";
	}else{
		$('pais').value = "Chile";
	}
}

