/**
 * Desenvolvedor: Vinícius Faria de Souza
 * 
 * Objetivo: Funções especificas utilizadas no template cadastrar_usuario
 */

//variáveis globais

window.onload = function () {
    var act = document.getElementById('act').value;
    if(act=='A') {
        //como é alteração, mostrando a div para sair
        document.getElementById('divsair').className = 'item';
        document.getElementById('cpfcorreto').style.display = 'inline';
        document.getElementById('botao').style.display = 'none';
        document.getElementById('enviarBotao').style.display = 'inline';
        document.getElementById('enviarBotao2').style.display = 'inline';
        altEmail();  //então mostra o rótulo correto de acordo com o vínculo do usuário com a instituição
    }
    else {
        //se é inclusão oculta div

        var urla1 = "cadastrar_usuario.php?act=I"; // Global também
        var urla2 = "cadastrar_usuario.php?act=A"
        var dominio = location.href;

        if(dominio.indexOf(urla2) != -1) { // verifica se a url começa com o conteudo da variavel dominio
            document.getElementById('enviarBotao').style.display = 'none';
            document.getElementById('enviarBotao2').style.display = 'none';
        }

        if(dominio.indexOf(urla1) != -1) { // verifica se a url começa com o conteudo da variavel dominio
            document.getElementById('icpf').focus();
        }

        document.getElementById('divsair').className = 'itemh';
        //document.getElementById('save').style.display = 'none';
    }
}

var msgant   = '<p>O CPF está incorreto.</p>';
var msgeant  = '<p>Favor informar o endereço de e-mail corretamente</p>';
var ret = 0;

function createUid() { //função para criar um uid baseado no nome e sobrenome informado pelo usuário

  var obj  = document.getElementById("nome").value; //pegam os dados
  var obj2 = document.getElementById("sobrenome").value;
  if(obj == "" || obj2 == "") {
     document.getElementById('div_uid').style.display = 'none';
  }
  else {
	obj= obj.replace(/[áÃ ãÃ¢]/g,"a") //substitui acentos e outros caracteres especiais
	obj= obj.replace(/[éÃ¨ê]/g,"e")
	obj= obj.replace(/[Ã¬íÃ®Ä©]/g,"i")
	obj= obj.replace(/[Ã²óÃ´õ]/g,"o")
	obj= obj.replace(/[Ã¹úÃ»Å©]/g,"u")
	obj= obj.replace(/[ç]/g,"c")

	obj2= obj2.replace(/[áÃ ãÃ¢]/g,"a")
	obj2= obj2.replace(/[éÃ¨ê]/g,"e")
	obj2= obj2.replace(/[Ã¬íÃ®Ä©]/g,"i")
	obj2= obj2.replace(/[Ã²óÃ´õ]/g,"o")
	obj2= obj2.replace(/[Ã¹úÃ»Å©]/g,"u")
	obj2= obj2.replace(/[ç]/g,"c")

        var act = document.getElementById('act').value;
        if(act!='A') { //se o tipo não for alteração
            document.getElementById('div_uid').style.display = 'none'; //não mostra a div com as opções de uid
            var url="ajax.php?act=nui&obj="+obj+"&obj2="+obj2;
            requisicaoHTTP('GET',url,true,2); //faz requisição ao servidor passando nome e sobrenome
        }
   }

}

function srcReg() { //trtando resposta do servidor com relação as opções de login
    var resp = ajax.responseText;
    if(resp.indexOf('Erro') != -1) { //se houve erro na criação dos logins
       alert(resp); //exibe
    }
    else { //senão
       var uid = document.getElementById("div_uid");
       uid.innerHTML = resp; // e atribui a ela os resultados retornados pelo servidor
       uid.style.display = 'inline'; //mostra a div com os uids
    }
}

function alterar(){ //função acionada quando o usuário alterar o estado, busca as cidades daquele estado
var obj = document.getElementById("estado");
var indice = obj.value;
	if(indice ==0) { //verifica se informou um estado válido
		document.getElementById('div_cidades').style.display = 'none';
	}
	else {
            var url="ajax.php?act=prc&estado="+indice;
            requisicaoHTTP('GET',url,true,1); //faz requisição ao servidor buscando cidades desse estado
            document.getElementById('avisa').innerHTML = 'Aguarde...';
	}

}

function delReg() { //vamos mostrar as cidades desse estado
    var resp = ajax.responseText;
    if(resp.indexOf('Erro') != -1) { //se houve algum erro
        alert(resp);
    }
    else {
        var div = document.getElementById("div_cidades");
        document.getElementById('div_cidades').style.display = 'inline';
        div.innerHTML = resp; //atribui cidades do estado a combo das cidades
        document.getElementById('avisa').innerHTML = '';
        document.getElementById('cidade').className = 'cidade';
    }
}


