/* *********************************************************************************************************
 * FUNÇÃO         = void setarFocu()
 * AUTOR          = Samuel Novais Moura Júnior
 * OBJETIVO       = Seta um focu no campo passado por parametro
 ********************************************************************************************************* */
function setarFocu(obj){
	document.getElementById(obj).focus();	
}

/* *********************************************************************************************************
 * FUNÇÃO         = void fecharJanela()
 * AUTOR          = Samuel Novais Moura Júnior
 * OBJETIVO       = Abre uma nova janela apenas com a barra de ferramentas e as barras de rolagem
 * EXEMPLO DE USO = abrirJanela("Endereço da página", "Comprimento", "Largura", "Nome da janela");
 * - O Endereço da página é o unico parametro obrigatório.
********************************************************************************************************* */
function fecharJanela(){
	window.close();	
}

/* *********************************************************************************************************
 * FUNÇÃO         = void abrirJanela(url, width, height, name)
 * AUTOR          = Samuel Novais Moura Júnior
 * OBJETIVO       = Abre uma nova janela apenas com a barra de ferramentas e as barras de rolagem
 * EXEMPLO DE USO = abrirJanela("Endereço da página", "Comprimento", "Largura", "Nome da janela");
 * - O Endereço da página é o unico parametro obrigatório.
********************************************************************************************************* */
function abrirJanela(url, width, height, name){
    var horizontal  = window.screen.availWidth;
    var vertical    = window.screen.availHeight;
    var comprimento = 800;
    var altura      = 500;
    var nome	    = "x";

    if(width != null && height != null) {
      comprimento = width;
      altura      = height;
    }

    if(name != null) {
      nome = name;
    }

    var x = window.open(url,nome," resizable=yes,scrollbars=yes,width="+ comprimento + ",height=" + altura);

    horizontal = Math.round((horizontal - comprimento) / 2);
    vertical   = Math.round((vertical   - altura) / 2);

    x.moveTo(horizontal, vertical);
    x.focus();

  }
/* *********************************************************************************************************
 * FUNÇÃO         = MascararData(data)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Atribuir as barras quando o usuário digitar uma data.
 ********************************************************************************************************* */
function mascararData(obj){
	obj.style.backgroundColor='white';
	var strObj = obj.value;
	//bloqueia_nao_numerico();
	if(obj.value.length==2){obj.value=obj.value + '/';}
	if(obj.value.length==5){obj.value=obj.value + '/';}
}
/* *********************************************************************************************************
 * FUNÇÃO         = boolean eDataValida(Str)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Verifica se a String passada como parametro é uma dada valida - formato dd/mm/yyyy.
 * EXEMPLO DE USO = if(!eDataValida("12/12/2001")){ alert("Data inválida"); return false;}
********************************************************************************************************* */
function eDataValida(Str) {

    vlraux = trim(Str.value);
    if ((vlraux == "") || (vlraux.length != 10) ||
       (vlraux.charAt(2) != "/") || (vlraux.charAt(5)!= "/")){
       return false;
    }

    dia = parseInt(vlraux.substring(0,2),10);
    mes = parseInt(vlraux.substring(3,5),10);
    ano = parseInt(vlraux.substring(6,10),10);
	
	
    if (isNaN(dia) || isNaN(mes) || isNaN(ano) || (mes < 1) || (mes > 12) || (dia < 1)) {
      alert("Data inválida");
      Str.value = "";
      return false;
    }
		 hoje = new Date();
         anoAtual = hoje.getFullYear();

	if(ano < 1850){
		alert("Data < que 1850");
      	Str.value="";
		return false;
	}

    tabmes = "312831303130313130313031";
	if ((dia == 29) && (mes == 2)){
      if ((ano == 0) || ((ano % 4) != 0)){
      	alert("Data inválida");
      	Str.value="";
        return false;
      }else{ 
	  	return true;
		}
    }

    k = (mes * 2 - 2);
    if (dia > tabmes.substring(k,k + 2)){
    	alert("Data inválida");
     	Str.value="";	
       	return false;
    }else{
		return true;
	}
	


   return false;
}




function eDataValidan(Str) {

    vlraux = trim(Str.value);
    if ((vlraux == "") || (vlraux.length != 10) ||
       (vlraux.charAt(2) != "/") || (vlraux.charAt(5)!= "/")){
       return false;
    }

    dia = parseInt(vlraux.substring(0,2),10);
    mes = parseInt(vlraux.substring(3,5),10);
    ano = parseInt(vlraux.substring(6,10),10);
	
	
    if (isNaN(dia) || isNaN(mes) || isNaN(ano) || (mes < 1) || (mes > 12) || (dia < 1)) {
      alert("Data inválida");
      Str.value = "";
      return false;
    }
		 hoje = new Date();
         anoAtual = hoje.getFullYear();

	if(ano < anoAtual){
		alert("Data deve ser >= do que a data atual");
      	Str.value="";
		return false;
	}

    tabmes = "312831303130313130313031";
	if ((dia == 29) && (mes == 2)){
      if ((ano == 0) || ((ano % 4) != 0)){
      	alert("Data inválida");
      	Str.value="";
        return false;
      }else{ 
	  	return true;
		}
    }

    k = (mes * 2 - 2);
    if (dia > tabmes.substring(k,k + 2)){
    	alert("Data inválida");
     	Str.value="";	
       	return false;
    }else{
		return true;
	}
	


   return false;
}

function eDataValidad(Str) {

    vlraux = trim(Str.value);
    if ((vlraux == "") || (vlraux.length != 10) ||
       (vlraux.charAt(2) != "/") || (vlraux.charAt(5)!= "/")){
       return false;
    }

    dia = parseInt(vlraux.substring(0,2),10);
    mes = parseInt(vlraux.substring(3,5),10);
    ano = parseInt(vlraux.substring(6,10),10);
	
	
    if (isNaN(dia) || isNaN(mes) || isNaN(ano) || (mes < 1) || (mes > 12) || (dia < 1)) {
      alert("Data inválida");
      Str.value = "";
      return false;
    }
		 hoje = new Date();
         anoAtual = hoje.getFullYear();

	if(ano > anoAtual){
		alert("Ano superior ao ano atual");
      	Str.value="";
		return false;
	}

    tabmes = "312831303130313130313031";
	if ((dia == 29) && (mes == 2)){
      if ((ano == 0) || ((ano % 4) != 0)){
      	alert("Data inválida");
      	Str.value="";
        return false;
      }else{ 
	  	return true;
		}
    }

    k = (mes * 2 - 2);
    if (dia > tabmes.substring(k,k + 2)){
    	alert("Data inválida");
     	Str.value="";	
       	return false;
    }else{
		return true;
	}
	


   return false;
}


function verificaDatas(dtInicial, dtFinal, atual){
   var dtini = document.getElementById(dtInicial).value;
   var dtfim = document.getElementById(dtFinal).value;

 
 if(dtfim != ""){
    if ((dtini == '') && (dtfim == '')) {
        alert('Complete os Campos.');
       // campos.inicial.focus();
        return false;
    }
   
    datInicio = new Date(dtini.substring(6,10),
                         dtini.substring(3,5),
                         dtini.substring(0,2));
    datInicio.setMonth(datInicio.getMonth() - 1);
   
   
    datFim = new Date(dtfim.substring(6,10),
                      dtfim.substring(3,5),
                      dtfim.substring(0,2));
                     
    datFim.setMonth(datFim.getMonth() - 1);

    if(datInicio <= datFim){
        return true;
    } else {
        document.getElementById(atual).value = "";
		alert('ATENÇAO: Data Inicial é maior que Data Final');
       // document.all.campos.final.focus();
       // document.all.campos.final.select();
		
        return false;
    } }  
}


/* *********************************************************************************************************
 * FUNÇÃO         = MascararCPF(CPF)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Formatar CPF 111.111.111-00
********************************************************************************************************* */
function mascararCPF(obj){
	obj.style.backgroundColor='white';
	var strObj = obj.value;
	//bloqueia_nao_numerico();
	if(obj.value.length==3){obj.value=obj.value + '.';}
	if(obj.value.length==7){obj.value=obj.value + '.';}
	if(obj.value.length==11){obj.value=obj.value + '-';}
}

