/* 	Conteúdo Javascript SisCpcar 2007 
* 	Programdor: Hugo Magalhães Nogueira
* 	Última atualização: 20/12/2006 
* 	hugo@barbacena.com.br
*	Todos os direitos reservados
*/


// Local Member Variables
var m_MaiorDeIdade = false;

// Instancia objeto Ajax para busca de cep
try {
    xmlhttp = new XMLHttpRequest();
} catch(ee) {
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E) {
            xmlhttp = false;
        }
    }
}

function iniciar_pagina($isPostBack)
{
  desabilitaEndereco();
  carregaCep(false);
  verificaNascimento();
  atribuiFoco('nome');
  v = iniciar_form('form1',a_campos);
  if ($isPostBack) window.scroll(0,0);
  return v;
}

function iniciar_telaAlteraDados()
{
	v = iniciar_form('formDados',telaAlteraDados_campos);
	return v;
}

function iniciar_telaAltera()
{
	v = iniciar_form('formDados',telaAltera_campos);
	return v;
}

function iniciar_telaCpf()
{
	v = iniciar_form('formDados',telaCpf_campos);
	return v;
}

function iniciar_tela1()
{
	v = iniciar_form('formStatus',tela1_campos);
	return v;
}

function verificaNascimento()
{
	var v_Nascimento = document.getElementById("nascimento").value;
	if (v_Nascimento.length == 10) 
	{
		m_MaiorDeIdade = verificaIdade(v_Nascimento);
		executaResponsavel();
	}
}

function verificaNascimentoAno()
{
	var v_Nascimento = document.getElementById("nascimento").value;
	if (v_Nascimento.length == 8)
	{
		v_Nascimento = v_Nascimento.split("/")[0] + "/" + v_Nascimento.split("/")[1] + "/19" + v_Nascimento.split("/")[2];
		document.getElementById("nascimento").value = v_Nascimento;
	}
	verificaNascimento();
}

function verificaIdade(p_Nascimento)
{
	var v_DiaServidor = getDiaServidor();
	var v_MesServidor = getMesServidor();
	var v_AnoServidor = getAnoServidor();
	var v_NascimentoArray = p_Nascimento.split("/");
	var v_Dia = v_NascimentoArray[0];
	var v_Mes = v_NascimentoArray[1];
	var v_Ano = v_NascimentoArray[2];
	if (v_Ano == (v_AnoServidor - 18))   // ano em que o candidato pode ter exatamente 18 anos
	{
		if (v_Mes == v_MesServidor)
		{
			if (v_Dia <= v_DiaServidor)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if (v_Mes < v_MesServidor)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (v_Ano < (v_AnoServidor - 18))
	{
		return true;					// é maior de idade
	}
	else
	{
		return false;					// é menor de idade
	}
}

function executaResponsavel()
{
	var v_ConteudoDiv = '<div style="margin: 8px 15px 8px 15px; font-family:"Trebuchet MS"; font-size:11px; color:#000033;">Preencha os dados do seu responsável legal (pai, mãe ou tutor).</div>';
	if (m_MaiorDeIdade)
	{
		document.getElementById("DivResponsavel").innerHTML = "";
		visibilidadeResponsavel(false);
	}
	else
	{
		document.getElementById("DivResponsavel").innerHTML = v_ConteudoDiv;
		visibilidadeResponsavel(true);
	}
}

function visibilidadeResponsavel(p_Visibilidade)
{
	v_Classe = (p_Visibilidade) ? 'field' : 'fieldDisabled';
	document.getElementById("nomeResp").readOnly = !p_Visibilidade;
	//document.getElementById("cidadeResp").readOnly = !p_Visibilidade;
	document.getElementById("cpfResp").readOnly = !p_Visibilidade;
	/*document.getElementById("nomeResp").value = "";
	document.getElementById("cidadeResp").value = "";
	document.getElementById("cpfResp").value = "";*/
	document.getElementById("nomeResp").className = v_Classe;
	//document.getElementById("cidadeResp").className = v_Classe;
	document.getElementById("cpfResp").className = v_Classe;
}

function carregaCep(IsPostBack){
	
	var cepValor = document.getElementById("cep1").value + document.getElementById("cep2").value;
	if (cepValor.length < 7) {
		if (IsPostBack)
		{
			alert('Preencha o CEP completo para que a validação possa ser feita.');
			if (cepValor.length < 5)
				document.getElementById("cep1").focus();
			else
				document.getElementById("cep2").focus();
		}
		return false;
	}
	if (IsPostBack) document.getElementById("endereco").value = "Aguarde, processando...";
	//cepValor = cepValor.substr(0, 5) + cepValor.substr(6,8);
    xmlhttp.open("GET", "carregaCep.php?cep="+cepValor,true);
    xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4){
            var texto=xmlhttp.responseText;

            texto=texto.replace(/\+/g," ");
            texto=unescape(texto);
			cepAtribuiValores(texto,IsPostBack);
		}
    }
    xmlhttp.send(null);
}