function altEmail() { //de acordo com o tipod e vínculo do usuário muda o rótulo do tipo de e-mail considerando que Funcionário Tercerizado e Estagiario não podem possuir e-mail institucional
   var vinculo = document.getElementsByName('vinculo');
   var intVinc = parseInt(getCheckedValue(vinculo));
   var act = document.getElementById('act').value;
   var vetUid = document.getElementsByName('uid');
   for (i=0;i<vetUid.length;i++){
       document.getElementsByName('uid')[i].checked = false;
   }
   
   if(intVinc>2) { //e-mail externo //Funcionário Tercerizado ou Estagiario
       document.getElementById('titEmail').innerHTML = 'Email Pessoal:';
       document.getElementById('finEmail').style.display = 'none';
       document.form1.email.disabled=false;
       if(act=="I")
           document.getElementById('email').value = '';
   }
   else { //e-mail ifmg
       document.getElementById('titEmail').innerHTML = 'Email Institucional: ';
       document.getElementById('finEmail').style.display = 'inline';

       if(act=='I'){
            document.form1.email.disabled=true;
            document.getElementById('email').value = '';
       }
       else
            document.form1.email.disabled=false;
   }
    
}

function valPas(senha) { //validação da senha do usuário
   if(senha.length < 8) { //senha menor que 8 caracteres
        return false;
   }
   else {
     var exp = new RegExp("^[a-zA-Z0-9!?.@#$%&*_]{8,15}$"); //expressao regular para senha alfanumérica
     if(exp.test(senha)) {
        //if((senha.match(/(.*[0-9])/)) && (senha.match(/(.*[a-z])/))) //valida senha se alfanumérica ou não
        return true;
//        else
  //         return false;
     }
     else
         return false;
   }
   return true;
}

function valMail(campo,acao) { //validação do campo e-mail
   var vinculo = document.getElementsByName('vinculo');
   var intVinc = parseInt(getCheckedValue(vinculo));
   //se o endereço é externo
   if(intVinc>2) { //e-mail externo //se o tipo de vínculo não é institucional
        if(campo.indexOf('.') == -1 || campo.indexOf('@') == -1 || campo.indexOf(' ') != -1) {  //valida normalmente o e-mail com @.
            document.getElementById('divemail').innerHTML = msgeant;
            return false;
        }
   }
   //se o endereço é interno
   else { //se vínculo é institucional
       if(campo.length > 0 && getCheckedValue(vinculo).length > 0) { //verifica se foi informado o vinculo
           if(acao=='I') { //se for inclusão
              var uid  = document.getElementsByName('uid'); //pega o uid
              var uidV = getCheckedValue(uid);
              if(campo!=uidV) { //se o uid for diferente do endereço informado não aceita
                  document.getElementById('divemail').innerHTML = '<p>O endereço de e-mail deve corresponder ao usuário de login.</p>';
                  return false;
              }
           }
       }
       else {
           document.getElementById('divemail').innerHTML = msgeant;
           return false;
       }
   }
   return true;
}


function getCheckedValue(radioObj) { //função para verificar qual opção escolhida em campos radio...
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function valCpf(cpf) { //validar o número de cpf
   var first = cpf.substr(0,3);
   var secon = cpf.substr(4,3);
   var terce = cpf.substr(8,3)
   var quart = cpf.substr(12,2);
   cpf = first+secon+terce+quart;
   var numeros, digitos, soma, i, resultado, digitos_iguais;
   digitos_iguais = 1;
   if (cpf.length < 11)
      return false;
   for (i = 0; i < cpf.length - 1; i++)
     if (cpf.charAt(i) != cpf.charAt(i + 1)) {
          digitos_iguais = 0;
          break;
     }
     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))
               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))
               return false;
         return true;
     }
     else
        return false;
}

function checkCPF() {
    //verificar se cpf já existe no cadastro
    var cpf = document.getElementById('icpf').value;
    if(valCpf(cpf)) { //se o cpf digitado é válido
       var act = document.getElementById('act').value;
       document.getElementById('icpf').style.background='#FFFFFF';
       document.getElementById('divcpf').style.display = 'none';
       if(act=='I') { //se é inclusão
          //vamos verificar na base LDAP se esse CPF já existe lá
          var url="ajax.php?act=sec&cpf="+encodeURIComponent(cpf);
          requisicaoHTTP('GET',url,true,3);
          document.getElementById('avisacpf').innerHTML = 'Aguarde...';
       }
    }
    else { //cpf inválido
        ret = 0;
        document.getElementById('divcpf').innerHTML = msgant;
        document.getElementById('icpf').style.background='#FFFFC8';
   	document.getElementById('cpfcorreto').style.display = 'none';
        document.getElementById('divcpf').style.display = 'inline';
        document.getElementById('divcpf').style.color = 'red';
    }
}