/* *********************************************************************************************************
 * FUNÇÃO         = boolean bloqueia_nao_numerico()
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Não permiti a digitação de alfa no campo
********************************************************************************************************* */
function bloqueia_nao_numerico(){
	if(event.keyCode < 48 || event.keyCode > 57){
		event.keyCode = 0;
		return false;
	}else{
		return true;
	}
}
/* *********************************************************************************************************
 * FUNÇÃO         = boolean eNumero(Char)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Veriica se o caracter passado como parametro é um numero.
 * EXEMPLO DE USO = var numero = "123a456";
 *                  if(!eNumero(numero.charAt(3))){ alert("O caracter não é um número");}
********************************************************************************************************* */
function eNumero(Char){
  numeros = "0,1,2,3,4,5,6,7,8,9";
  arrayNumeros = numeros.split(",");
  for(i=0; i < arrayNumeros.length; i++){
   if(Char == arrayNumeros[i]){
     return true;
   }
  }
  return false;
}
/* *********************************************************************************************************
 * FUNÇÃO         = boolean eNumerico(Str)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Veriica se a String passada como parametro é um numero.
 * EXEMPLO DE USO = var numero = "123a456";
 *                  if(!eNumerico(numero)){ alert("A String não é um número");}
********************************************************************************************************* */
function eNumerico(Valor){
  for(j=0; j < Valor.length; j++){
    if(!eNumero(Valor.charAt(j))){
      return false;
    }
  }
  return true;
}
/* *********************************************************************************************************
 * FUNÇÃO         = boolean eCpfValido(Str)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Verifica se a String passada como parametro é um CPF válido -formato- 999.999.999-99
 * EXEMPLO DE USO = if(!eCpfValido("999.999.999-99")){ alert("CPF inválido"); return false;}
********************************************************************************************************* */
function eCpfValido(Str){
	if(Str.value != ""){
	  	var CPF  =  retiraCaracteresSeparacao(Str.value);
	    if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
	            CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
	            CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
	            CPF == "88888888888" || CPF == "99999999999"){
				alert("CPF inválido.");
				Str.value = "";
	            return false;
		}
	    soma = 0;
	    for (i=0; i < 9; i ++)
	            soma += parseInt(CPF.charAt(i)) * (10 - i);
	    resto = 11 - (soma % 11);
	    if (resto == 10 || resto == 11)
	            resto = 0;
	    if (resto != parseInt(CPF.charAt(9))){
			alert("CPF inválido.");
			Str.value = "";
			return false;
		}
	    soma = 0;
	    for (i = 0; i < 10; i ++)
	            soma += parseInt(CPF.charAt(i)) * (11 - i);
	    resto = 11 - (soma % 11);
	    if (resto == 10 || resto == 11)
	            resto = 0;
	    if (resto != parseInt(CPF.charAt(10))){
			alert("CPF inválido.");
			Str.value = "";
			return false;
		}
	    return true;
	}
}
/* *********************************************************************************************************
 * FUNÇÃO         = String retiraCaracteresSeparacao(Str)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Retirar caracteres de separação de uma String, ("/", "-", ".", ",", ";", "|", " ", "\", ":", "(", ")").
 * EXEMPLO DE USO = "12122001" = retiraCaracteresSeparacao("12-12.2001");
********************************************************************************************************* */
function retiraCaracteresSeparacao(Str) {
  var s = "";
  var espaco = "X X";
  Str = trim(Str);
  for (i = 0; i < Str.length ; i++) {
    if (Str.charAt(i) != "/" && Str.charAt(i) != "-" && Str.charAt(i) != "."  && Str.charAt(i) != "," &&
        Str.charAt(i) != ";" && Str.charAt(i) != "|" && Str.charAt(i) != espaco.charAt(1) && Str.charAt(i) != "\\" &&
        Str.charAt(i) != ":" && Str.charAt(i) != "(" && Str.charAt(i) != ")"){
      s = s + Str.charAt(i);
    }
  }

 return s;
}
/* *********************************************************************************************************
 * FUNÇÃO         = String trim(Str)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Remove espaço do começo e fim da string.
 * EXEMPLO DE USO = "teste de função" == trim(" teste de função ");
********************************************************************************************************* */
function trim(Str) {
      inicio = 0;
      fim =  Str.length - 1;
	  emBranco = true;

      for (i = 0; i < Str.length; i++) {
        if (Str.charAt(i) != " ") {
          inicio = i;
	    emBranco = false;
          break;
        }
      }

      for(j = fim; j > -1; j--){
        if (Str.charAt(j) != " ") {
          fim = j;
	    emBranco = false;
          break;
        }
      }

     if(emBranco)return "";

     if(inicio == 0 && 
	fim == (Str.length - 1) && 
	inicio != fim &&
	Str.substring(inicio, fim+1).length != Str.length){

  	return "";
     }

      return Str.substring(inicio, fim+1);
}
/* *********************************************************************************************************
 * FUNÇÃO         = boolean validaEmail(Campo)
 * AUTOR          = Samuel Novais
 * OBJETIVO       = Verifica se o campo de email está no formato nome@nome.nome
 * EXEMPLO DE USO =
 * <input type="text" name="campo" value="" onBlur="JavaScript: validaEmail(this);">
********************************************************************************************************* */

function validaEmail(campo){
	var ponto      = false;
	var arroba     = false;
	campo.value = campo.value.toLowerCase();
    for (var i=0; i < campo.value.length; i++) {
		if(campo.value.substring(i, i+1)=='.')
			ponto = true;
		if((arroba==false) && (campo.value.substring(i, i+1)=='@') )
			arroba = true;
		else if((arroba) && (campo.value.substring(i, i+1)=='@') )
			arroba = false;
		if(campo.value.substring(campo.value.length - 1, campo.value.length)=='.')
			ponto = false;
	}
	if( ( (ponto && arroba)) || (campo.value=='') )
		return true;
	else{
		alert('Formato de Email Inválido!');
		campo.value="";
		campo.focus();
	 	return false;
	}

}
/* *********************************************************************************************************
 * FUNÇÃO         = void formataTelFax(Campo, Prefixo)
 * AUTOR          = Samuel Júnior
 * OBJETIVO       = Formata o valor do campo para o formato "(999) 9999-9999"
 * EXEMPLO DE USO =
 * <input type="text" name="campoTel" value="" onBlur="JavaScript: formataTel(this);"> 9999-9999
 * <input type="text" name="campoTel" value="" onBlur="JavaScript: formataTel(this, 1);"> (99) 9999-9999
********************************************************************************************************* */
function formataTel(Campo, Prefixo){
  if (Campo.value != "") {
    var numero = retiraCaracteresSeparacao(Campo.value);

    if(!eNumerico(numero)){
      //Campo.style.backgroundColor='#c1dcfd';
      alert("Numero de telefone inválido");
      Campo.value = "";
      Campo.focus();
      return false;
    }

    if (Prefixo == null) {
      if(numero.length < 7 || numero.length > 8){
       // Campo.style.backgroundColor='#c1dcfd';
        alert("Numero de telefone inválido");
        Campo.value = "";
        Campo.focus();
        return false;
      }

      if(numero.length == 7){
        Campo.value = numero.substring(0, 3) +"-"+ numero.substring(3, 7);
      }

      if(numero.length == 8){
        Campo.value = numero.substring(0, 4) +"-"+ numero.substring(4, 8);
      }

    }
    else {
      if(numero.length < 10 || numero.length > 11){
        //Campo.style.backgroundColor='#c1dcfd';
        alert("Numero de telefone inválido");
        Campo.value = "";
        Campo.focus();
        return false;
      }
    }
  }
}
/* *********************************************************************************************************
 * FUNÇÃO         = MascaraTel(Campo)
 * AUTOR          = Samuel Júnior
 * OBJETIVO       = Formata o valor do campo para o formato "(99) 9999-9999"
 * EXEMPLO DE USO =
 * <input type="text" name="campoTel" value="" onKeypress="JavaScript: MascaraTel(this);">
********************************************************************************************************* */
function MascaraTel(obj){
	obj.style.backgroundColor='white';
	var strObj = obj.value;
	//bloqueia_nao_numerico();
	if(obj.value.length==1){obj.value= "(" + obj.value;}
	if(obj.value.length==3){obj.value= obj.value + ')';}
	if(obj.value.length==8){obj.value= obj.value + '-';}
	
}




