// JavaScript Document

// variáveis globais
var http;
var select_id;

//===================================================================================================================================
function Tipo_Pessoa(object) {

	if (object.value == 1) {
			faculdade.style.display = "block";
			graduacao.style.display = "none";
	}
	else {
			graduacao.style.display = "block";
			faculdade.style.display = "none";
	}
}
//===================================================================================================================================
function Tipo_Formacao(c) {

	if (document.getElementById("form_trabalho").cbt_tipo_formacao[0].checked) {
		document.getElementById('escola').style.display = "block";
		document.getElementById('faculdade').style.display = "none";
		
		document.getElementById("cbt_facul_curso").value = "";
		document.getElementById("cbt_facul_local").value = "";
		document.getElementById("cbt_facul_data").value = "";
	}
	else if (document.getElementById("form_trabalho").cbt_tipo_formacao[1].checked) {
		document.getElementById('escola').style.display = "block";
		document.getElementById('faculdade').style.display = "none";
		
		document.getElementById("cbt_facul_curso").value = "";
		document.getElementById("cbt_facul_local").value = "";
		document.getElementById("cbt_facul_data").value = "";
	}
	else if (document.getElementById("form_trabalho").cbt_tipo_formacao[2].checked) {
		document.getElementById('escola').style.display = "none";
		document.getElementById('faculdade').style.display = "block";
		
		document.getElementById("cbt_escola_serie").value = "";
		document.getElementById("cbt_escola_local").value = "";
		document.getElementById("cbt_escola_data").value = "";
	}
}
//===================================================================================================================================
function add_curso() {
	
	check_01 = document.getElementById("cbt_add_curso2").checked;
	check_02 = document.getElementById("cbt_add_curso3").checked;

	if (check_01) {
		document.getElementById('curso02').style.display = "block";
	}else{
		if (check_02) { // Caso o curso 2 esteja sendo desmarcado, mas o curso 3 esteja marcado.
			// Simulando um click no cbt_add_curso3
			document.getElementById("cbt_add_curso3").checked = false;
			add_curso();
		}else{
			document.getElementById('curso02').style.display = "none";
			document.getElementById('cbt_curso2_nome').value = "";
			document.getElementById('cbt_curso2_local').value = "";
			document.getElementById('cbt_curso2_data').value = "";
		}
	}

	if (check_02) {
		document.getElementById('curso03').style.display = "block";
	}else{
		document.getElementById('curso03').style.display = "none";
		document.getElementById('cbt_curso3_nome').value = "";
		document.getElementById('cbt_curso3_local').value = "";
		document.getElementById('cbt_curso3_data').value = "";
	}
}
//===================================================================================================================================
function add_idioma() {
	
	add_idioma2 = document.getElementById("cbt_add_idioma2").checked;
	add_idioma3 = document.getElementById("cbt_add_idioma3").checked;
	
	if (add_idioma2) {
		document.getElementById("idioma02").style.display = "block";
	}else{
		if (add_idioma3) { // Caso o idioma 2 esteja sendo desmarcado, mas o idioma 3 esteja marcado.
			// Simulando um click no cbt_add_idioma3
			document.getElementById("cbt_add_idioma3").checked = false;
			add_idioma();
		}else{
			document.getElementById('idioma02').style.display = "none";
			document.getElementById("cbt_idioma2").value = "";
			document.getElementById("cbt_idioma2_estab").value = "";
			document.getElementById("cbt_idioma2_concl").value = "";
		}
	}
	
	if (add_idioma3) {
		document.getElementById('idioma03').style.display = "block";
	}else{
		document.getElementById('idioma03').style.display = "none";
		document.getElementById("cbt_idioma3").value = "";
		document.getElementById("cbt_idioma3_estab").value = "";
		document.getElementById("cbt_idioma3_concl").value = "";
	}
	
}
//===================================================================================================================================
function add_emp_ant() { // Adiciona uma empresa anterior na qual o usuário já trabalhou

	add_emp02 = document.getElementById("cbt_add_emp_ant_02").checked;
	add_emp03 = document.getElementById("cbt_add_emp_ant_03").checked;
	
	if (add_emp02) {
		document.getElementById("emp_ant02").style.display = "block";
	}else{
		if (add_emp03) { // Caso a empresa anterior 2 esteja sendo desmarcado, mas a empresa anterior 3 esteja marcada.
			// Simulando um click no cbt_add_emp_ant_03
			document.getElementById("cbt_add_emp_ant_03").checked = false;
			add_emp_ant();
		}else{
			document.getElementById('emp_ant02').style.display = "none";
			document.getElementById("cbt_emp_ant02_nome").value = "";
			document.getElementById("cbt_emp_ant02_cargo").value = "";
			document.getElementById("cbt_emp_ant02_admiss").value = "";
			document.getElementById("cbt_emp_ant02_demiss").value = "";
			document.getElementById("cbt_emp_ant02_ativ").value = "";
		}
	}
	
	if (add_emp03) {
		document.getElementById('emp_ant03').style.display = "block";
	}else{
		document.getElementById('emp_ant03').style.display = "none";
		document.getElementById("cbt_emp_ant03_nome").value = "";
		document.getElementById("cbt_emp_ant03_cargo").value = "";
		document.getElementById("cbt_emp_ant03_admiss").value = "";
		document.getElementById("cbt_emp_ant03_demiss").value = "";
		document.getElementById("cbt_emp_ant03_ativ").value = "";
	}
}
//===================================================================================================================================
function add_cargo_pretendido() {
	
	add_cargo02 = document.getElementById("cbt_add_cargo02").checked;
	add_cargo03 = document.getElementById("cbt_add_cargo03").checked;
	
	if (add_cargo02) {
		document.getElementById("cargo02").style.display = "block";
	}else{
		if (add_cargo03) { // Caso o cargo pretendido anterior 2 esteja sendo desmarcado, mas o cargo anterior 3 esteja marcado.
			// Simulando um click no cbt_add_cargo_03
			document.getElementById("cbt_add_cargo03").checked = false;
			add_cargo_pretendido();
		}else{
			document.getElementById('cargo02').style.display = "none";
			document.getElementById('cbt_cargo02_area_negocio').value = "";
			document.getElementById("cbt_cargo02_cargo").options.length = 0	// elimina as opções
			document.getElementById('cbt_cargo02_exp').value = "";
		}
	}
	
	if (add_cargo03) {
		document.getElementById('cargo03').style.display = "block";
	}else{
		document.getElementById('cargo03').style.display = "none";
		document.getElementById('cbt_cargo03_area_negocio').value = "";
		document.getElementById("cbt_cargo03_cargo").options.length = 0	// elimina as opções
		document.getElementById('cbt_cargo03_exp').value = "";
	}
}
//===================================================================================================================================