function insReg() { //mostra se o cpf já foi inserido na base
    var texto = parseInt(ajax.responseText);
    document.getElementById('avisacpf').innerHTML = '';
    if(parseInt(texto)==100) { //se o cpf não existe no cadastro ainda, mas existe na base do sistema de gestão gestaõ
         document.getElementById('divcpf').innerHTML = msgant;
         document.getElementById('divcpf').style.display = 'none';
         document.getElementById('cpfcorreto').style.display = 'inline';
         document.getElementById('nome').focus();
         ret = 1;
    }
    else { //já existe cpf com esse número ou o cpf não existe na base gestão
       var msgnew = '';
       if(parseInt(texto)==0) //cpf não existe na base do LDAP, mas também não existe na base do sistema de gestão.
          msgnew = '<p>O CPF informado não está cadastrado no sistema de gestão, o cadastro não é permitido, entre em contato com o <a href="mailto:gsa.ouropreto@ifmg.edu.br">GSA</a> e regularize sua situação.</p>';
       else if(parseInt(texto)>0 && parseInt(texto)<100) //cpf já existe na base, não é possível efetuar o cadastro
       msgnew = '<p>Já existe um cadastro com esse número de cpf, clique <a href="gerar_senha.php">aqui</a> para gerar uma nova senha.</p>';
       document.getElementById('divcpf').innerHTML = msgnew;
       document.getElementById('divcpf').style.display = 'inline';
       document.getElementById('cpfcorreto').style.display = 'none';
       document.getElementById('divcpf').style.color = 'red';
       ret = 0;
    }
}

function catEmailAdd() { //quando o entra no campo de e-mail
    var act      = document.getElementById('act').value; //pega ação
    var email = document.getElementById('email').value; //pega endereço de e-mail
    if(email.length==0) {
      if(act=='I') { //se for inclusão
          var vinculo = document.getElementsByName('vinculo'); //e institucional
          var intVinc = parseInt(getCheckedValue(vinculo));
          if(intVinc<=2) { //e-mail interno
              var uid  = document.getElementsByName('uid');
              var uidV = getCheckedValue(uid);
              document.getElementById('email').value = uidV; //atribui o login informado ao endereço de e-mail
          }
      }
    }
}

function saida() { //confirma se o usuário deseja deixar o sistema
    if(confirm("Deseja realmente sair do MGU?")) {
        window.open('logout.php',target='_top');
    }
}

function insRow() { //funçaõ para inserir usuário no sistema
    var act = document.getElementById('act').value;
    if(valRow(act)) { //valida campos obrigatórios
         var email  = '';
         var nome      = encodeURIComponent(document.getElementById('nome').value); //pega dados do formulário
         var sobrenome = encodeURIComponent(document.getElementById('sobrenome').value);
         var icpf      = encodeURIComponent(document.getElementById('icpf').value);
         var itelefone = encodeURIComponent(document.getElementById('itelefone').value);
         var icelular  = encodeURIComponent(document.getElementById('icelular').value);
         var rua       = encodeURIComponent(document.getElementById('rua').value);
         var numerocasa= encodeURIComponent(document.getElementById('numerocasa').value);
         var distrito  = encodeURIComponent(document.getElementById('distrito').value);
         var inscricao = encodeURIComponent(document.getElementById('inscricao').value);
         var bairro    = encodeURIComponent(document.getElementById('bairro').value);
         var estado    = encodeURIComponent(document.getElementById('estado').value);
         var cidade    = encodeURIComponent(document.getElementById('cidade').value);
         var icep      = encodeURIComponent(document.getElementById('icep').value);
         var vinculo   = getCheckedValue(document.getElementsByName('vinculo'));
         var setlotacao= encodeURIComponent(document.getElementById('setlotacao').value);
         var uid       = getCheckedValue(document.getElementsByName('uid'));
         var intVinc   = parseInt(vinculo);
         if(intVinc>2) { //e-mail externo
             email  = encodeURIComponent(document.getElementById('email').value);
         }
         else { //se o e-mail é institucional adiciona prefixo ifmg ao usuário escolhido
             email  = encodeURIComponent(document.getElementById('email').value)+'@ifmg.edu.br';
         }
         var password  = encodeURIComponent(document.getElementById('password').value);
         var complemento = encodeURIComponent(document.getElementById('complemento').value);
         var emailalt    = encodeURIComponent(document.getElementById('emailalt').value);
         var url="ajax.php?act=ins&nome="+nome+'&sobrenome='+sobrenome+'&icpf='+icpf+'&itelefone='+itelefone+'&icelular='+icelular+'&rua='+rua+'&numerocasa='+numerocasa+'&bairro='+bairro+'&estado='+estado+'&cidade='+cidade+'&icep='+icep+'&vinculo='+vinculo+'&setlotacao='+setlotacao+'&uid='+uid+'&email='+email+'&password='+password+'&distrito='+distrito+'&inscricao='+inscricao+'&complemento='+complemento+'&emailalt='+emailalt;
         document.getElementById('avisainc').innerHTML = 'Aguarde...';
         requisicaoHTTP('GET',url,true,4); //faz requisição de inserção de usuário na base
         
    }
    else {
        alert('O MGU encontrou alguns erros ao tentar efetuar o cadastro, corriga-os e tente novamente.'); //a validação retornou falhas...
    }
}