function cepAtribuiValores(dados,IsPostBack) {
	if (dados.indexOf("|") == 0) 
	{
		//alert('Cep inválido!');
		/*document.getElementById("cidade").value = "";
		document.getElementById("uf").value = "";
		document.getElementById("bairro").value = "";
		document.getElementById("endereco").value = "";*/
		//return false;
		
		trataTipoCep("I");
		if (IsPostBack)
		{
			limpaCamposEndereco();
		}
	}
	else 
	{
		campos = dados.split("|");
		document.getElementById("cidade").value = campos[1];
		document.getElementById("uf").value = campos[0];
		document.getElementById("bairro").value = campos[2];
		document.getElementById("endereco").value = campos[5];
		var tipoCep = campos[4];
		trataTipoCep(tipoCep);
	}
}

function trataTipoCep(p_tipoCep) 
{
	var ordemCamposI = new Array('nome','nascimento','sexo','ano','local','cep1','cep2','btnValidaCep','endereco','bairro','numero','complemento','bairro','cidade','uf','telefone','nomeResp','cpfResp');
	var ordemCamposN = new Array('nome','nascimento','sexo','ano','local','cep1','cep2','btnValidaCep','numero','complemento','telefone','nomeResp','cpfResp');
	var ordemCamposB = new Array('nome','nascimento','sexo','ano','local','cep1','cep2','btnValidaCep','complemento','telefone','nomeResp','cpfResp');
	var ordemCamposC = new Array('nome','nascimento','sexo','ano','local','cep1','cep2','btnValidaCep','endereco','numero','complemento','bairro','telefone','nomeResp','cpfResp');
	document.getElementById("tipo_cep").value = p_tipoCep;
	
	var v_liBairro = document.getElementById('liBairro');
	var lista = document.getElementById('listaPrincipal');
	
	/* Tipo de cep inválido, inexistente no banco */
	if (p_tipoCep == 'I')
	{
		habilitaEndereco();
		lista.insertBefore(m_liNum, v_liBairro);
		lista.insertBefore(m_liComp, v_liBairro);
		document.getElementById("cidade").focus();
		atribuiIndicesDeTab(ordemCamposI);
	}
	if (p_tipoCep == 'N')
	{
		desabilitaEndereco();
		lista.insertBefore(m_liNum, v_liBairro);
		lista.insertBefore(m_liComp, v_liBairro);
		document.getElementById("numero").focus();
		atribuiIndicesDeTab(ordemCamposN);
	}
	else if (p_tipoCep == 'B')
	{
		lista.insertBefore(m_liComp, v_liBairro);
		desabilitaEndereco();
		document.getElementById("complemento").focus();
		atribuiIndicesDeTab(ordemCamposB);
	}
	else if (p_tipoCep == 'C')
	{
		lista.insertBefore(m_liNum, v_liBairro);
		lista.insertBefore(m_liComp, v_liBairro);	
		habilitaCampo("endereco");
		habilitaCampo("bairro");
		desabilitaCampo("cidade");
		desabilitaCampo("uf");
		document.getElementById("endereco").focus();
		atribuiIndicesDeTab(ordemCamposC);
	}
	else 
	{
		habilitaEndereco();
		lista.insertBefore(m_liNum, v_liBairro);
		lista.insertBefore(m_liComp, v_liBairro);
		document.getElementById("endereco").focus();
		atribuiIndicesDeTab(ordemCamposI);
	}
		
}

function corrigirForm()
{
	document.getElementById("confirmados").value = 0;
	document.getElementById("corrigir").value = 1;
	document.form2.submit();	
}

function desabilitaEndereco() 
{
	desabilitaCampo("cidade");
	desabilitaCampo("uf");
	desabilitaCampo("bairro");
	desabilitaCampo("endereco");
}

function habilitaEndereco() 
{
	habilitaCampo("cidade");
	habilitaCampo("uf");
	habilitaCampo("bairro");
	habilitaCampo("endereco");
}