function preencherMesmoEndereco() {
	if (document.form_cliente.mesmo_endereco.checked) {
		document.form_cliente.endereco_entrega.value = document.form_cliente.endereco.value;
		document.form_cliente.numero_entrega.value = document.form_cliente.numero.value;
		document.form_cliente.complemento_entrega.value = document.form_cliente.complemento.value;
		document.form_cliente.bairro_entrega.value = document.form_cliente.bairro.value;
		document.form_cliente.cidade_entrega.value = document.form_cliente.cidade.value;
		document.form_cliente.estado_entrega.value = document.form_cliente.estado.selectedIndex;
		document.form_cliente.cep_entrega.value = document.form_cliente.cep.value;
	}
	else
	{
		document.form_cliente.endereco_entrega.value = "";
		document.form_cliente.numero_entrega.value = "";
		document.form_cliente.complemento_entrega.value = "";
		document.form_cliente.bairro_entrega.value = "";
		document.form_cliente.cidade_entrega.value = "";
		document.form_cliente.estado_entrega.value = "";
		document.form_cliente.cep_entrega.value = "";
	}
}
//===================================================================================================================================

/*
 * Esta função realiza a formatação das máscaras que podem ser aplicadas nos campos do formulário.
 * Utilizar '?' somente para números, caso seja permido qualquer caracteres utilizar '!'.
 */