function updReg() { //trata resposta da inserção...
    document.getElementById('avisainc').innerHTML = '';
    var texto = ajax.responseText;
    if(texto.indexOf('Erro') != -1) { //houve erro na inserção
        alert(texto);
    }
    else {
        //alert('Usuário '+texto+ ' inserido com sucesso!'); //usuário inserido com sucesso
        window.open('pagina_msg.php',target='_top');
    }
}

function updRow() { //atualização de dados cadastrais
    var act = document.getElementById('act').value;
    if(valRow(act)) { //verifica se usuário inseriu todos os dados
         var nome      = encodeURIComponent(document.getElementById('nome').value);
         var sobrenome = encodeURIComponent(document.getElementById('sobrenome').value);
         var itelefone = encodeURIComponent(document.getElementById('itelefone').value);
         var icelular  = encodeURIComponent(document.getElementById('icelular').value);
         var rua       = encodeURIComponent(document.getElementById('rua').value);
         var numerocasa= encodeURIComponent(document.getElementById('numerocasa').value);
         var distrito  = encodeURIComponent(document.getElementById('distrito').value);
         var inscricao = encodeURIComponent(document.getElementById('inscricao').value);
         var bairro    = encodeURIComponent(document.getElementById('bairro').value);
         var icpf      = encodeURIComponent(document.getElementById('icpf').value);
         var estado    = encodeURIComponent(document.getElementById('estado').value);
         var cidade    = encodeURIComponent(document.getElementById('cidade').value);
         var icep      = encodeURIComponent(document.getElementById('icep').value);
         var vinculo   = getCheckedValue(document.getElementsByName('vinculo'));
         var setlotacao= encodeURIComponent(document.getElementById('setlotacao').value);
         var email     = encodeURIComponent(document.getElementById('email').value);
         var uid       = encodeURIComponent(document.getElementById('uid').value);
         var oldPass   = encodeURIComponent(document.getElementById('oldPass').value);
         var emailalt  = encodeURIComponent(document.getElementById('emailalt').value);
         var complemento = encodeURIComponent(document.getElementById('complemento').value);
         var url="ajax.php?act=upd&nome="+nome+'&sobrenome='+sobrenome+'&itelefone='+itelefone+'&icelular='+icelular+'&rua='+rua+'&numerocasa='+numerocasa+'&bairro='+bairro+'&estado='+estado+'&cidade='+cidade+'&icep='+icep+'&vinculo='+vinculo+'&setlotacao='+setlotacao+'&email='+email+'&distrito='+distrito+'&inscricao='+inscricao+'&complemento='+complemento+'&emailalt='+emailalt+'&uid='+uid+'&oldPass='+oldPass+'&icpf='+icpf;
         document.getElementById('avisainc').innerHTML = 'Aguarde...';
         document.getElementById('avisainc2').innerHTML = 'Aguarde...';
         document.getElementById('avisainc3').innerHTML = 'Aguarde...';

         requisicaoHTTP('GET',url,true,5); //faz requisição ao servidor passando url para que o servidor atualize os dados
    }
    else {
        alert('O MGU encontrou alguns erros ao tentar atualizar o cadastro, corriga-os e tente novamente.');
    }
}

function strReg() { //retorno da atualização dos dados do usuário
    //document.getElementById('aviso').style.display = 'none';
    document.getElementById('avisainc').innerHTML = '';
    document.getElementById('avisainc2').innerHTML = '';
    document.getElementById('avisainc3').innerHTML = '';

    var texto = ajax.responseText;
    if(texto.indexOf('Erro') != -1) { //se houve erro
        alert(texto);
    }
    else {
        var msg = 'Usuário '+texto+ ' alterado com sucesso.';
        alert(msg);
    }
}

