var aux = null;
var c = 9;
function showHide(id) {

	var obj = document.getElementById(id);
 	var objold = document.getElementById(aux);
   	var obj_imagem = document.getElementById('ico_'+id);
	var obj_imagem_old = document.getElementById('ico_'+aux);
	
	 if(obj.style.display == "inline") {
		  obj.style.display = "none";		  
		  if (obj_imagem) 
		  {
		  	obj_imagem.src = "imagem/ico_mais.gif";
		  }
		  aux = id;
	 } else {
		  obj.style.display = "inline";
		  if (obj_imagem) 
		  {
		  	obj_imagem.src = "imagem/ico_menos.gif";
		  }
	  if (objold != null && objold != obj){
		   objold.style.display = "none";
		   if (obj_imagem_old) 
		  {
		   obj_imagem_old.src = "imagem/ico_mais.gif";
		  }
	  }
	  aux = id;
	 }
 
}

//VALIDA CPF
function valida_cpf(obj,num) 
{ 
	var cpf = obj.value;
	var numeros, digitos, soma, i, resultado, digitos_iguais,tam; 
	digitos_iguais = true; 
	if (cpf.length < 11) 
	{
		tam = cpf.length;
		for (i = 0; i < 11 - tam; i++) 
			cpf = '0'+cpf;
	}
	obj.value = cpf;
	for (i = 0; i < cpf.length - 1; i++) 
		if (cpf.charAt(i) != cpf.charAt(i + 1)) 
			  { 
				  digitos_iguais = false; 
				  break; 
			  } 
	
	if (cpf == '00000000000') 
	{
		document.getElementById('erro'+num).style.display = "inline";
		return false;	
	}	  
	
	if (!digitos_iguais) 
		{ 
			numeros = cpf.substring(0,9); 
			digitos = cpf.substring(9); 
			soma = 0; 
			for (i = 10; i > 1; i--) 
				soma += numeros.charAt(10 - i) * i; 
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
			if (resultado != digitos.charAt(0)) 
			{
				  document.getElementById('erro'+num).style.display = "inline";
				  return false; 
			}
			numeros = cpf.substring(0,10); 
			soma = 0; 
			for (i = 11; i > 1; i--) 
				soma += numeros.charAt(11 - i) * i; 
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
			if (resultado != digitos.charAt(1)) 
			{ 
				  document.getElementById('erro'+num).style.display = "inline";
				  return false; 
			}
			return true; 
		} 
	else{
		
		document.getElementById('erro'+num).style.display = "inline";		
		return false;
	}
}
//FIM VALIDA CPF

//VALIDA CNPF
function valida_cnpj(obj,num) 
{ 
	var cnpj = obj.value;
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais,tam; 
	digitos_iguais = true; 
	if (cnpj.length < 14 && cnpj.length < 15) 
	{
		tam = cnpj.length;
		for (i = 0; i < 14 - tam; i++) 
			cnpj = '0'+cnpj;
	} 
	obj.value = cnpj; // conserta e exibe o cnpj no campo texto
	for (i = 0; i < cnpj.length - 1; i++) 
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)) 
		{ 
			  digitos_iguais = false; 
			  break; 
		} 
	if (cnpj == '00000000000000') 
	{
	  //document.form.erro.value = "1";
	  document.getElementById('erro'+num).style.display = "inline";
	  return false;	
	}	  
	
	if (!digitos_iguais) 
	{ 
		tamanho = cnpj.length - 2 
		numeros = cnpj.substring(0,tamanho); 
		digitos = cnpj.substring(tamanho); 
		soma = 0; 
		pos = tamanho - 7; 
		for (i = tamanho; i >= 1; i--) 
		{ 
			  soma += numeros.charAt(tamanho - i) * pos--; 
			  if (pos < 2) pos = 9; 
		} 
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
		if (resultado != digitos.charAt(0)) {
			  //document.form.erro.value = "1";
			  document.getElementById('erro'+num).style.display = "inline";
			  return false; } 
		tamanho = tamanho + 1; 
		numeros = cnpj.substring(0,tamanho); 
		soma = 0; 
		pos = tamanho - 7; 
		for (i = tamanho; i >= 1; i--) 
		{ 
			  soma += numeros.charAt(tamanho - i) * pos--; 
			  if (pos < 2) pos = 9; 
		} 
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
		if (resultado != digitos.charAt(1)) 
		{ 
			  //document.form.erro.value = "1";
			document.getElementById('erro'+num).style.display = "inline";
			return false; 
		}
            return true;
		} 
		else{
			document.getElementById('erro'+num).style.display = "inline";
			return false; 
	}
} 
//FIM VALIDA CNPJ