function habilitaCampo(p_Campo)
{
	document.getElementById(p_Campo).readOnly = false;
	document.getElementById(p_Campo).className = 'field';
}

function desabilitaCampo(p_Campo)
{
	document.getElementById(p_Campo).readOnly = true;
	document.getElementById(p_Campo).className = 'fieldDisabled';
}

function limpaCamposEndereco()
{
	document.getElementById("cidade").value = "";
	document.getElementById("uf").value = "";
	document.getElementById("bairro").value = "";
	document.getElementById("endereco").value = "";
	document.getElementById("numero").value = "";
	document.getElementById("complemento").value = "";
}

function limpar()
{
	document.getElementById("cidade").value = "";
	document.getElementById("uf").value = "";
	document.getElementById("bairro").value = "";
	document.getElementById("endereco").value = "";
	document.getElementById("nome").value = "";
	document.getElementById("nascimento").value = "";
	document.getElementById("cep1").value = "";
	document.getElementById("cep2").value = "";
	document.getElementById("telefone").value = "";
	document.getElementById("nomeResp").value = "";
	document.getElementById("cpfResp").value = "";
	document.getElementById("ano").selectedIndex = 0;
	document.getElementById("local").selectedIndex = 0;
	desabilitaEndereco();
	carregaCep(false);	
	visibilidadeResponsavel(false);
	document.getElementById("DivResponsavel").innerHTML = "";
	document.getElementById("nome").focus();
}

function enviaFormPrincipal()
{
	//habilitaCampoSelect("uf");
	document.getElementById("btnContinuar").value = "Aguarde...";
	document.getElementById("btnContinuar").disabled = true;
	document.form1.submit();
}

function enviaFormConfirmacao()
{
	//habilitaCampoSelect("uf");
	document.getElementById("btnConfirmar").value = "Aguarde...";
	document.getElementById("btnConfirmar").disabled = true;
	document.form2.submit();
}

function manualOver()
{
	document.getElementById("tdManual").style.backgroundColor = "#FFD5D5";
	
}

function manualOut()
{
	document.getElementById("tdManual").style.backgroundColor = "#FFF9F9";
}

function manualClick()
{
	abreDocumento("manual.pdf");
	//window.open("documentos/manual.pdf","Manual");	
}

function abreDocumento(p_Doc) 
{
	window.open("documentos/"+p_Doc,"SisCpcar_doc","width=550, height=500, top=0, left=0, toolbar=0, menubar=1, location=0, status=0, scrollbars=1, resizable=1");
}

function abreInstrEsp() 
{
	window.open("http://www.fab.mil.br/portal/cabine/concursos/01_IE_CPCAR_2011.pdf","SisCpcar_doc","width=550, height=500, top=0, left=0, toolbar=0, menubar=1, location=0, status=0, scrollbars=1, resizable=1");
}

function abreAnexos() 
{
	window.open("http://www.fab.mil.br/portal/cabine/concursos/CPCAR/CPCAR_2009/02-AN_IE_CPCAR_2009.pdf","SisCpcar_doc","width=550, height=500, top=0, left=0, toolbar=0, menubar=1, location=0, status=0, scrollbars=1, resizable=1");
}

function abreIca() 
{
	window.open("http://www.fab.mil.br/portal/concursos/ICA_160-6_2009.pdf","SisCpcar_doc","width=550, height=500, top=0, left=0, toolbar=0, menubar=1, location=0, status=0, scrollbars=1, resizable=1");
}

function imprimeDocumento(p_Doc) 
{
	window.open("documentos/impressao.php?doc="+p_Doc,"SisCpcar_doc","width=800, height=500, top=0, left=0, toolbar=0, menubar=1, location=0, status=0, scrollbars=0, resizable=0");
}

var tela1_campos = {
	
	'cpf': {'l': 'CPF','r':true,'t':'t_cpf','mx': 14,'help':'Entre com o CPF do Candidato, no formato XXX.XXX.XXX-XX','mascara':'###.###.###-##','tab':0}

//NUNCA DEIXAR UMA VIRGULA NO FINAL DESSES VALORES!!!!!! 
};

var telaAltera_campos = {
	'nascimento': {'l': 'Data de Nascimento','r': true,'t':'t_nascimento','mn': 10,'mx': 10,'help':'Entre com a data de nascimento, no formato dd/mm/AAAA','mascara':'##/##/####','tab':0},
	'cpf': {'l': 'CPF','r':true,'t':'t_cpf','mx': 14,'help':'Entre com o CPF do Candidato, no formato XXX.XXX.XXX-XX','mascara':'###.###.###-##','tab':0}

//NUNCA DEIXAR UMA VIRGULA NO FINAL DESSES VALORES!!!!!! 
};