function formatar_mascara(campo, mask, evt) {
 
	if(document.all) { // Internet Explorer
		key = evt.keyCode;
	}
	else { // Outros
		key = evt.which;
	}
	
	if (key == 8) {
		return true;
	}
	
	string = campo.value;  
	i = string.length;
	
	if (i < mask.length) {
		if (mask.charAt(i) == '?') {
			return (key > 47 && key < 58);
		} else {
			if (mask.charAt(i) == '!') {  return true;  }
			for (c = i; c < mask.length; c++) {
				if (mask.charAt(c) != '?' && mask.charAt(c) != '!')
					campo.value = campo.value + mask.charAt(c);
				else if (mask.charAt(c) == '!'){
					return true;
				} else {
					return (key > 47 && key < 58);
				}
			}
		}
	} else return false;
}

//=================================================================================================================================
// Função que valida a data informada pelo usuário
function valida_data(campo) {
	
	var data_valida = true;
	if (campo.value.length == 10) {
		
		data = campo.value.split("/");
		var dia = parseInt( data[0] );
		var mes = parseInt( data[1] );
		var ano = parseInt( data[2] );
		
		var data_corrente = new Date();
		var ano_bissexto = false;
		
		if ( (ano < 1900) || (ano > data_corrente.getFullYear()) )  {
			data_valida = false;	
		}else {
			if (mes == 2) {	//Fevereiro
				/*
				* Para saber se um ano é bissexto ou não, deve-se seguir as regras abaixo:
				* 1. Se o ano não termina em 00, ele é bissexto se for divisível por 4. Exemplos: 1988, 1992, 1996, 2004, e assim por diante;
				* 2. Se o ano termina em 00, ele é bissexto se for divisível por 400. Exemplos: 2000, 2400, 2800, e assim por diante.
				*/
				if ( (data[2].substr(-2) != "00") && (ano % 4 == 0)) {
					ano_bisssexto = true;
				}else if ((data[2].substr(-2) != "00") && (ano % 400 == 0)) {
					ano_bissexto = true;
				}
				
				if ((ano_bissexto) && (dia > 29)) {
					data_valida = false;
				}else if ((!ano_bissexto) && (dia > 28)) {
					data_valida = false;
				}
			
			/*
			* Até Julho (mes 07) todos os meses ímpares possuem 31 dias, enquanto os pares possuem 30 (excessão à fevereiro [mes 02])
			* Apartir de Agosto (mes 08) isso se inverte.
			*/
			}else if (mes <= 7) {	// Julho
				if (mes % 2 == 0) {	// Mes par
					if (dia > 30) { data_valida = false; }
				}else{
					if (dia > 31) { data_valida = false; }
				}
			}else if (mes > 7) {
				if (mes % 2 == 0) {	// Mes par
					if (dia > 31) { data_valida = false; }
				}else{
					if (dia > 30) { data_valida = false; }
				}
			}
		}
	}else if (campo.value.length != 0){
		data_valida = false;
	}
	
	// De acordo com o resultado, o focus é posicionado no campo de data ou não
	if (!data_valida) {
		alert("A data informada e invalida.");
	}
	
	return data_valida;
}

//=================================================================================================================================
// Função que valida o cep informado pelo usuário
// Para verificar o cep basta validar o tamanho do mesmo. (já que a máscara é aplicada automaticamente e o campo não aceita letras.)
function valida_cep(campo) {
	cep_valido = false;
	if (campo.value.length == 9) {
		cep_valido = true;
	}
	if (!cep_valido) {
		alert('O numero de cep informado e invalido.');
	}
	return cep_valido;
}