//VALIDA_TÍTULO DE ELEITOR
//função recursiva para o calculo do dígito verificador, faz a verificação um de cada vez
//variável c recebe sempre 9 para calculo do título de eleitor
function valida_titulo(titulo,c)
{

	if (titulo.length-1 == 0) return titulo.substring(0)*c;

	return ((titulo.substring(titulo.length-1)*c+ valida_titulo(titulo.substring(0,titulo.length-1),c-1))%11);   

}

function recebe_titulo(titulo){	
						   
	//completa o titulo com 0's a esquerda para o calculo

    if (titulo.length >=5){
        while (titulo.length < 12) {titulo = "0"+titulo;}
        if (
            (titulo.substring(titulo.length-2)) ==
            (valida_titulo(titulo.substring(0,titulo.length-4),c)%10+''+valida_titulo(titulo.substring(titulo.length-4,titulo.length-1),c)%10)
           )
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

//FIM VALIDA_TÍTULO DE ELEITOR

//PESQUISA POR TITULO DE ELEITOR
function localiza_titulo(titulo,captcha)
{
	document.getElementById('erro').style.display = "none";
	
    (recebe_titulo(titulo))? window.open('pages/utm_mapa.jsp?titulo='+titulo+'&captcha='+captcha,'nova','width=752,height=552, resizable=yes, scrollbars=no') : document.getElementById('erro').style.display = "inline";
	return false;
}
//FIM PESQUISA POR TITULO DE ELEITOR

//PESQUISA POR ZONA E SEÇÃO
function localiza_Zona_Secao(zona,secao,captcha)
{
	if ((zona != null) && (secao != null) && (captcha != null))
	{
		window.open('pages/utm_mapa.jsp?zona='+zona+'&secao='+secao+'&captcha='+captcha,'nova','width=752,height=552,resizable=yes, scrollbars=no');
	}else
	{
		return false;
	}
}
//FIM PESQUISA ZONA SEÇÃO

//PESQUISA POR LOCAL DE VOTAÇÃO
function localiza_local_votacao(zona,codigo_lv,cod_munic,captcha){
    if((zona != null) && (codigo_lv != 0) && (captcha != null)){
        window.open('pages/utm_mapa.jsp?zona='+zona+'&codigo_lv='+codigo_lv+'&cod_munic='+cod_munic+'&captcha='+captcha,'nova','width=752,height=552,resizable=yes, scrollbars=no');
    }    
}
//FIM PESQUISA LOCAL_VOTACAO


//FILTRA CARACTERES DIGITADOS

function trataLabelTitulo(obj)
{
	obj.value='';
	obj.maxLength=12;	
}


function pegaTecla(e)
{
	var tecla;
	
	
	//var erTitulo = /\d|[\b]/; //expressão regular que filtra qq tecla não seja numero positivo ou backspace
	//var erTitulo = /x08|\d+/; //expressão regular que filtra qq tecla não seja numero positivo ou backspace
	var teclaEnter = /\x0D/; // ENTER
	var teclaBackspace = /[\b]/;
	var teclaNumero = [0,1,2,3,4,5,6,7,8,9];
	
	//if (window.event) tecla = window.event.keyCode;
	if (window.event)//IE
	{
		tecla = e.keyCode; 
		teclaChar = String.fromCharCode(tecla);		
	}
	else if (e.which) //Netscape/Firefox/Opera
	{
		tecla = e.which; 
		teclaChar = String.fromCharCode(tecla);			
	}
	
	if ( teclaNumero.join().indexOf(teclaChar) >= 0 )
	{
		return true;
	}/*else if (teclaEnter.test(teclaChar)) //libera ENTER
	{
		var obj = document.getElementById('localizar');
		obj.onclick();
		return false;
	//}else if (tecla == 8)
	}*/else if (teclaBackspace.test(teclaChar))
	{
		return true;
	}else
	{
		return false;
	}	
}

//###################   percorre XML para preenchimento de combo 13/03/2008       #################

// permission is granted to use this javascript provided that the below code is not altered

function xmlLoader(url){
 
    if(window.XMLHttpRequest){
        var Loader = new XMLHttpRequest();
        Loader.open("GET", url ,false);
        Loader.send(null);
        return Loader.responseXML;
    }else if(window.ActiveXObject){
        var Loader = new ActiveXObject("Msxml2.DOMDocument.3.0");
        Loader.async = false;
        Loader.load(url);
        return Loader;
    }
}


function xmlArvore(xmlNode,no,atributo_pai,vetor_combo)
{
    var s = xmlNode.getElementsByTagName(no);
    //no --> nodo que será retornado
    //atributo_pai --> É o atributo do nodo pai do nodo "no"
    x = 0;
    var child = null;
    

    if (atributo_pai != null)//caso o nodo pai tenha atributo
    {
        s = s[0].parentNode;        
        child = s.parentNode;
        child = child.childNodes;
        var i = 0;
        while (i < child.length )
        {            
            if (child[i].attributes[0].nodeValue == atributo_pai){
                s = child[i];
                s = s.childNodes;
                i = s.length; //somente para sair do while
            }
        //child = s.nextSibling;//pega o proximo nodo
        i++;
        }
        
    }else //quando o nodo pai não tem atributo basta subir um nivel e listar todos os nodos abaixo dele
    {           
        s = s[0].parentNode; //pega o nodo pai, faço isso pq para varrer todos os nodos correndentes tenho que pegar a partir do nodo pai (sobe um nivel)
        s = s.childNodes;
    }

    for(var i=0;i<s.length;i++)//percorrendo os filhos do nó
    {         
        child = s[i];          
        if (child.nodeType == 1)
        {	            
            vetor_combo[x++] = child.attributes[0].nodeValue;
        }
     
    }

    
}



function monta_combo(url,no,atributo,nome,acao,div_retorno){
    //url           --> endereço onde se enconta o arquivo XML.
    //no            --> nodo que será exibido no combo
    //atributo      --> atributo do nodo pai
    //nome          --> nome de exibição
    //acao          --> conteudo do evento onChange
    //div_retorno   --> div que sera populada pelo combo
    var str = "";
    
    if (url != null) 
    {
        var vetor_combo = new Array();//vetor que ira guardar os registros que irão preencher o combo
        //var x = 0;
        var xml = xmlLoader(url);//xmlLoader É o arquivo XML para ser manipulado
        xmlArvore(xml,no,atributo,vetor_combo);        
        str = '<select onchange="'+acao+'" id="'+no+'" name="'+no+'">';
        str += '<option selected="" value="0">.:'+nome+':.</option>';
    
        for (var i=0;i < vetor_combo.length;i++){
            str += '<option value="'+vetor_combo[i]+'">'+vetor_combo[i]+'</option>';
        }    
        str += '</select>';
        
    }
    else
    {
        str = '<select onchange="" id="'+no+'" name="'+no+'">';
        str += '<option selected="" value="0">.:'+nome+':.</option>';
        str += '</select>';
    }
    document.getElementById(div_retorno).innerHTML = str;    
}
//##############################################################################################


//###funcao usada em UTM.jsp######################

function executa_pesquisa()
    {   
        
        var achei;
        var len =  $("input[name='tipoConsulta']").length;
        var zona = null;
        var secao = null;
        var cod_lv_munic = null;
        
        for (var i=0; i<len; i++){            
          if($("input[name='tipoConsulta']")[i].checked){
              achei = i;            
          }
        }
        
        var captcha = document.getElementById('text_captcha');
        
        if (achei == 0){//se for por titulo
            for (i=document.getElementById('titulo').value.length;i<=11;i++) {
                document.getElementById('titulo').value = '0'+ document.getElementById('titulo').value;
            }
              var titulo = document.getElementById('titulo');              

            localiza_titulo(titulo.value,captcha.value);
            
        }else if (achei == 1){ //se for por zona secao           
            zona = document.getElementById('zona');
            secao = document.getElementById('secao'); 
            
            localiza_Zona_Secao(zona.value,secao.value,captcha.value);
            
        }else if (achei == 2){ //se for por local votacao
            zona = document.getElementById('zona');
            cod_lv_munic = document.getElementById('cod_lv_munic');
            cod_lv_munic = cod_lv_munic.value;//recebe o value do objeto
            
            var vetzonaMunicipio = new Array();
            vetzonaMunicipio= cod_lv_munic.split(":");
            
            localiza_local_votacao(zona.value,vetzonaMunicipio[0],vetzonaMunicipio[1],captcha.value);  
      }  
    }

 //###############################################################################################