var telaAlteraDados_campos = {	
	'nascimento': {'l': 'Data de Nascimento','r': true,'t':'t_nascimento','mn': 10,'mx': 10,'help':'Entre com a data de Praça do Candidato, no formato dd/mm/AAAA','mascara':'##/##/####','tab':0}

//NUNCA DEIXAR UMA VIRGULA NO FINAL DESSES VALORES!!!!!! 
};


var telaCpf_campos = {
	
	'telefone1': {'l': 'Telefone','r':true,'t':'t_telefone1','help':'Entre com o Telefone no formato (XX) XXXX-XXXX','mascara':'(##) ####-####','tab':1},
	'telefone2': {'l': 'Telefone','r':true,'t':'t_telefone2','help':'Entre com o Telefone  no formato (XX) XXXX-XXXX','mascara':'(##) ####-####','tab':1}

//NUNCA DEIXAR UMA VIRGULA NO FINAL DESSES VALORES!!!!!! 
};

var a_campos = {
	'endereco': {'l': 'Endereco','r':true,'t':'t_endereco','help':'Preencha o Cep do candidato para que o sistema identifique o endereço.','mascara':'','tab':1},
	'nome': {'l': 'Nome','r':true,'t':'t_nome','help':'Entre com o nome do candidato.','mascara':'','tab':1},
	'candCpf': {'l': 'Cpf','r':true,'t':'t_candCpf','help':'Entre com o cpf do candidato, no formato XXX.XXX.XXX-XX','mascara':'###.###.###-##','tab':0},
	'cpf_cadunico': {'l': 'Cpf','r':true,'t':'t_cpf_cadunico','help':'Entre com o cpf do candidato cadastrato no CadUnico, no formato XXX.XXX.XXX-XX','mascara':'###.###.###-##','tab':0},
	'cep1': {'l': 'Cep1','r':true,'t':'t_cep1','help':'Entre com o CEP do Candidato, no formato XXXXX','mascara':'#####','tab':1},
	'cep2': {'l': 'Cep2','r':true,'t':'t_cep2','help':'Entre com o CEP do Candidato, no formato XXX','mascara':'###','tab':1},
	'cpfResp': {'l': 'CPF','r':true,'t':'t_cpf','mx': 14,'help':'Entre com o CPF do Responsável do Candidato, no formato XXX.XXX.XXX-XX','mascara':'###.###.###-##','tab':0},
	'telefone': {'l': 'Telefone','r':true,'t':'t_telefone','help':'Entre com o Telefone do Candidato, no formato (XX) XXXX-XXXX','mascara':'(##) ####-####','tab':1},	
	'nascimento': {'l': 'Data de Nascimento','r': true,'t':'t_nascimento','mn': 10,'mx': 10,'help':'Entre com a data de Nascimento do Candidato, no formato dd/mm/AAAA','mascara':'##/##/####','tab':0},
	'rg_dtexp_cadunico': {'l': 'Data de Expedição','r': true,'t':'t_nascimento','mn': 10,'mx': 10,'help':'Entre com a data de Expedição, no formato dd/mm/AAAA','mascara':'##/##/####','tab':0},
	'local': {'l': 'Local','r': true,'t':'t_local','help':'Escolha o local qual deseja prestar o Exame de Admissão (provas).'},
	'ano': {'l': 'Ano','r': true,'t':'t_ano','help':'Escolha o ano (série) para o qual deseja prestar o Exame de Admissão.'}


//NUNCA DEIXAR UMA VIRGULA NO FINAL DESSES VALORES!!!!!! 
};

var v;
var exibe_assistente = '';

function forcaMaiuscula(campo)
{
	//document.getElementById(campo).value = document.getElementById(campo).value.toUpperCase();
}

function cepPulaCampo()
{
	if (document.getElementById('cep1').value.length == 5)
		document.getElementById('cep2').focus();
}

function cepPulaCampo2()
{
	if (document.getElementById('cep2').value.length == 3)
		//document.getElementById('btnValidaCep').focus();
		carregaCep(true);
}

function campoMaiusculasSemEspeciais(campo)
{
	var valor = document.getElementById(campo).value;
	var valid = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-';
	var valorFinal = "";
	
	for(var i=0; i < valor.length; i++ )
	{
		str = valor.substr(i,1);
		str = substituiAcentuacao(str.toUpperCase());
		if ((str == " ") || (valid.indexOf(str) > -1)) 
		{
			valorFinal += str;	
		}
	}
	document.getElementById(campo).value = valorFinal;
}