//=================================================================================================================================
// Função que valida o email informado pelo usuário
function valida_email (mail) {
	if ( (mail.indexOf("@") == -1) || (mail.indexOf(".") == -1) || (mail.length == 2) || (mail.substr(0,1) == "@") || (mail.substr(-1) == ".") || (mail.indexOf("@.") != -1) ) {
		alert("O email informado e invalido.");
		return false;
	}
}

//=================================================================================================================================
// FUNÇÃO IMPUT BUSCA
//=================================================================================================================================
function limpa_busca() 
{
        busca_digitada = document.getElementById('busca_cont').value;

        if (busca_digitada == "Buscar") 
        {
                document.getElementById('busca_cont').value = "";
        }
        else
        {
                document.getElementById('busca_cont').value = busca_digitada;
        }
}

function verifica_busca() 
{
        busca_digitada = document.getElementById('busca_cont').value;
        
        if(busca_digitada == "")
        {
                document.getElementById('busca_cont').value = "Buscar";
        }
        else if ((busca_digitada != "Buscar") && (busca_digitada != ""))
        {
                document.getElementById('busca_cont').value = busca_digitada;
        }
}
//=================================================================================================================================
// FUNÇÃO IMPUT NEWSLETTER - NOME COMPLETO
//=================================================================================================================================
function limpa_nome_news() 
{
        busca_nome_news_digitada = document.getElementById('nome_news').value;

        if (busca_nome_news_digitada == "Nome Completo") 
        {
                document.getElementById('nome_news').value = "";
        }
        else
        {
                document.getElementById('nome_news').value = busca_nome_news_digitada;
        }
}

function verifica_nome_news() 
{
        busca_nome_news_digitada = document.getElementById('nome_news').value;
        
        if(busca_nome_news_digitada == "")
        {
                document.getElementById('nome_news').value = "Nome Completo";
        }
        else if ((busca_nome_news_digitada != "Nome Completo") && (busca_nome_news_digitada != ""))
        {
                document.getElementById('nome_news').value = busca_nome_news_digitada;
        }
}
//=================================================================================================================================
// FUNÇÃO IMPUT NEWSLETTER - EMAIL
//=================================================================================================================================
function limpa_email_news() 
{
        busca_email_news_digitada = document.getElementById('email_news').value;

        if (busca_email_news_digitada == "Seu E-mail") 
        {
                document.getElementById('email_news').value = "";
        }
        else
        {
                document.getElementById('email_news').value = busca_email_news_digitada;
        }
}

function verifica_email_news() 
{
        busca_email_news_digitada = document.getElementById('email_news').value;
        
        if(busca_email_news_digitada == "")
        {
                document.getElementById('email_news').value = "Seu E-mail";
        }
        else if ((busca_email_news_digitada != "Seu E-mail") && (busca_email_news_digitada != ""))
        {
                document.getElementById('email_news').value = busca_email_news_digitada;
        }
}
//===================================================================================================================================
// Essa função é somente para identificar o Navegador e suporte ao XMLHttpRequest.

function getHTTPObject() {
    var req;
    try {
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
            if (req.readyState == null) {
                req.readyState = 1;
                req.addEventListener("load", function() {
                    req.readyState = 4;
                    if (typeof req.onReadyStateChange == "function") {
                        req.onReadyStateChange();
                    }
                }, false);  
            }
            return req; 
        }

        if (window.ActiveXObject) {
            var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
            for (var i = 0; i < prefixes.length; i++) {
                try {
                    req = new ActiveXObject(prefixes[i] + ".XmlHttp");
                    return req;
                } catch (ex) {};
            }
        }
    } catch (ex) {}

	alert("O objeto XmlHttp não é suportado pelo seu navegador.");
}

//===================================================================================================================================
// Função que preenche as selects de cargo quando a área de negócio é preenchida