function v_NR(tecla)

{

if(typeof(tecla) == 'undefined')

var tecla = window.event;

var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);



// permite números, 8=backspace, 46=del e 9=tab

if ( (codigo >= 48 && codigo <= 57) || (codigo >= 96 && codigo <= 105) || codigo == 8 || codigo == 46 || codigo == 9 )

{ return true; }
else
{ alert("Apenas números são permitidos !"); return false; } 

}







//-----> máscara cnpj:

function m_CNPJ(campo,tammax) {



var vr = campo.value;

vr = vr.replace( "-", "" );

vr = vr.replace( "/", "" );

vr = vr.replace( ".", "" );

vr = vr.replace( ".", "" );

var tam = vr.length;



if (tam < tammax) { tam = vr.length + 1 ; }



tam = tam - 1;

if ( (tam > 2) && (tam <= 5) ) {

vr = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ) ; }

if ( (tam >= 6) && (tam <= 8) ) {

vr = vr.substr( 0, tam - 5 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; }

if ( (tam >= 9) && (tam <= 11) ) {

vr = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; }

if ( (tam >= 12) && (tam < 14) ) {

vr = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '/' + vr.substr( tam - 5, 4 ) + '-' + vr.substr( tam - 1, tam ) ; }



campo.value = vr; 

}







//-----> máscara cpf: 

function m_CPF(campo,tammax) {



var vr = campo.value;

vr = vr.replace( "-", "" );

vr = vr.replace( ".", "" );

vr = vr.replace( ".", "" );

var tam = vr.length;



if (tam < tammax) { tam = vr.length + 1; }



tam = tam - 1;

if ( (tam > 2) && (tam <= 11) ) {

vr = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ); }

if ( (tam == 10) ) {

vr = vr.substr( 0, tam - 7 ) + '.' + vr.substr( tam - 7, 3 ) + '.' + vr.substr( tam - 4, tam ); }




campo.value = vr;

}







//-----> máscara cep:

function m_CEP(campo,tammax) {


var vr = campo.value;

vr = vr.replace( "-", "" );

vr = vr.replace( ".", "" );

var tam = vr.length;



if (tam < tammax) { tam = vr.length + 1; }



tam = tam - 1;

if ( (tam > 2) && (tam <= 8) ) {

vr = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ); }

if ( (tam == 7) ) {

vr = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, tam ); }



campo.value = vr;

}







//-----> máscara data:

function m_data(campo,tammax,tecla) {



if(typeof(tecla) == 'undefined') {


var tecla = window.event;




var vr = campo.value;

vr = vr.replace( "/", "" );

vr = vr.replace( "/", "" );

var tam = vr.length;


if (tam < tammax) { tam = vr.length + 1; }


tam = tam - 1;


if ( (tam >= 2) && (tam < 3) ) {  vr = vr.substr( 0, tam - 0 ) + '/' + vr.substr( tam - 0, 2 ); }

if ( (tam >= 3) && (tam < 4) ) {  vr = vr.substr( 0, tam - 1 ) + '/' + vr.substr( tam - 1, 2 ); }

if (tam == 4) { vr = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, 2 ) + '/' + vr.substr( tam - 0, 5 ); }

if (tam == 5) { vr = vr.substr( 0, tam - 3 ) + '/' + vr.substr( tam - 3, 2 ) + '/' + vr.substr( tam - 1, 6 ); }

if (tam == 6) {  vr = vr.substr( 0, tam - 4 ) + '/' + vr.substr( tam - 4, 2 ) + '/' + vr.substr( tam - 2, 7 ); }

if (tam == 7) { vr = vr.substr( 0, tam - 5 ) + '/' + vr.substr( tam - 5, 2 ) + '/' + vr.substr( tam - 3, 8 ); }


campo.value = vr;

}
}






//-----> máscara hora:

function m_HORA(campo,tammax,tecla) {



if(typeof(tecla) == 'undefined')

var tecla = window.event;

var codigo = (tecla.which ? tecla.which : tecla.keyCode ? tecla.keyCode : tecla.charCode);



var vr = campo.value;

vr = vr.replace( ":", "" );

vr = vr.replace( ":", "" );

var tam = vr.length;



if (tam < tammax) { tam = vr.length + 1; }

if (codigo == 5) { tam = tam - 1; }




tam = tam - 1;

if ( (tam >= 2) && (tam < 3) ) {

vr = vr.substr( 0, tam - 0 ) + ':' + vr.substr( tam - 0, 2 ); }

if ( (tam >= 3) && (tam < 4) ) {

vr = vr.substr( 0, tam - 1 ) + ':' + vr.substr( tam - 1, 2 ); }

if (tam == 4) {

vr = vr.substr( 0, tam - 2 ) + ':' + vr.substr( tam - 2, 2 ) + '' + vr.substr( tam - 0, 5 ); }

if (tam == 5) {

vr = vr.substr( 0, tam - 3 ) + ':' + vr.substr( tam - 3, 2 ) + ':' + vr.substr( tam - 1, 6 ); }



campo.value = vr;

}



function buscarCidades(valor) {
      //verifica se o browser tem suporte a ajax
	  
	 
	  try {
         ajax = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e) {
         try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
         }
	     catch(ex) {
            try {
               ajax = new XMLHttpRequest();
            }
	        catch(exc) {
               alert("Esse browser nao tem recursos para uso do Ajax");
               ajax = null;
            }
         }
      }
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		 document.forms[0].cidade.options.length = 0;
		 
		var novo = document.createElement("option");
		novo.setAttribute("id", "opcoes");
		novo.value = "0";
		novo.text  = "Escolha";
		document.forms[0].cidade.options.add(novo);
	     
		 idOpcao  = document.getElementById("opcoes");
		 

		 
	     ajax.open("POST", "index.php?modulo=cidade&acao=listar&cidade="+valor, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }
			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processa(ajax.responseXML);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processa(obj){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("cidade");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	  
	  var novo = document.createElement("option");
		novo.setAttribute("id", "opcoes");
		novo.value = "";
		novo.text  = "";
		document.forms[0].cidade.options.add(novo);
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length ; i++) {
            var item = dataArray[i];
			//contéudo dos campos no arquivo XML
			var idCidade    =  item.getElementsByTagName("idCidade")[0].firstChild.nodeValue;
			var nome =  item.getElementsByTagName("nome")[0].firstChild.nodeValue;
			
	        idOpcao.innerHTML = "--Selecione uma das opçoes abaixo--";
		
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", "opcoes");
				//atribui um valor
			    novo.value = idCidade;
				//atribui um texto
			    novo.text  = nome;
				//finalmente adiciona o novo elemento
				document.forms[0].cidade.options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione o estado --";
	  }	  
   }



function formatar(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
nTecla = evtKeyPress.keyCode; }
else if(document.layers) { // Nestcape
nTecla = evtKeyPress.which;
}

sValue = objForm[strField].value;

// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

if (bolMask) {
sCod += sMask.charAt(i);
mskLen++; }
else {
sCod += sValue.charAt(nCount);
nCount++;
}

i++;
}

objForm[strField].value = sCod;

if (nTecla != 8) { // backspace
if (sMask.charAt(i-1) == "9") { // apenas números...
return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
return true;
} }
else {
return true;
}
}


function limparlistausuarios(){
window.location='http://localhost/servidor/sigweb/index.php?modulo=usuarios&acao=formularioPesquisaUsuario';
}


function testabrowser(){
    try {
        ajax = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch (e) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (ex) {
            try {
                ajax = new XMLHttpRequest();
            } 
            catch (exc) {
                alert("Esse browser nao tem recursos para uso do Ajax");
                ajax = null;
            }
        }
    }
}