function substituiAcentuacao(str)
{
	var aSub = 'ÀÁÂÃÄÅÆ';
	var eSub = 'ÉÈÊË';
	var iSub = 'ÌÍÎÏ';
	var oSub = 'ÒÓÔÕÖ';
	var uSub = 'ÙÚÛÜ';
	var cSub = 'Ç';
	
	if (aSub.indexOf(str) > -1)
		return 'A';
	else if (eSub.indexOf(str) > -1)
		return 'E';
	else if (iSub.indexOf(str) > -1)
		return 'I';
	else if (oSub.indexOf(str) > -1)
		return 'O';
	else if (uSub.indexOf(str) > -1)
		return 'U';
	else if (cSub.indexOf(str) > -1)
		return 'C';
	else return str;
}

function atribuiIndicesDeTab(ordemCampos)
{
	for(var i=0; i < ordemCampos.length; i++ )
	{
		//alert(ordemCampos1[i]);
		document.getElementById(ordemCampos[i]).tabIndex = i + 1;
	}
}

function atribuiFoco(campo)
{
	document.getElementById(campo).focus();
}

function popupEncerradas()
{
	popup('encerradas.php', 250, 150, 0);	
}

function popupNaoIniciadas()
{
	popup('naoiniciadas.php', 250, 220, 0);	
}

function popup(url, width, height, scrol)
{
	window.open(url,"_blank","resizable=no,toolbar=no,status=no,menubar=no,scrollbars=" + scrol + ",width=" + width + ",height=" + height + ",top=70,left=120");
}

function verificaProtocolo()
{
	if (document.getElementById("protocolo").value == "")
	{
		alert("Por favor, preencha o número da inscrição.");
	}
	else 
	{
		document.form1.submit();
	}
}

function carregaProtocolo()
{
	if (document.getElementById("cpf").value == "")
	{
		alert("Por favor, preencha o cpf do candidato.");
	}
	else 
	{
		xmlhttp.open("GET", "carregaProtocolo.php?cpf="+document.getElementById('cpf').value,true);
		xmlhttp.onreadystatechange=function() {
	
			if (xmlhttp.readyState==4){
				var texto=xmlhttp.responseText;
				texto=unescape(texto);
				if (texto == "")
				{
					document.formStatus.submit();
				}
				else
				{
					document.getElementById('protocolo').value = texto;
					document.formProtocolo.submit();
				}
			}
		}
		xmlhttp.send(null);	
	}
}

function copiaCpfResp()
{
	if(document.getElementById('rdCpfResp').checked) 
	{
		document.getElementById('cpfResp').value = document.getElementById('candCpf').value;
	}
}

function criaLiNum(value)
{
	var li  = document.createElement('li');
	var label = document.createElement('label');
	var b = document.createElement('b');
	var input = document.createElement('input');
	
	var titulo = document.createTextNode('Número:');
	input.setAttribute('maxlength','15');
	input.setAttribute('name','numero');
	input.setAttribute('type','text');
	input.setAttribute('class','field');
	input.setAttribute('id','numero');
	input.setAttribute('value',value);
	input.setAttribute('onKeyUp','campoMaiusculasSemEspeciais(\'numero\');');
	
	b.appendChild(titulo);
	label.appendChild(b);
	li.appendChild(label);
	li.appendChild(input);
	
	return li;
}

function criaLiComp(value)
{
	var li  = document.createElement('li');
	var label = document.createElement('label');
	var b = document.createElement('b');
	var input = document.createElement('input');
	
	var titulo = document.createTextNode('Complemento:');
	input.setAttribute('maxlength','15');
	input.setAttribute('name','complemento');
	input.setAttribute('type','text');
	input.setAttribute('class','field');
	input.setAttribute('id','complemento');
	input.setAttribute('value',value);
	input.setAttribute('onKeyUp','campoMaiusculasSemEspeciais(\'complemento\');');
	
	b.appendChild(titulo);
	label.appendChild(b);
	li.appendChild(label);
	li.appendChild(input);
	
	return li;
}

function desabilitaOmap() 
{
	desabilitaCampo("orgMilitar");
	document.getElementById('militarNao').checked = true;
}

function habilitaOmap() 
{
	habilitaCampo("orgMilitar");
	document.getElementById('militarSim').checked = true;
}