function preenche_cargo(num, cod_cargo_01) {
	// num indica se é o cargo pretendido 1°, 2°, ou 3°
	
	select_id = "";
	
	if (num == 1) {
		select_id  = "cbt_cargo01_cargo";
	} else if (num == 2) {
		select_id  = "cbt_cargo02_cargo";
	} else if (num == 3 ) {
		select_id  = "cbt_cargo03_cargo";
	}
	
	http = getHTTPObject();
	http.open("GET", "http://www.azimute.eng.br/lib/pesq_cargo02.php?cod_cargo_01="+cod_cargo_01, true);
	http.onreadystatechange = handleHttpResponse;
    http.send(null);
}

//===================================================================================================================================
// Função utilizada para processar a resposta (AJAX) de pesq_cargo02.php

function handleHttpResponse() {
	if (http.readyState == 4) {
			
		campo_select = document.getElementById(select_id);
		
		//antes de preencher com as novas opções, limpa as antigas
        campo_select.options.length = 0;
		
		result = http.responseText.split("||");
        for (cont = 0; cont < result.length - 1; cont++) {
			// criando a nova opção
            opcao = result[cont].split("|");
            campo_select.options[cont] = new Option(opcao[1]);

			// setando o atributo value
			atributo = document.createAttribute("value");
			atributo.value = opcao[0];
			campo_select.options[cont].setAttributeNode(atributo);
        }	
    }
}


// Função que verifica se todos os campos obrigatórios da página "trabalhe-conosco" foram preenchidos
//===================================================================================================================================
function camp_obrig_01() {
	ret = true;
	
	campos_obrig = Array(10);
	campos_obrig[00] = "cbt_nome_completo";
	campos_obrig[01] = "cbt_data_nasc";
	campos_obrig[02] = "cbt_sexo";
	campos_obrig[03] = "cbt_estado_civil";
	campos_obrig[04] = "cbt_estado";
	campos_obrig[05] = "cbt_cidade";
	campos_obrig[06] = "cbt_bairro";
	campos_obrig[07] = "cbt_endereco";
	campos_obrig[08] = "cbt_cep";
	campos_obrig[09] = "cbt_email";
	
	for (cont = 0; cont < campos_obrig.length; cont++) {
		if (document.getElementById(campos_obrig[cont]).value == "") {
			ret = false;
			break;
		}
	}
	
	if (ret == false) {
		alert("Todos os campos obrigatorios precisam ser preenchidos.")
		document.getElementById(campos_obrig[cont]).focus();
	}else{
		document.getElementById('form_trabalho').action = 'http://www.azimute.eng.br/sessao-trabalhe-conosco-01/continuar';
		document.getElementById('form_trabalho').submit();	
	}

	return ret;
}

// Função que verifica se todos os campos obrigatórios da página "trabalhe-conosco-02" foram preenchidos
//===================================================================================================================================
function camp_obrig_02() {
	//num_action indica se o link clicado foi o de avançar ou o de retornar
	ret = true;
	
	campos_obrig = Array(3);
	
	if (document.getElementById("form_trabalho").cbt_tipo_formacao[0].checked || document.getElementById("form_trabalho").cbt_tipo_formacao[1].checked) {
		campos_obrig[00] = "cbt_escola_serie";
		campos_obrig[01] = "cbt_escola_local";
		campos_obrig[02] = "cbt_escola_data";
	}else if(document.getElementById("form_trabalho").cbt_tipo_formacao[2].checked){
		campos_obrig[00] = "cbt_facul_curso";
		campos_obrig[01] = "cbt_facul_local";
		campos_obrig[02] = "cbt_facul_data";
	}
	else {
		alert("Selecione o tipo de formacao.")
		return false;
	}
	
	for (cont = 0; cont < campos_obrig.length; cont++) {
		if (document.getElementById(campos_obrig[cont]).value == "") {
			ret = false;
			break;
		}
	}
	
	if (ret == false) {
		alert("Todos os campos obrigatorios precisam ser preenchidos.")
		document.getElementById(campos_obrig[cont]).focus();
	}else{
		document.getElementById('form_trabalho').action = 'http://www.azimute.eng.br/sessao-trabalhe-conosco-02/continuar';
		document.getElementById('form_trabalho').submit();
	}

	return ret;
}