function verificarCampo(idaux,id,campo,tabela,valor){

auxv = true;


if((campo == 'del_cpf') || (campo == 'qual_cpf')){
auxv = eCpfValido(valor);
}


if(campo == 'cpf'){
auxv = eCpfValido(valor);
}

if(campo == 'cpf1'){
auxv = eCpfValido(valor);
}

if(campo == 'cpf2'){
auxv = eCpfValido(valor);
}

if(campo == 'cpf3'){
auxv = eCpfValido(valor);
}

if(campo == 'cpf4'){
auxv = eCpfValido(valor);
}

if(campo == 'cpf5'){
auxv = eCpfValido(valor);
}


if(campo == 'sup_cpf'){
auxv = eCpfValido(valor);
}

if(campo == 'email'){
auxv = validaEmail(valor);
}


if(auxv == false){
document.getElementById(id).innerHTML = "";
}


valoraux = valor.value;

if(valoraux != ""){
	
if(auxv == true){




    testabrowser();
    if (ajax) {

        ajax.open("GET", "index.php?modulo=ajax&acao=consultar&tabela="+tabela+"&valor="+valoraux+"&campo="+campo+"&idaux="+idaux, true);



ajax.send(null);
        ajax.onreadystatechange = function(){
        
		

            if (ajax.readyState == 4) {
                if (ajax.responseText) {
				processaCampo(ajax.responseXML,campo,id);
                }
                else {
				//alert('erro ao abrir o arquivo');
                }
            }
        }
    }
	
}}
}



function processaCampo(obj,campo,id){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
            var item = dataArray[0];
			//contéudo dos campos no arquivo XML
			var resultado    =  item.getElementsByTagName("resultado")[0].firstChild.nodeValue;
			if(resultado == 0){
            var str = "<img src=\"img/icones/ok.png\"/>";
            document.getElementById(id).innerHTML = str;
			}else{
			
			alert('Já existe em nossa basse de dados')
			document.getElementById(campo).value = "";
            var str = "<img src=\"img/icones/erro.png\"/>";
            document.getElementById(id).innerHTML = str;
			}
			
			
	  }
	  
   }