function valRow(acao) { //validando formulário de dados, age diferente de acordo com a ação
    var nome = document.getElementById('nome');
    var opc  = true;
    if(nome.value.length==0) {  //nome obrigatorio
	nome.style.background='#FFFFC8';
	document.getElementById('divnome').style.display = 'inline'; //avisa se não informou
        document.getElementById('divnome').style.color = 'red'; //muda cor do texto de alerta
        opc = false;
    }
    else {
	nome.style.background='#FFFFFF'; //se está ok deixa em branco
	document.getElementById('divnome').style.display = 'none'; //apaga div com o erro
    }
    var sobrenome = document.getElementById('sobrenome');
    if(sobrenome.value.length==0) {
	sobrenome.style.background='#FFFFC8';
	document.getElementById('divsobrenome').style.display = 'inline';
        document.getElementById('divsobrenome').style.color = 'red';
        opc = false;
    }
    else {
	sobrenome.style.background='#FFFFFF';
	document.getElementById('divsobrenome').style.display = 'none';
    }
    if(acao=='I') { //se acao inclusão
     if(ret==0) //verifica o erro retornado na verificação do cpf
       opc = false;
    }
    var itelefone = document.getElementById('itelefone');
    var icelular  = document.getElementById('icelular');
    if(itelefone.value.length==0 && icelular.value.length==0) { //celular ou telefone deve ser informado
	document.getElementById('divtelcel').style.display = 'inline';
        document.getElementById('divtelcel').style.color = 'red';
        opc = false;
    }
    else {
	document.getElementById('divtelcel').style.display = 'none';
    }
    var rua = document.getElementById('rua');
    if(rua.value.length==0) {
        rua.style.background='#FFFFC8';
	document.getElementById('divrua').style.display = 'inline';
        document.getElementById('divrua').style.color = 'red';
        opc = false;
    }
    else {
        rua.style.background='#FFFFFF';
	document.getElementById('divrua').style.display = 'none';
    }
    var numerocasa = document.getElementById('numerocasa');
    if(numerocasa.value.length==0) {
        numerocasa.style.background='#FFFFC8';
	document.getElementById('divnumerocasa').style.display = 'inline';
        document.getElementById('divnumerocasa').style.color = 'red';
        opc = false;
    }
    else {
        numerocasa.style.background='#FFFFFF';
	document.getElementById('divnumerocasa').style.display = 'none';
    }
    var bairro = document.getElementById('bairro');
    if(bairro.value.length==0) {
        bairro.style.background='#FFFFC8';
	document.getElementById('divbairro').style.display = 'inline';
        document.getElementById('divbairro').style.color = 'red';
        opc = false;
    }
    else {
        bairro.style.background='#FFFFFF';
	document.getElementById('divbairro').style.display = 'none';
    }
    var estado = document.getElementById('estado');
    if(estado.value==0) {
        estado.style.background='#FFFFC8';
	document.getElementById('divestado').style.display = 'inline';
        document.getElementById('divestado').style.color = 'red';
        opc = false;
    }
    else {
        estado.style.background='#FFFFFF';
	document.getElementById('divestado').style.display = 'none';
        var cidade = document.getElementById('cidade');
        if(cidade.value==0) {
            cidade.style.background='#FFFFC8';
            document.getElementById('divcidade').style.display = 'inline';
            document.getElementById('divcidade').style.color = 'red';
            opc = false;
        }
        else {
            cidade.style.background='#FFFFFF';
            document.getElementById('divcidade').style.display = 'none';
        }
    }
    var icep = document.getElementById('icep');
    if(icep.value.length==0) {
        icep.style.background='#FFFFC8';
	document.getElementById('divcep').style.display = 'inline';
        document.getElementById('divcep').style.color = 'red';
        opc = false;
    }
    else {
        icep.style.background='#FFFFFF';
	document.getElementById('divcep').style.display = 'none';
    }
    var vinculo = document.getElementsByName('vinculo');
    if(getCheckedValue(vinculo).length==0) {
	document.getElementById('divvinculo').style.display = 'inline';
        document.getElementById('divvinculo').style.color = 'red';
        opc = false;
    }
    else {
	document.getElementById('divvinculo').style.display = 'none';
    }
    var setlotacao = document.getElementById('setlotacao');
    if(setlotacao.value==0) {
        setlotacao.style.background='#FFFFC8';
	document.getElementById('divdire').style.display = 'inline';
        document.getElementById('divdire').style.color = 'red';
        opc = false;
    }
    else {
        setlotacao.style.background='#FFFFFF';
	document.getElementById('divdire').style.display = 'none';
    }
    if(acao=='I') {
        var uid = document.getElementsByName('uid');
        if(getCheckedValue(uid).length==0) {
            document.getElementById('divuid').style.display = 'inline';
            document.getElementById('divuid').style.color = 'red';
            opc = false;
        }
        else {
            document.getElementById('divuid').style.display = 'none';
        }
    }
    var email = document.getElementById('email');
    if(valMail(email.value,acao)==false) { //valida e-mail conforme tipo de vínculo
        email.style.background='#FFFFC8';
	document.getElementById('divemail').style.display = 'inline';
        document.getElementById('divemail').style.color = 'red';
        opc = false;
    }
    else {
        email.style.background='#FFFFFF';
	document.getElementById('divemail').style.display = 'none';
    }
    var emailalt = document.getElementById('emailalt');
    var exp = new RegExp("^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$");
    var achoue = exp.test(emailalt.value);
    if(achoue==false) {
//    if(emailalt.value.indexOf('.') == -1 || emailalt.value.indexOf('@') == -1 || emailalt.value.indexOf(' ') != -1) {  //valida normalmente o e-mail com @.
            emailalt.style.background='#FFFFC8';
            document.getElementById('divemailalt').style.display = 'inline';
            document.getElementById('divemailalt').style.color = 'red';
            opc = false;
    }
    else {
            emailalt.style.background='#FFFFFF';
            document.getElementById('divemailalt').style.display = 'none';
    }
    if(acao=='I') { //se for inclusão
        var password = document.getElementById('password');
        if(valPas(password.value)==false) { //valida senha, na não é possível alterar a senha na alteração de dados somente no link especifico
            password.style.background='#FFFFC8';
            document.getElementById('divpassword').style.display = 'inline';
            document.getElementById('divpassword').style.color = 'red';
            opc = false;
        }
        else {
            password.style.background='#FFFFFF';
            document.getElementById('divpassword').style.display = 'none';
            var password_conf = document.getElementById('password_conf');
            if(password_conf.value!=password.value) {
                password_conf.style.background='#FFFFC8';
                document.getElementById('divpasswordconf').style.display = 'inline';
                document.getElementById('divpasswordconf').style.color = 'red';
                opc = false;
            }
            else {
                password_conf.style.background='#FFFFFF';
                document.getElementById('divpasswordconf').style.display = 'none';
            }
        }
    }
    return opc;
}

function login() { //função para verificar se o login e senha do usuários estão corretos
  if(valLogin())  {
    criaQueryString('frmLogin'); //cria stringa dadosUsuario pegando todos os dados do formulário
    dadosUsuario += '&act=log'; //adiciona a ação que será executada pelo script no servidor
    var url = 'ajax.php';
    document.getElementById('acesso').innerHTML = 'Aguarde...';
    requisicaoHTTP('POST',url,true,6); //faça requisição POST ao servidor
  }
}

function updTip() {
   document.getElementById('acesso').innerHTML = '';
   var texto = ajax.responseText; //pega resposta do servidor
   if(texto.indexOf('Erro') != -1) { //se houve erro
        alert(texto);
   }
   else {
       var url = 'cadastrar_usuario.php?act=A'; //senão vamos direcionar o usuário para a página de alteração
       window.open(url,target='_top'); //carregando página
   }
}

function valLogin() { //verificando se usuário informou dados para login
    var nomelogin  = document.getElementById('nomelogin').value;
    var senhalogin = document.getElementById('senhalogin').value;
    if(nomelogin.length==0) { //nome de usuário não pode ser vazio
        alert('É necessário informar o usuário para login.');
        document.getElementById('nomelogin').focus();
        return false;
    }
    if(senhalogin.length==0) { //senha não pode ser vazia
        alert('É necessário informar a senha de autenticação.');
        document.getElementById('senhalogin').focus();
        return false;
    }
    return true;
}

function recSenha() { //função para criação de nova senha
  if(valRecu()) {
   criaQueryString('frmSenha'); //atribui a variavel dadosUsuario os dados do formulário frmSenha
   dadosUsuario = 'act=rse&'+dadosUsuario; //adiciona a url a ação que será realizada no servidor
   var url = 'ajax.php';
   document.getElementById('avisa').innerHTML = 'Aguarde...';
   requisicaoHTTP('POST',url,true,7); //chama a função do servidor
  }
}

function conOpc() { //trata resposta do servidor com relação a recuperação de senha
   document.getElementById('avisa').innerHTML = '';
   var texto = ajax.responseText;
   if(texto.indexOf('Erro') != -1) { //se houve erro
        alert(texto);
   }
   else {
       var url = 'pagina_msg.php'; //retorna mensagema  página de msg
       window.open(url,target='_top'); //carrega página msg
   }
}

function valRecu() { //função para validar dados para criar nova senha
    var nomelogin = document.getElementById('nomelogin').value;
    var icpf      = document.getElementById('icpf').value;
    if(nomelogin.length==0) { //verifica se infomrou login
        alert('É necessário informar o usuário para recuperação.');
        document.getElementById('nomelogin').focus();
        return false;
    }
    if(!valCpf(icpf)) { //verifica se validou cpf, cpf deve ser válido
        alert('CPF inválido.');
        document.getElementById('icpf').focus();
        return false;
    }
    return true;
}

function recChange() { //função para conectar no servidor para alterar a senha
  if(valCada()) { //verifica se os dados foram inseridos corretamente no formulário
   criaQueryString('frmChange'); //cria string com os dados a serem enviados por POST para os ervidor
   dadosUsuario = 'act=rca&'+dadosUsuario; //atribui ação aos dados
   var url = 'ajax.php';
   document.getElementById('avisa').innerHTML = 'Aguarde...';
   requisicaoHTTP('POST',url,true,8); //faz requisição ao servidor usando POST
  }
}

function liqReg() { //resposta do servidor
   document.getElementById('avisa').innerHTML = '';
   var texto = ajax.responseText;
   if(texto.indexOf('Erro') != -1) { //se houve erro
        alert(texto);
   }
   else {
       var url = 'pagina_msg.php'; //vai para a página de mensagem e mostra ao usuário
       window.open(url,target='_top');
   }
}