function buscarCombo(id,sel,campo,banco,tabela,colunavalue,colunatexto,valor) {
	 
	 
	 //verifica se o browser tem suporte a ajax
	        testabrowser();
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		 document.forms[0].elements[sel].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
	
	     ajax.open("GET", "ajax.php?modulo=ajax&acao=combo&banco="+banco+"&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaCombo(ajax.responseXML,colunavalue,colunatexto,id,campo,sel);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = ">> Erro no carregamento dos registros";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaCombo(obj,colunavalue,colunatexto,id,campo,sel){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "--Selecione uma das opçoes abaixo--";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }






function buscarCombob(id,sel,campo,tabela,colunavalue,colunatexto,valor,resto) {

	        testabrowser();
	 
	  if(ajax) {
	     var congressos = $j("#congresso").val();
	 	 resto = " and congressos = '"+congressos+"'";	
	
			
		 document.forms[0].elements[sel].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
	var end = "index.php?modulo=ajax&acao=combob&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"&resto="+resto+"";
		 	     ajax.open("GET", end, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaCombob(ajax.responseXML,colunavalue,colunatexto,id,campo,sel);
			   }
			   else {
			     
				   
				   //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "-- escolher --";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaCombob(obj,colunavalue,colunatexto,id,campo,sel){
      //pega a tag cidade
	
      var dataArray   = obj.getElementsByTagName("registro");
		
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "-- escolha --";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- escolha  --";
	  }	  
   }








function buscarCombobee(id,sel,campo,tabela,colunavalue,colunatexto,valor,resto) {

	        testabrowser();
	 
	  if(ajax) {
	     

		 document.forms[0].elements[sel].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
	var end = "index.php?modulo=ajax&acao=combob&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"&resto="+resto+"";
		 
	     ajax.open("GET", end, true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaCombobee(ajax.responseXML,colunavalue,colunatexto,id,campo,sel);
			   }
			   else {
			     
				   
				   //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "-- escolher --";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaCombobee(obj,colunavalue,colunatexto,id,campo,sel){
      //pega a tag cidade
	
      var dataArray   = obj.getElementsByTagName("registro");
		
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "-- escolha --";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
		 }
		 var coc = document.getElementById('congresso').value;
		 
		 var res = " AND congressos='"+coc+"'";
   		 buscarCombob('opcoes5','cargo','estado','cargo','cargo','cargo','DFC',res,'');
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- escolha  --";
	  }	  
   }






function buscarCombobb(id,sel,campo,tabela,colunavalue,colunatexto,valor,resto,cong) {
	 //alert("index.php?modulo=ajax&acao=combob&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"&resto="+resto+"");
	 //verifica se o browser tem suporte a ajax
	        testabrowser();
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		var congressos = $j("#congresso").val();
	 	 resto = " and congressos = '"+congressos+"'";	
		 document.forms[0].elements[sel].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
	
		 
	     ajax.open("GET", "index.php?modulo=ajax&acao=combob&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"&resto="+resto+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaCombobb(ajax.responseXML,colunavalue,colunatexto,id,campo,sel,valor,cong);
			   }
			   else {
			     
				   
				   //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "-- escolher --";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaCombobb(obj,colunavalue,colunatexto,id,campo,sel,valor,cong){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "-- escolha --";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
		 }
		 var coc = document.getElementById('congresso').value;
		 
		 var res = " AND congressos='"+coc+"'";
   		 buscarCombob('opcoes5','cargo','estado','cargo','cargo','cargo',valor,res,'');
		 
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- escolha --";
	  }	  
   }









function buscarComboo(id,sel,campo,tabela,colunavalue,colunatexto,colunatexto2,valor,valor2) {
	 
	 
	 //verifica se o browser tem suporte a ajax
	        testabrowser();
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		 document.forms[0].elements[sel].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
	
		 
	     ajax.open("GET", "index.php?modulo=ajax&acao=comboo&campotexto2="+colunatexto2+"&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaComboo(ajax.responseXML,colunavalue,colunatexto,id,campo,sel,valor,valor2);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = ">> Erro no carregamento dos registros";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaComboo(obj,colunavalue,colunatexto,id,campo,sel,valor,valor2){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 var resultadosel = 0;
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "--Selecione uma das opçoes abaixo--";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
			var resultadotexto2    =  item.getElementsByTagName("resultadotexto2")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
				
		 
		
				
				if(valor2 == resultadovalue){
				resultadosel++;
				}
				
				
				
		 }
		 
		 
		document.forms[0].cod_municipio.options[resultadosel].selected = true;
		 
		 
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }











function buscarRegistro(campo2,valor2,campo,tabela,colunavalues,opcoes,sexo,valor) {

	   testabrowser();
	
	  if(ajax) {
				

	     ajax.open("GET", "index.php?modulo=ajax&acao=buscar&valor2="+valor2+"&campo2="+campo2+"&tabela="+tabela+"&valor="+valor+"&campovalues="+colunavalues+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		  
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {

			
			      processaRegistro(ajax.responseXML,colunavalues,campo,opcoes,sexo);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = ">> Erro no carregamento dos registros";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaRegistro(obj,colunavalues,campo,opcoes,sexo){
   
	 
	  camp = colunavalues.split(',');
	 
	
	  //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		
		  

	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {

		 var item = dataArray[i];

     
		var flg_sexo   =  item.getElementsByTagName('flg_sexo')[0].firstChild.nodeValue;
	

	
	
		if(flg_sexo=='F'){
		document.forms[0].elements[sexo].options[2].selected = true;
		}
		if(flg_sexo=='M'){
		document.forms[0].elements[sexo].options[1].selected = true;
		}
		
		
		var txt_uf   =  item.getElementsByTagName('txt_uf')[0].firstChild.nodeValue;
		
		if(txt_uf=='AC'){numuf = 1;}
		if(txt_uf=='AL'){numuf = 2;}
		if(txt_uf=='AP'){numuf = 3;}
		if(txt_uf=='AM'){numuf = 4;}
		if(txt_uf=='BA'){numuf = 5;}
		if(txt_uf=='CE'){numuf = 6;}
		if(txt_uf=='DF'){numuf = 7;}
		if(txt_uf=='GO'){numuf = 8;}
		if(txt_uf=='ES'){numuf = 9;}
		if(txt_uf=='MA'){numuf = 10;}
		if(txt_uf=='MT'){numuf = 11;}
		if(txt_uf=='MS'){numuf = 12;}
		if(txt_uf=='MG'){numuf = 13;}
		if(txt_uf=='PA'){numuf = 14;}
		if(txt_uf=='PB'){numuf = 15;}
		if(txt_uf=='PR'){numuf = 16;}
		if(txt_uf=='PE'){numuf = 17;}
		if(txt_uf=='PI'){numuf = 18;}
		if(txt_uf=='RJ'){numuf = 19;}
		if(txt_uf=='RN'){numuf = 20;}
		if(txt_uf=='RS'){numuf = 21;}
		if(txt_uf=='RO'){numuf = 22;}
		if(txt_uf=='RR'){numuf = 23;}
		if(txt_uf=='SP'){numuf = 24;}
		if(txt_uf=='SC'){numuf = 25;}
		if(txt_uf=='SE'){numuf = 26;}
		if(txt_uf=='TO'){numuf = 27;}
		
		document.forms[0].txt_uf.options[numuf].selected = true;
		var cod_municipio   =  item.getElementsByTagName('cod_municipio')[0].firstChild.nodeValue;
		buscarComboo('opcoes','municipio2','UF','Municipio','CodMunicipio','NomeMunicipio','OrigemRegistro',txt_uf,cod_municipio);
		
		 var num_beneficio   =  item.getElementsByTagName('num_beneficio')[0].firstChild.nodeValue;
		 document.getElementById('num_beneficio').value = num_beneficio; 
		 var txt_nome =  item.getElementsByTagName('txt_nome')[0].firstChild.nodeValue;
		 document.getElementById('txt_nome').value = txt_nome; 
		 var cod_beneficio_especie   =  item.getElementsByTagName('cod_beneficio_especie')[0].firstChild.nodeValue;
		 document.getElementById('cod_beneficio_especie').value = cod_beneficio_especie; 
		 var txt_nit   =  item.getElementsByTagName('txt_nit')[0].firstChild.nodeValue;
		 document.getElementById('txt_nit').value = txt_nit; 
		 var txt_cep   =  item.getElementsByTagName('txt_cep')[0].firstChild.nodeValue;
		 document.getElementById('txt_cep').value = txt_cep; 
		 var txt_fone  =  item.getElementsByTagName('txt_fone')[0].firstChild.nodeValue;
		 document.getElementById('txt_fone').value = txt_fone; 
		 var txt_endereco   =  item.getElementsByTagName('txt_endereco')[0].firstChild.nodeValue;
		 document.getElementById('txt_endereco').value = txt_endereco; 
		 var txt_bairro   =  item.getElementsByTagName('txt_bairro')[0].firstChild.nodeValue;
		 document.getElementById('txt_bairro').value = txt_bairro; 
		  var celular   =  item.getElementsByTagName('celular')[0].firstChild.nodeValue;
		 document.getElementById('celular').value = celular; 
			
		var dat_nascimento   =  item.getElementsByTagName('dat_nascimento')[0].firstChild.nodeValue;
		
		if(dat_nascimento != " "){
		dat = dat_nascimento.split('-');
		dat2 = dat[2].split(' ');
		dat = dat2[0]+"/"+dat[1]+"/"+dat[0];
		document.getElementById('dat_nascimento').value = dat; 
		}
		
		
		}
		 
	
			
					
		 
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }



function setval(valor,campo,campo2,campo3){
if((valor.elements[campo].value == "") || (valor.elements[campo].value == " ")){
document.getElementById(campo).style.backgroundColor = '#f0f0cb';
campoaux  = document.getElementById(campo2);
campoaux.innerHTML = campo3; 
}else{
document.getElementById(campo).style.backgroundColor = '#ffffff';
campoaux  = document.getElementById(campo2);
campoaux.innerHTML = ""; 
}
}


function buscarRegistro2(campo2,valor2,campo,tabela,colunavalues,ide,valor) {

	   testabrowser();
	
	  if(ajax) {


	     ajax.open("GET", "index.php?modulo=ajax&acao=buscar&valor2="+valor2+"&campo2="+campo2+"&tabela="+tabela+"&valor="+valor+"&campovalues="+colunavalues+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		  
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			
			      processaRegistro2(ajax.responseXML,colunavalues,campo,ide);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = ">> Erro no carregamento dos registros";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaRegistro2(obj,colunavalues,campo,ide){
      
	  camp = colunavalues.split(',');
	 
	
	  //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {

		 var item = dataArray[i];

		   // Verifica se questionário já existe
		  var cod_entidade   =  item.getElementsByTagName('cod_entidade')[0].firstChild.nodeValue;
	    
	
		 verificarCampo2(ide,'iconenada','cod_entidade','federacao',cod_entidade);
		
	
		 for(var i = 0 ; i < camp.length; i++) {
		 res = camp[i];
			 var res2   =  item.getElementsByTagName(res)[0].firstChild.nodeValue;
		document.getElementById(res).value = res2; 
				
		}
		 
		 

		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }



function buscarRegistro3(campo2,valor2,campo,tabela,colunavalues,ide,valor) {

	   testabrowser();
	
	  if(ajax) {


	     ajax.open("GET", "index.php?modulo=ajax&acao=buscar&valor2="+valor2+"&campo2="+campo2+"&tabela="+tabela+"&valor="+valor+"&campovalues="+colunavalues+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		  
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			
			      processaRegistro3(ajax.responseXML,colunavalues,campo,ide);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = ">> Erro no carregamento dos registros";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   
 function processaRegistro3(obj,colunavalues,campo,ide){
      
	  camp = colunavalues.split(',');
	 
	
	  //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {

		 var item = dataArray[i];

		   // Verifica se questionário já existe
		  var cod_entidade   =  item.getElementsByTagName('cod_entidade')[0].firstChild.nodeValue;
	  
	
		 verificarCampo3(ide,'iconenada','cod_entidade','sindicatos',cod_entidade);
		
	
		 for(var i = 0 ; i < camp.length; i++) {
		 res = camp[i];
			 var res2   =  item.getElementsByTagName(res)[0].firstChild.nodeValue;
		document.getElementById(res).value = res2; 
				
		}
		 
		 

		 }
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }







function verificarCampo2(idaux,id,campo,tabela,valor){




    testabrowser();
    if (ajax) {

 ajax.open("GET", "index.php?modulo=ajax&acao=consultar2&tabela="+tabela+"&valor="+valor+"&campo="+campo+"&idaux="+idaux, true);




ajax.send(null);
        ajax.onreadystatechange = function(){
        
		

            if (ajax.readyState == 4) {
                if (ajax.responseText) {
				
			
				processaCampo2(ajax.responseXML,campo,idaux);
			
				
				
				}
                else {
				//alert('erro ao abrir o arquivo');
                }
            }
        }
    }
}



function processaCampo2(obj,campo,id){
      //pega a tag cidade
	  
      var dataArray   = obj.getElementsByTagName("registro");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
            var item = dataArray[0];
			//contéudo dos campos no arquivo XML
			var resultado    =  item.getElementsByTagName("resultado")[0].firstChild.nodeValue;
			if(resultado == 0){
			}else{
			if(confirm('Já existe questionário cadastrado na federação escolhida, deseja editar agora?')){
			document.location='index.php?modulo=federacao&acao=editar&identificador='+resultado;	
			}else{
			
			if(id == 'nada'){
			document.location='index.php?modulo=federacao&acao=inserir';
			}else{
			document.location='index.php?modulo=federacao&acao=editar&identificador='+id;
			
			}
			}
		
		
			}
			
			
	  }
	  
   }





function verificarCampo3(idaux,id,campo,tabela,valor){




    testabrowser();
    if (ajax) {

 ajax.open("GET", "index.php?modulo=ajax&acao=consultar2&tabela="+tabela+"&valor="+valor+"&campo="+campo+"&idaux="+idaux, true);




ajax.send(null);
        ajax.onreadystatechange = function(){
        
		

            if (ajax.readyState == 4) {
                if (ajax.responseText) {
				
			
				processaCampo3(ajax.responseXML,campo,idaux);
			
				
				
				}
                else {
				//alert('erro ao abrir o arquivo');
                }
            }
        }
    }
}



function processaCampo3(obj,campo,id){
      //pega a tag cidade
	  
      var dataArray   = obj.getElementsByTagName("registro");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
            var item = dataArray[0];
			//contéudo dos campos no arquivo XML
			var resultado    =  item.getElementsByTagName("resultado")[0].firstChild.nodeValue;
			if(resultado == 0){
			}else{
			if(confirm('Já existe questionário cadastrado no sindicato escolhido, deseja editar agora?')){
			document.location='index.php?modulo=sindicatos&acao=editar&identificador='+resultado;	
			}else{
			
			if(id == 'nada'){
			document.location='index.php?modulo=sindicatos&acao=inserir';
			}else{
			document.location='index.php?modulo=sindicatos&acao=editar&identificador='+id;
			
			}
			}
		
		
			}
			
			
	  }
	  
   }


function  mostrarcampo(campo,campo1,verificacao,valor){
	var valoraux = valor.value;
	
	if(valoraux == verificacao){
	document.getElementById(campo).style.visibility = 'visible';
	} else {
	document.getElementById(campo).style.visibility = 'hidden';
	document.getElementById(campo1).value = ""; 
	}
}


function  mostrarcampos(campo,campo1,campo2,campo3,verificacao,valor){
	var valoraux = valor.value;
	
	camp = campo1.split(',');
	
	camp2 = campo2.split(',');

	camp3 = campo3.split(',');


	if(valoraux == verificacao){
	document.getElementById(campo).style.visibility = 'visible';
	} else {
	document.getElementById(campo).style.visibility = 'hidden';
	
	
    for(var i = 0 ; i < camp.length; i++) {
	document.getElementById(camp[i]).checked = false; 
	 }
	 
	 for(var i = 0 ; i < camp2.length; i++) {
	document.getElementById(camp2[i]).value = ""; 
	 }
	 

	 for(var i = 0 ; i < camp3.length; i++) {
	 var camp3aux = camp3[i];
	 document.forms[0].camp3aux.options[0].selected = true;
     }
	 
	
	
}
}

function mostrar(div,acao1,acao){


if(div == 'LayerFoto1'){
if(acao == 'show'){
$j("#LayerFoto11").fadeIn("slow");
$j("#mostrarfoto1").hide();

}

if(acao == 'hide'){
$j("#LayerFoto11").hide();
$j("#mostrarfoto1").fadeIn("slow");
}
}


if(div == 'LayerFoto2'){
if(acao == 'show'){
$j("#LayerFoto22").fadeIn("slow");
$j("#mostrarfoto2").hide();

}

if(acao == 'hide'){
$j("#LayerFoto22").hide();
$j("#mostrarfoto2").fadeIn("slow");
}
}

}


function  mostrarcampos3(campo,camp,campo3,campo4,verificacao,valor){
	var valoraux = valor.value;
	camp3 = campo3.split(',');
	camp4 = campo4.split(',');


	if(valoraux == verificacao){
	document.getElementById(campo).style.visibility = 'visible';

	} else {
	document.getElementById(campo).style.visibility = 'hidden';
	document.getElementById(camp).style.visibility = 'hidden';
	
	
 
	 for(var i = 0 ; i < camp3.length; i++) {
	 var camp3aux = camp3[i];
	
	 document.forms[0].elements[camp3aux].options[0].selected = true;
     }
	 
	
	 for(var i = 0 ; i < camp4.length; i++) {
	document.getElementById(camp4[i]).value = ""; 
	 }
}
}




function validarNumInt(objeto){
	valor=objeto.value;
	var inteiro = /^\d+$/;
	if(inteiro.test(valor)==false){
		
		
		var valorx = valor.length-1;

		if(valor != null && valor !=""){
			
		var valoraux = valor.substring(0, valorx);	
		
		alert("Por favor, insira somente números inteiros positivos.");		
		objeto.value=valoraux;
		objeto.focus();
			
		globalvar =objeto;
		setTimeout("globalvar.focus()",250);		
		}
	}	
}




function  cauculo1(campo,valor){
	var valoraux = valor.value;
	var valortotal = document.forms[0].sit_filhostotal.value;
	
	
	if(valoraux > valortotal){
	alert('Atenção o Nº de '+valoraux+' filhos com atual companheiro(a) é superior ao total de '+valortotal+' filhos que teve (ao todo)   - Por favor escolher outro valor')	
	document.forms[0].elements[campo].options[0].selected = true;	
	}
	


    
 
}

 function escolherdelegado(valor,div1,div2){
	document.getElementById('delegados').style.display = "block";
	
	if(valor == 'Delegado de Base')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "block";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	if(valor == 'Delegado Diretoria')
	{
	//document.getElementById('msnquite').innerHTML = "Fetag quite com a Contag:";
	
	document.getElementById('msnquitefetag').style.display = "none";
	document.getElementById('msnquitecontag').style.display = "block";
	
	
	document.getElementById('msnnome').style.display = "none";
	document.getElementById('msnnomediretor').style.display = "block";
	document.getElementById('msnnome2').style.display = "none";
	document.getElementById('msnnomediretor2').style.display = "block";

	
	document.getElementById('caixaplenaria').style.display = "none";
	document.getElementById('caixasindicato').style.display = "none";
	document.getElementById('caixacargo').style.display = "block";
	document.getElementById('caixacargo2').style.display = "block";
	
	
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	document.getElementById('caixaestatuto').style.display = "block";
	document.getElementById('caixaata').style.display = "block";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
	}
	
	
	
	if(valor == 'Delegado Jovem')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "block";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";	
	
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	
	
	if(valor == 'Delegado 3º Idade')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "none";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	
	

 }
 
 
 function validarNumInt3(campo2,objeto){
	
	
	
	var valortotal = document.forms[0].elements[campo2].value;
	
	if(valortotal != ""){
		
	
	
	valor=objeto.value;
	var inteiro = /[/]?\d+$/;
	if(inteiro.test(valor)==false){
		
		
		var valorx = valor.length-1;

		if(valor != null && valor !=""){
			
		var valoraux = valor.substring(0, valorx);	
		
		alert("Por favor, insira somente números inteiros positivos.");		
		objeto.value="";
		objeto.focus();
			
		globalvar =objeto;
		setTimeout("globalvar.focus()",250);		
		}
	}	}
}


function validarNumInt4(campo2,objeto){
	
	
	
	var valortotal = document.forms[0].elements[campo2].value;
	
	if(valortotal != ""){
		
	
	
	valor=objeto.value;
	var inteiro = /[-]?\d+$/;
	if(inteiro.test(valor)==false){
		
		
		var valorx = valor.length-1;

		if(valor != null && valor !=""){
			
		var valoraux = valor.substring(0, valorx);	
		
		alert("Por favor, insira somente números inteiros positivos.");		
		objeto.value="";
		objeto.focus();
			
		globalvar =objeto;
		setTimeout("globalvar.focus()",250);		
		}
	}	}
}




 function escolhertipodocumento(valor,div1,div2){
	document.getElementById('documentos').style.display = "block";
	
	if(valor == 'Documento Base')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "block";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	if(valor == 'Estatuto da CONTAG')
	{
	//document.getElementById('msnquite').innerHTML = "Fetag quite com a Contag:";
	
	document.getElementById('msnquitefetag').style.display = "none";
	document.getElementById('msnquitecontag').style.display = "block";
	
	
	document.getElementById('msnnome').style.display = "none";
	document.getElementById('msnnomediretor').style.display = "block";
	document.getElementById('msnnome2').style.display = "none";
	document.getElementById('msnnomediretor2').style.display = "block";

	
	document.getElementById('caixaplenaria').style.display = "none";
	document.getElementById('caixasindicato').style.display = "none";
	document.getElementById('caixacargo').style.display = "block";
	document.getElementById('caixacargo2').style.display = "block";
	
	
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	document.getElementById('caixaestatuto').style.display = "block";
	document.getElementById('caixaata').style.display = "block";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
	}
	
	
	
	if(valor == 'Regimento Interno')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "block";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";	
	
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	
	
	if(valor == 'Código de Ética')
	{
	//document.getElementById('msnquite').innerHTML = "STR quite com a Fetag:";
	document.getElementById('msnquitefetag').style.display = "block";
	document.getElementById('msnquitecontag').style.display = "none";
	
	
	document.getElementById('msnnome').style.display = "block";
	document.getElementById('msnnomediretor').style.display = "none";
	document.getElementById('msnnome2').style.display = "block";
	document.getElementById('msnnomediretor2').style.display = "none";
	
	document.getElementById('caixaplenaria').style.display = "block";
	document.getElementById('caixasindicato').style.display = "none";
	document.getElementById('caixacargo').style.display = "none";
	document.getElementById('caixacargo2').style.display = "none";
	document.getElementById('plenaria').value = "";
	document.getElementById('sindicato').value = "";
	document.getElementById('cargo').value = "";
	document.getElementById('cargo2').value = "";
	
	
	document.getElementById('caixaestatuto').style.display = "none";
	document.getElementById('caixaata').style.display = "none";
	document.forms[0].estatuto.options[0].selected = true;
	document.forms[0].ata.options[0].selected = true;
		
	}
	
	
	
	

 }
 
 function validarNumInt2(campo2,objeto){
	
	
	
	var valortotal = document.forms[0].elements[campo2].value;
	
	if(valortotal != ""){
		
	
	
	valor=objeto.value;
	var inteiro = /^\d+$/;
	if(inteiro.test(valor)==false){
		
		
		var valorx = valor.length-1;

		if(valor != null && valor !=""){
			
		var valoraux = valor.substring(0, valorx);	
		
		alert("Por favor, insira somente números inteiros positivos.");		
		objeto.value="";
		objeto.focus();
			
		globalvar =objeto;
		setTimeout("globalvar.focus()",250);		
		}
	}	}
}


function validarNumInt5(campo2,objeto){
	
	
	
	var valortotal = document.forms[1].elements[campo2].value;
	
	if(valortotal != ""){
		
	
	
	valor=objeto.value;
	var inteiro = /^\d+$/;
	if(inteiro.test(valor)==false){
		
		
		var valorx = valor.length-1;

		if(valor != null && valor !=""){
			
		var valoraux = valor.substring(0, valorx);	
		
		alert("Por favor, insira somente números inteiros positivos.");		
		objeto.value="";
		objeto.focus();
			
		globalvar =objeto;
		setTimeout("globalvar.focus()",250);		
		}
	}	}
}

 
function  cauculomaior(campo,campo2,valor){
	
	validarNumInt2(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[0].elements[campo2].value;

	if((valortotal == "") && (valoraux != "")){
	alert('Atenção!!! Este campo só pode ser preenchido depois de carregar a informação sobre o início')	
	document.forms[0].elements[campo].value = "";
	}
	
	
	valoraux2 = parseInt(valoraux);
	valortotal2 = parseInt(valortotal);

	
	if(valoraux2 < valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é inferior ao digitado no início - Por favor escolher outro valor')	
	document.forms[0].elements[campo].value = "";	
	}
}



function  cauculomenor(campo,campo2,valor){
	
	validarNumInt2(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[0].elements[campo2].value;

	if(valortotal != ""){
	
	valoraux2 = parseInt(valoraux);
	valortotal2 = parseInt(valortotal);

	
	if(valoraux2 > valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é superior ao digitado no Final - Por favor escolher outro valor')	
	document.forms[0].elements[campo].value = "";	
	}	}
}

function  cauculomaior2(campo,campo2,campo3,campo4,valor){
	
	validarNumInt5(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[1].elements[campo2].value;
	
	var inicio = document.forms[1].elements[campo3].value;
	var final = document.forms[1].elements[campo4].value;
    valoraux2 = parseInt(valoraux);
	inicio = parseInt(inicio);
	final = parseInt(final);

	if((valoraux2 < inicio) || (valoraux2 > final)){
		alert('Valor digitado  estar fora do intervalo de questões que este documento possui -> digite valores entre  '+inicio+' - '+final);
		document.forms[1].elements[campo].value = "";
		exit;
	}


if((valortotal == "") && (valoraux != "")){
	alert('Atenção!!! Este campo só pode ser preenchido depois de carregar a informação sobre o início')	
	document.forms[1].elements[campo].value = "";
	}
	
	
	
	valortotal2 = parseInt(valortotal);

	
	if(valoraux2 < valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é inferior ao digitado no início - Por favor escolher outro valor')	
	document.forms[1].elements[campo].value = "";	
	}
}



function  cauculomenor2(campo,campo2,campo3,campo4,valor){
	
	validarNumInt5(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[1].elements[campo2].value;
	
	var inicio = document.forms[1].elements[campo3].value;
	var final = document.forms[1].elements[campo4].value;
	
	valoraux2 = parseInt(valoraux);
	inicio = parseInt(inicio);
	final = parseInt(final);
	
	if((valoraux2 < inicio) || (valoraux2 > final)){
		alert('Valor digitado estar fora do intervalo de questões que este documento possui -> digite valores entre  '+inicio+' - '+final);
		document.forms[1].elements[campo].value = "";
		exit;
	}

	if(valortotal != ""){
	
	
	valortotal2 = parseInt(valortotal);



	
	

	
	if(valoraux2 > valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é superior ao digitado no Final - Por favor escolher outro valor')	
	document.forms[1].elements[campo].value = "";	
	}	}
}




function  cauculomaior3(campo,campo2,campo3,campo4,valor){
	
	validarNumInt2(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[0].elements[campo2].value;
	
	var inicio = document.forms[0].elements[campo3].value;
	var final = document.forms[0].elements[campo4].value;
    valoraux2 = parseInt(valoraux);
	inicio = parseInt(inicio);
	final = parseInt(final);

	if((valoraux2 < inicio) || (valoraux2 > final)){
		alert('Valor digitado  estar fora do intervalo de questões que este documento possui -> digite valores entre  '+inicio+' - '+final);
		document.forms[0].elements[campo].value = "";
		exit;
	}


if((valortotal == "") && (valoraux != "")){
	alert('Atenção!!! Este campo só pode ser preenchido depois de carregar a informação sobre o início')	
	document.forms[0].elements[campo].value = "";
	}
	
	
	
	valortotal2 = parseInt(valortotal);

	
	if(valoraux2 < valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é inferior ao digitado no início - Por favor escolher outro valor')	
	document.forms[0].elements[campo].value = "";	
	}
}



function  cauculomenor3(campo,campo2,campo3,campo4,valor){
	
	validarNumInt2(campo2,valor);
	
	
	var valoraux = valor.value;

	var valortotal = document.forms[0].elements[campo2].value;
	
	var inicio = document.forms[0].elements[campo3].value;
	var final = document.forms[0].elements[campo4].value;
	
	valoraux2 = parseInt(valoraux);
	inicio = parseInt(inicio);
	final = parseInt(final);
	
	if((valoraux2 < inicio) || (valoraux2 > final)){
		alert('Valor digitado estar fora do intervalo de questões que este documento possui -> digite valores entre  '+inicio+' - '+final);
		document.forms[0].elements[campo].value = "";
		exit;
	}

	if(valortotal != ""){
	
	
	valortotal2 = parseInt(valortotal);



	
	

	
	if(valoraux2 > valortotal2){
	alert('Atenção!!! O valor '+valoraux+' é superior ao digitado no Final - Por favor escolher outro valor')	
	document.forms[0].elements[campo].value = "";	
	}	}
}




 function escolherestado(valor,div1,div2){

if(valor == ""){
	location = '?modulo=documentoalteracao&acao=listar';	
 }else{
	location = '?modulo=documentoalteracao&acao=listar&estado='+valor;	
 }
}


 function escolherestadocadernopropostas(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=listarcadernodepropostas';	
 }else{
	location = '?modulo=relatorios&acao=listarcadernodepropostas&estado='+valor;	
 }
}

 function escolherestado2(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=listar';	
 }else{
	location = '?modulo=relatorios&acao=listar&estado='+valor;	
 }
}

 function escolherestado3(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=listar2';	
 }else{
	location = '?modulo=relatorios&acao=listar2&estado='+valor;	
 }
}


 function escolherestado4(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=listar3';	
 }else{
	location = '?modulo=relatorios&acao=listar3&estado='+valor;	
 }
}

function escolherestado5(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=listar5';	
 }else{
	location = '?modulo=relatorios&acao=listar5&estado='+valor;	
 }
}
 function escolheraprovados(valor,div1,div2){

if(valor == ""){
	location = '?modulo=relatorios&acao=aprovadas';	
 }else{
	location = '?modulo=relatorios&acao=aprovadas&congresso='+valor;	
 }
}





function aprovar(questaoaprovada,idquestao,estadoaprova,campo,campoo,questao,campooo){


testabrowser();
    if (ajax) {

        ajax.open("GET", "index.php?modulo=ajax&acao=aprovar&identificador="+idquestao+"&questaoaprovada="+questaoaprovada+"&estadoaprova="+estadoaprova+"", true);




ajax.send(null);
        ajax.onreadystatechange = function(){
        
		

            if (ajax.readyState == 4) {
                if (ajax.responseText) {
				processaCampoAprova(ajax.responseXML,campo,campoo,questao,campooo);
                }
                else {
				//alert('erro ao abrir o arquivo');
                }
            }
        }
    }
	

}



function processaCampoAprova(obj,campo,campoo,questao,campooo){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");
      
	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
	     //percorre o arquivo XML paara extrair os dados
            var item = dataArray[0];
			//contéudo dos campos no arquivo XML
			var resultado    =  item.getElementsByTagName("resultado")[0].firstChild.nodeValue;
			if(resultado == 0){
				alert('Questão não aprovada devido erro no sistema ');
          	
			}else{
			alert('Questão aprovada com sucesso');
			linhas = document.getElementById(campoo).value;
		for(i=0; i < linhas; i++){
		var newcampo = "aprova"+questao+i;
		var newcampo2 = "aprova"+questao+i+i;
		document.getElementById(newcampo).style.display = "block";
		document.getElementById(newcampo2).style.display = "none";
	   }
		
			
		document.getElementById(campooo).style.display = "none";
		document.getElementById(campo).style.display = "block";
		
		}
			
			
	  }
	  
   }





function buscarSindicatos(id,sel,campo,tabela,colunavalue,colunatexto,valor,sel2,id2) {
	 
	 
	 //verifica se o browser tem suporte a ajax
	        testabrowser();
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		 document.forms[0].elements[sel].options.length = 1;
		 document.forms[0].elements[sel2].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
		 idOpcao2  = document.getElementById(id2);
	
		 
	     ajax.open("GET", "index.php?modulo=ajax&acao=combosindicatos&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaSindicatos(ajax.responseXML,colunavalue,colunatexto,id,campo,sel,sel2,valor);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "-- Escolha um Estado --";
				   idOpcao2.innerHTML = "-- Escolha um Estado --";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   

function processaSindicatos(obj,colunavalue,colunatexto,id,campo,sel,sel2,valor){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "--Selecione uma das opçoes abaixo--";
		 idOpcao2.innerHTML = "--Selecione uma das opçoes abaixo--";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
				
				
				var novo2 = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo2.setAttribute("id", id);
				//atribui um valor
			    novo2.value = resultadovalue;
				//atribui um texto
			    novo2.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				
              	document.forms[0].elements[sel2].options.add(novo2);
				

		 }
		 buscarCombob('opcoes4','plenaria','uf','plenarias','campo','campo',valor,'','');	
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }




function escolherpc(valor){
	escolherplecom(valor);
	escolherplecom2(valor);
}

function escolherestadodelegados(valor){
	
buscarSindicatos('opcoes','sindicato1','txt_uf','tb_entidade','txt_nome','txt_nome',valor,'sindicato2','opcoes2');


}



function buscarSindicatos2(id,sel,campo,tabela,colunavalue,colunatexto,valor,sel2,id2,cong) {
	 
	 
	 //verifica se o browser tem suporte a ajax
	        testabrowser();
	  //se tiver suporte ajax
	  if(ajax) {
	     //deixa apenas o elemento 1 no option, os outros sao excluídos

		 document.forms[0].elements[sel].options.length = 1;
		 document.forms[0].elements[sel2].options.length = 1;
		 document.forms[0].elements['cargo'].options.length = 1;
		 document.forms[0].elements['plenaria'].options.length = 1;
	     
		 idOpcao  = document.getElementById(id);
		 idOpcao2  = document.getElementById(id2);
	
		 
	     ajax.open("GET", "index.php?modulo=ajax&acao=combosindicatos&tabela="+tabela+"&valor="+valor+"&campotexto="+colunatexto+"&campovalue="+colunavalue+"&campo="+campo+"", true);
		 ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		 ajax.onreadystatechange = function() {
            //enquanto estiver processando...emite a msg de carregando
			if(ajax.readyState == 1) {
			   idOpcao.innerHTML = "Aguarde carregando...!";   
			   
			 
	        }


			//após ser processado - chama funçao processXML que vai varrer os dados
            if(ajax.readyState == 4 ) {
			   if(ajax.responseXML) {
			      processaSindicatos2(ajax.responseXML,colunavalue,colunatexto,id,campo,sel,sel2,valor,cong);
			   }
			   else {
			       //caso nao seja um arquivo XML emite a mensagem abaixo
				   idOpcao.innerHTML = "-- Escolha um Estado --";
				   idOpcao2.innerHTML = "-- Escolha um Estado --";
			   }
            }
         }
		 //passa o código do estado escolhido
	     var params = "estado="+valor;

		 
         ajax.send(params);
      }
   }
   

function processaSindicatos2(obj,colunavalue,colunatexto,id,campo,sel,sel2,valor,cong){
      //pega a tag cidade
      var dataArray   = obj.getElementsByTagName("registro");

	  //total de elementos contidos na tag cidade
	  if(dataArray.length > 0) {
		  
		 
	     //percorre o arquivo XML paara extrair os dados
         for(var i = 0 ; i < dataArray.length; i++) {
         
		  
		 var item = dataArray[i];
		
		 idOpcao.innerHTML = "--Selecione uma das opçoes abaixo--";
		 idOpcao2.innerHTML = "--Selecione uma das opçoes abaixo--";
		//contéudo dos campos no arquivo XML
			var resultadovalue    =  item.getElementsByTagName("resultadovalue")[0].firstChild.nodeValue;
			var resultadotexto    =  item.getElementsByTagName("resultadotexto")[0].firstChild.nodeValue;
					
			
			//cria um novo option dinamicamente  
			var novo = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo.setAttribute("id", id);
				//atribui um valor
			    novo.value = resultadovalue;
				//atribui um texto
			    novo.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				document.forms[0].elements[sel].options.add(novo);
				
				
				var novo2 = document.createElement("option");
			    //atribui um ID a esse elemento
			    novo2.setAttribute("id", id);
				//atribui um valor
			    novo2.value = resultadovalue;
				//atribui um texto
			    novo2.text  = resultadotexto;
				//finalmente adiciona o novo elemento
				
				
				document.forms[0].elements[sel2].options.add(novo2);
				
						//cria um novo option dinamicamente  
		
		 }
		 buscarCombobb('opcoes4','plenaria','uf','plenarias','campo','campo',valor,'','',cong);
	  }
	  else {
	    //caso o XML volte vazio, printa a mensagem abaixo
		idOpcao.innerHTML = "-- Primeiro selecione uma opçao acima --";
	  }	  
   }



function janela(param, h, w, t){
novaJanela = window.open(param, 'popup'+h+'px'+w+'px', 'height='+h+', width='+w+', scrollbars='+t);
}