function valCada() { //valida dados necessário para alteração de senha
    var nomelogin = document.getElementById('nomelogin').value;
    var ioPass    = document.getElementById('ioPass').value;
    var inPass    = document.getElementById('inPass').value;
    var icPass    = document.getElementById('icPass').value;
    if(nomelogin.length==0) { //login deve ser válido
        alert('É necessário informar o usuário para recuperação.');
        document.getElementById('nomelogin').focus();
        return false;
    }
    if(ioPass.length==0) { //senha deve ser válida
        alert('É necessário informar a senha atual.');
        document.getElementById('ioPass').focus();
        return false;
    }
    if(valPas(inPass)==false) { //senha deve ser alfanumérica
        alert('A nova senha deve possuir no mínimo 8 caracteres e deve ser alfanúmerica.');
        document.getElementById('inPass').focus();
        return false;
    }
    if(inPass!=icPass) { //confirmação não bate
        alert('A confirmação não coincide com a nova senha informada.');
        document.getElementById('icPass').focus();
        return false;
    }
    return true;
}

function vinculaEmail() {
   var vinculo = document.getElementsByName('vinculo');
   var intVinc = parseInt(getCheckedValue(vinculo));
   if(intVinc<3) { //e-mail externo //Funcionário Tercerizado ou Estagiario
       var uid      = document.getElementsByName('uid');
       var uidValue = getCheckedValue(uid);
       document.getElementById('email').value = uidValue;
   }
}

function focusCPF(){
    document.getElementById('icpf').focus();
}

function OnEnter(evt) {
    var key_code = evt.keyCode  ? evt.keyCode  :
    evt.charCode ? evt.charCode :
    evt.which    ? evt.which    : void 0;
    if (key_code == 13) {
        updRow();
        return true;
    }
    return evt;
}

function fonte(par){
        //Se for pra aumentar e o tamanho ainda não passou de 15

        if(par == 'aumentar'){
            if(document.getElementById('teste').className=='fonte3'){
               document.getElementById('teste').className = "fonte1";
            }else
                document.getElementById('teste').className = "fonte2";

	//Se for pra diminuir e o tamanho ainda não é menor que 8
	}else if(par == 'diminuir'){
            if(document.getElementById('teste').className=='fonte2'){
                document.getElementById('teste').className = "fonte1";
            }else
                document.getElementById('teste').className = "fonte3";
        }else{
            document.getElementById('teste').className = "fonte1";
        }
}

function increaseFontSize() {
   var div = document.getElementsByTagName('div');
   var h1 = document.getElementsByTagName('h1');
   var p = document.getElementsByTagName('p');
   var label = document.getElementsByTagName('label');
   var input = document.getElementsByTagName('input');
   var select = document.getElementsByTagName('select');
   var a = document.getElementsByTagName('a');

   for(i=0;i<a.length;i++) {
        if(a[i].getAttribute('id') == "a1" || a[i].getAttribute('id') == "a2" || a[i].getAttribute('id') == "a3"){
        a[i].style.fontSize = 16+"px"
        }
   }
  
   for(i=0;i<select.length;i++) {
        if(select[i].getAttribute('id') != "destaque_governo"){
        if(select[i].style.fontSize) {
            s = parseInt(select[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s<=14) {
             s += 1;
        }
        select[i].style.fontSize = s+"px"
        }

   }

   for(i=0;i<div.length;i++) {
     if( div[i].getAttribute('id') != "divsair" && div[i].getAttribute('id') != "menu-acessibilidade" && div[i].getAttribute('id') != "main-menu1" && div[i].getAttribute('id') != "main-menu2" &&div[i].getAttribute('id') != "rodape"){
        if(div[i].style.fontSize) {
            s = parseInt(div[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s<=14) {
             s += 1;
        }
        div[i].style.fontSize = s+"px"
      }
   }

   for(i=0;i<input.length;i++) {
        if(input[i].style.fontSize) {
            s = parseInt(input[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s<=14) {
             s += 1;
        }
        input[i].style.fontSize = s+"px"
   }


   for(i=0;i<h1.length;i++) {
      if(h1[i].style.fontSize) {
         s = parseInt(h1[i].style.fontSize.replace("px",""));
      } else {
         s = 13;
      }
      if(s<=14) {
         s += 1;
      }
      if((h1[i].getAttribute('id') == "h11"||h1[i].getAttribute('id') == "h12"||h1[i].getAttribute('id') == "h13"||h1[i].getAttribute('id') == "h14"||h1[i].getAttribute('id') == "h15"||h1[i].getAttribute('id') == "h16" || h1[i].getAttribute('id') == "h17") && s<18){
            s+=1;
        }
      h1[i].style.fontSize = s+"px"
   }

   for(i=0;i<p.length;i++) {
      if( p[i].getAttribute('id') != "aba0" && p[i].getAttribute('id') != "aba1" && p[i].getAttribute('id') != "aba2" && p[i].getAttribute('id') != "r1"){
        if(p[i].style.fontSize) {
             s = parseInt(p[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s<=14) {
             s += 1;
        }
        p[i].style.fontSize = s+"px"
      }
   }
   for(i=0;i<label.length;i++) {
        if(label[i].style.fontSize) {
            s = parseInt(label[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(label[i].getAttribute('id') != "preencForm" && s<=14) {
             s += 1;
        }
        if(label[i].getAttribute('id') == "preencForm" && s<18){
            s+=1;
        }
        label[i].style.fontSize = s+"px"
      }
   
}

function decreaseFontSize() {
   var div = document.getElementsByTagName('div');
   var h1 = document.getElementsByTagName('h1');
   var p = document.getElementsByTagName('p');
   var label = document.getElementsByTagName('label');
   var input = document.getElementsByTagName('input');
   var select = document.getElementsByTagName('select');
   var a = document.getElementsByTagName('a');

   for(i=0;i<a.length;i++) {
        if(a[i].getAttribute('id') == "a1" || a[i].getAttribute('id') == "a2" || a[i].getAttribute('id') == "a3"){
        a[i].style.fontSize = 16+"px"
        }
   }

   for(i=0;i<select.length;i++) {
        if(select[i].getAttribute('id') != "destaque_governo"){
        if(select[i].style.fontSize) {
            s = parseInt(select[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s<=12) {
             s -= 1;
        }
        select[i].style.fontSize = s+"px"
        }

   }

   for(i=0;i<div.length;i++) {
      if( div[i].getAttribute('id') != "divsair" && div[i].getAttribute('id') != "menu-acessibilidade" && div[i].getAttribute('id') != "main-menu1" && div[i].getAttribute('id') != "main-menu2" &&div[i].getAttribute('id') != "rodape"){
        if(div[i].style.fontSize) {
             s = parseInt(div[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s>=12) {
             s -= 1;
        }
        div[i].style.fontSize = s+"px"
      }
   }
   for(i=0;i<input.length;i++) {
        if(input[i].style.fontSize) {
            s = parseInt(input[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s>=12) {
             s -= 1;
        }
        input[i].style.fontSize = s+"px"
   }
   for(i=0;i<h1.length;i++) {
      if(h1[i].style.fontSize) {
         s = parseInt(h1[i].style.fontSize.replace("px",""));
      } else {
         s = 13;
      }
      if(h1[i].getAttribute('id') != "h11" && h1[i].getAttribute('id') != "h12" && h1[i].getAttribute('id') != "h13"  && h1[i].getAttribute('id') != "h14" && h1[i].getAttribute('id') != "h15" && h1[i].getAttribute('id') != "h16" && h1[i].getAttribute('id') != "h17" && s>=12) {
         s -= 1;
      }
      if((h1[i].getAttribute('id') == "h11" || h1[i].getAttribute('id') == "h12" || h1[i].getAttribute('id') == "h13" || h1[i].getAttribute('id') == "h14" || h1[i].getAttribute('id') == "h15" || h1[i].getAttribute('id') == "h16" || h1[i].getAttribute('id') == "h17") && s>14){
            s-=1;
        }
      h1[i].style.fontSize = s+"px"
   }

   for(i=0;i<p.length;i++) {
      if( p[i].getAttribute('id') != "aba0" && p[i].getAttribute('id') != "aba1" && p[i].getAttribute('id') != "aba2" && p[i].getAttribute('id') != "r1"){
        if(p[i].style.fontSize) {
             s = parseInt(p[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if(s>=12) {
             s -= 1;
        }
        p[i].style.fontSize = s+"px"
     }
   }
   for(i=0;i<label.length;i++) {
        if(label[i].style.fontSize) {
            s = parseInt(label[i].style.fontSize.replace("px",""));
        } else {
             s = 13;
        }
        if( label[i].getAttribute('id') != "preencForm" && s>=12 ) {
             s -= 1;
        }
        if(label[i].getAttribute('id') == "preencForm" && s>14){
            s-=1;
        }
        label[i].style.fontSize = s+"px"
      }
}

function normalFontSize() {
   var div = document.getElementsByTagName('div');
   var h1 = document.getElementsByTagName('h1');
   var p = document.getElementsByTagName('p');
   var label = document.getElementsByTagName('label');
   var input = document.getElementsByTagName('input');

   for(i=0;i<div.length;i++) {
      if( div[i].getAttribute('id') != "divsair" && div[i].getAttribute('id') != "main-menu1" && div[i].getAttribute('id') != "main-menu2" &&div[i].getAttribute('id') != "rodape")
        if(div[i].style.fontSize) {
             div[i].style.fontSize = "";
      }
   }

   for(i=0;i<input.length;i++) {
        if(input[i].style.fontSize) {
            input[i].style.fontSize = "";
        }
   }

  for(i=0;i<h1.length;i++) {
      if(h1[i].style.fontSize) {
         h1[i].style.fontSize = "16px";
      }
   }

   for(i=0;i<p.length;i++) {
      if( p[i].getAttribute('id') != "aba0" && p[i].getAttribute('id') != "aba1" && p[i].getAttribute('id') != "aba2" && p[i].getAttribute('id') != "r1")
        if(p[i].style.fontSize) {
            p[i].style.fontSize = "";
     }
   }
   for(i=0;i<label.length;i++) {
        if(label[i].style.fontSize) {
            if(label[i].getAttribute('id') == "preencForm"){
                label[i].style.fontSize = 16+"px";
            }
            else
                label[i].style.fontSize = "";
      }
   }
}
   




