//visualizar curriculo do filiado
function ver(codigo){	
	var ajaxRequest; 
	var url;
	
	url = "../funcoes/senge_ajax.asp?cod=verCurriculo&codigo="+ codigo 

		try{
			
			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){
				var texto = ajaxRequest.responseText;										

				if (texto == 'ok'){ //redirecionar					
					window.location.href = '../curriculo/ver_resultado.asp?cod='+codigo;
				}
				else {
					alert('Currículo aguardando liberação do Senge.')
				}
			}
		}	

		ajaxRequest.open("GET",url, true);	
		ajaxRequest.send(null);			

}

//controle dos butoes + ou - e cores da linha azul x vermelho
function mudaImg(codigo){
	if(document.getElementById('Img'+codigo).alt == "foto1") {				
		document.getElementById('Img'+codigo).src = "../imagens/dif.png";
		document.getElementById('Img'+codigo).alt = "foto2";		
		document.getElementById('Linha'+codigo).style.color = '#F00';			
	}
	else {		
		document.getElementById('Img'+codigo).src="../imagens/soma.png";
		document.getElementById('Img'+codigo).alt = "foto1";				
		document.getElementById('Linha'+codigo).style.color = '#006';
	}		
}

//Excluir o curriculo da tabela.
function curriculoExcluir(){	

	var url, confirma;	

	confirma = window.confirm('Você tem certeza que deseja excluir o currículo?') 

	if (confirma) {

		url = "../funcoes/senge_ajax.asp?cod=excluirCurriculo"

		try{

			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){

				var texto = ajaxRequest.responseText;											

				if (texto == 'ok'){

					alert('Currículo excluído com sucesso!')

					window.location.href = '../menu.asp';

				}

				else {

					alert('Erro na exclusão.')

				}

			}

		}	

		ajaxRequest.open("GET",url, true);	

		ajaxRequest.send(null);			

	}

	else {		

		return false;

	} 

}



//Altera o currículo do filiado.

function curriculoAlterar(){

	if(validarFormCurriculo()){

		document.formCurriculo.tipo.value = 'alterar'		

		document.formCurriculo.action = 'curriculo.asp'

		document.formCurriculo.submit();				

	}	

}



//Grava o currículo do filiado.

function curriculoPublicar(){

	if(validarFormCurriculo()){

		document.formCurriculo.tipo.value = 'publicar'		

		document.formCurriculo.action = 'curriculo.asp'

		document.formCurriculo.submit();		

	}

}



//Pesquisa no banco de currículos.

function curriculoBuscar(){

	if(validarFormBusca()){			

		document.formBusca.action = 'busca_resultado.asp'

		document.formBusca.submit();	



	}

}



function validarFormBusca(){

	

		var contador, msg, ordem;

		ordem = 0;

		contador = 0;

		msg = '';

		

		if (document.formBusca.todos.checked){

			return true;

		}

			

		//obrigar a preencher o horario.

		if (document.formBusca.checkHorario.checked){		

			if ((!document.formBusca.checkManha.checked) && (!document.formBusca.checkTarde.checked) && (!document.formBusca.checkNoite.checked) ) {		

				msg = msg +  ++ordem +'. Pelo menos um horário deverá ser marcado para a busca.\n';

			}	

		}

	

		//obrigar a preencher o mudar.

		if (document.formBusca.checkMudar.checked){	

		

			if ((!document.formBusca.mudar_0.checked) && (!document.formBusca.mudar_1.checked)){

				msg = msg +  ++ordem +'. O campo disponibilidade para mudar não foi selecionado.\n';

			}

		}

		

		//obrigar a preencher o idioma.

		if (document.formBusca.checkArea.checked){							

			

			for (var i=1 ; i<=20 ; i++){			

				if (document.formBusca["area_"+i].checked){

					contador++;				

				}			

			}

	

			if (contador == 0){

				msg = msg +  ++ordem +'. Nenhuma área de atuação foi selecionada.\n';

			}

		}	

		

		if ((!document.formBusca.checkHorario.checked) && (!document.formBusca.checkMudar.checked)  && (!document.formBusca.checkArea.checked) ){

			msg = msg +  ++ordem +'. Nenhum tipo de filtro foi selecionado para a busca..\n';

		}

		

		

		if (msg != ''){

			if (ordem <= 1)

				msg = 'Foi encontrado um erro na busca:\n\n'+ msg 

			else

				msg = 'Erros foram encontrados na busca:\n\n'+ msg 

			alert(msg);

			return false;

		}

		else {

			return true;

		}

}



//Método que valida formulário do currículo, no publicar e no alterar.

function validarFormCurriculo(){	

	var contador, msg, ordem;

	ordem = 0;

	contador = 0;

	msg = '';

	

	//Obrigar que pelo menos um campo de visibilidade seja marcado.

	if (document.formCurriculo.checkNome.checked) {

		contador++;

	}

	if (document.formCurriculo.checkEnd.checked) {

		contador++;

	}

	if (document.formCurriculo.checkTel.checked) {

		contador++;

	}

	if (document.formCurriculo.checkEmail.checked) {

		contador++;

	}

	if (contador == 0){

		msg = msg +  ++ordem +'. Pelo menos um campo de visibilidade deverá ser selecionado.\n';

	}

	

	contador = 0;	

	//Pelo menos uma área de atuação deverá ser marcada

	for(var i = 1 ; i <= 20; i++){			

		if (document.formCurriculo["area_"+i].checked){

			contador++;

		}

	}

	if (contador == 0){

		msg = msg + ++ordem +'. Pelo menos uma área de atuação deverá ser selecionada.\n';

	}

	



	contador = 0;	

	//Pelo menos um horário deverá ser marcado.	

	if (document.formCurriculo.checkManha.checked) {

		contador++;

	}

	if (document.formCurriculo.checkTarde.checked) {

		contador++;

	}

	if (document.formCurriculo.checkNoite.checked) {

		contador++;

	}

	if (contador == 0){

		msg = msg + ++ordem +'. Pelo menos um horário deverá ser selecionada.\n';

	}





	contador = 0;	

	//A disponibildade para mudar é obrigatório

	if ((document.formCurriculo.mudar_0.checked) || (document.formCurriculo.mudar_1.checked)){

		contador++;

	}

	if (contador == 0){

		msg = msg + ++ordem +'. O campo disponibilidade para mudar não foi selecionado.\n';

	}

		

	

	if (msg != ''){

		if (ordem <= 1)

			msg = 'Foi encontrado um erro formulário:\n\n'+ msg 

		else

			msg = 'Erros foram encontrados no formulário:\n\n'+ msg 

		alert(msg);

		return false;

	}

	else {

		return true;

	}

}



//Modidica o endereco do cadastro do filiado.

function salvarEndereco(){

	var ajaxRequest; 

	var url, endereco, bairro, cidade, uf, email, telefone_1, telefone_2, cep, msg;



	msg = '';

	document.getElementById("msg").innerHTML = '';

		

	endereco = document.formAlterarCadastro.endereco.value;

	bairro = document.formAlterarCadastro.bairro.value;

	cidade = document.formAlterarCadastro.cidade.value;

	uf = document.formAlterarCadastro.uf.value;

	email = document.formAlterarCadastro.email.value;

	telefone_1 = document.formAlterarCadastro.telefone_1.value;

	telefone_2 = document.formAlterarCadastro.telefone_2.value;

	cep = document.formAlterarCadastro.cep.value;

		

	if (endereco == '') {

		msg = msg + 'O campo endereço é obrigatório.\n'

	}	

	if (bairro == '') {

		msg = msg + 'O campo bairro é obrigatório.\n'

	}	

	if (cidade == '') {

		msg = msg + 'O campo cidade é obrigatório.\n'

	}		

	if (uf == '') {

		msg = msg + 'O campo uf é obrigatório.\n'

	}		

	if (email == '') {

		msg = msg + 'O campo email é obrigatório.\n'

	}		

	if (telefone_1 == '') {

		msg = msg + 'O campo telefone 1 é obrigatório.\n'

	}		

	if (cep == '') {

		msg = msg + 'O campo cep é obrigatório.\n'

	}		

	

	

	if (msg != ''){

		msg = 'Erro no formulário:\n'+ msg 

		alert(msg);

	}	

	else {

		url = "../funcoes/senge_ajax.asp?cod=cadastro&endereco="+endereco+"&bairro="+bairro

		url = url + "&cidade="+cidade+"&uf="+uf+"&telefone_1="+telefone_1+"&telefone_2="+telefone_2+"&cep="+cep+"&email="+email

		

		try{

			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){

				var texto = ajaxRequest.responseText;		

							

				if (texto == 'ok'){

					document.getElementById("msg").innerHTML = 'Cadastro atualizado com sucesso!';		

					controle('cancelar')

				}

				else{					

					document.getElementById("msg").innerHTML = 'Não foi possível alterar o cadastro, procure o Senge-CE.';		

					

				}

			}

		}	

		ajaxRequest.open("GET",url, true);	

		ajaxRequest.send(null);		

	}	

}



//Alterar senha de acesso do Senge Digital.

function alterarSenha(){

	var ajaxRequest; 

	var url, cpf, atual, nova, confirma;



	document.getElementById("msg").innerHTML = '';



	atual = document.formAlterarSenha.atual.value;

	nova =  document.formAlterarSenha.nova.value;

	confirma =  document.formAlterarSenha.confirma.value;



	if (atual == '') {

		document.getElementById("msg").innerHTML = 'A "senha atual" é um campo obrigatório.';

	}	

	else if (nova == '') {

		document.getElementById("msg").innerHTML = 'A "nova senha" é um campo obrigatório.';

	}	

	else if (confirma == '') {

		document.getElementById("msg").innerHTML = 'A "confirme nova senha" é um campo obrigatório.';

	}		

	else if (nova != confirma) {

		document.getElementById("msg").innerHTML = 'Confirmação de senha inválida.';

	}	

	else {

		url = "../funcoes/senge_ajax.asp?cod=alterarSenha&atual="+atual+"&nova="+nova+"&confirma="+confirma

		

		try{

			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){

				var texto = ajaxRequest.responseText;											

				document.getElementById("msg").innerHTML = texto;		

				document.formAlterarSenha.atual.value = '';

				document.formAlterarSenha.nova.value = '';

				document.formAlterarSenha.confirma.value = '';

			}

		}	

		ajaxRequest.open("GET",url, true);	

		ajaxRequest.send(null);		

	}

}



//Metodo para logar no Senge Digital.

function login(){

	var ajaxRequest; 

	var url, cpf;



	document.getElementById("msg").innerHTML = '';



	cpf = document.formLogin.cpf.value;	

	senha = document.formLogin.senha.value;	

	cpf = cpf.replace(".","");

	cpf = cpf.replace(".","");

	cpf = cpf.replace("-","");



	if (cpf == '' || !(validaCpfCnpj(cpf))) {

		document.getElementById("msg").innerHTML = 'CPF inválido.';

	}	

	else if (senha == '') {

		document.getElementById("msg").innerHTML = 'Senha não informada.';

	}	

	else {

		url = "funcoes/senge_ajax.asp?cod=login&cpf="+cpf+"&senha="+senha

		

		try{

			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){

				var texto = ajaxRequest.responseText;											

								

				if (texto == 'ok'){

					document.formLogin.action = 'menu.asp';

					document.formLogin.submit();					

				}

				else{

					document.getElementById("msg").innerHTML = texto;		

				}

			}

		}	

		ajaxRequest.open("GET",url, true);	

		ajaxRequest.send(null);		

	}

}



//Metodo para solcitar a senha via email.

function solicitaSenha(){

	var ajaxRequest; 

	var url, cpf;



	document.getElementById("msg").innerHTML = '';



	cpf = document.formSenha.cpf.value;	

	cpf = cpf.replace(".","");

	cpf = cpf.replace(".","");

	cpf = cpf.replace("-","");



	if (cpf == '' || !(validaCpfCnpj(cpf))) {

		document.getElementById("msg").innerHTML = 'CPF inválido.';

	}	

	else {

		url = "../funcoes/senge_ajax.asp?cod=solicita_senha&cpf="+cpf

		

		try{

			// Opera 8.0+, Firefox, Safari

			ajaxRequest = new XMLHttpRequest();

		} catch (e){

			// Internet Explorer Browsers

			try{

				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {

				try{

					ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

				} catch (e){

					// Something went wrong

					alert("Seu navegador não está funcionando corretamente!");

					return false;

				}

			}

		}

		// Create a function that will receive data sent from the server

		ajaxRequest.onreadystatechange = function(){

			if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){

				var texto = ajaxRequest.responseText;							

				document.getElementById("msg").innerHTML = texto;		

			}

		}	

		ajaxRequest.open("GET",url, true);	

		ajaxRequest.send(null);		

	}

}



//Deixa digitar somente números.

function somenteNumero(e){

	var tecla=(window.event)?event.keyCode:e.which;

    if((tecla > 47 && tecla < 58) || tecla == "0" || tecla == "9") return true;

	    else{

    if (tecla != 8) return false;

    	else return true;

    }

}



//Mascara para preenchimento dos formulários

function aplicaMascara(Mascara, elemento){    

    // Seta o elemento

    var elemento = (elemento) ? elemento : document.getElementById(elemento); 

    if(!elemento) return false;

    

    // Método que busca um determinado caractere ou string dentro de uma Array

    function in_array( oque, onde ){

            for(var i = 0 ; i <onde.length; i++){

            if(oque == onde[i]){

                return true;

            }

        }

        return false;

    }

    // Informa o array com todos os caracteres que podem ser considerados caracteres de mascara

    var SpecialChars = [':', '-', '.', '(',')', '/', ',', '_'];

    var oValue = elemento.value;

    var novo_valor = '';

    for( i = 0 ; i <oValue.length; i++){

        //Recebe o caractere de mascara atual

        var nowMask = Mascara.charAt(i);

        //Recebe o caractere do campo atual

        var nowLetter = oValue.charAt(i);

        //Aplica a masca

        if(in_array(nowMask, SpecialChars) == true && nowLetter != nowMask){

            novo_valor +=  nowMask + '' + nowLetter;

        } else {

            novo_valor += nowLetter;

        }

        // Remove regras duplicadas

        var DuplicatedMasks = nowMask+''+nowMask;

        while (novo_valor.indexOf(DuplicatedMasks)>= 0) {

         novo_valor = novo_valor.replace(DuplicatedMasks, nowMask);

        }

    }

    // Retorna o valor do elemento com seu novo valor

    elemento.value = novo_valor;

}



//Verifica a validade de um CPF/CNPJ.

function validaCpfCnpj(cpf) {

	//Verifica tamanho e testa CNPJ e CPF 

	if (cpf.length > 11 ) {

		var cnpj;

		cnpj = cpf;

		var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;

		digitos_iguais = 1;

		if (cnpj.length < 14 && cnpj.length < 15){

			return false;

		}

		for (i = 0; i < cnpj.length - 1; i++){

			if (cnpj.charAt(i) != cnpj.charAt(i + 1)){

				digitos_iguais = 0;

				break;

			}

		}

		if (!digitos_iguais){

			tamanho = cnpj.length - 2

			numeros = cnpj.substring(0,tamanho);

			digitos = cnpj.substring(tamanho);

			soma = 0;

			pos = tamanho - 7;

			for (i = tamanho; i >= 1; i--){

				soma += numeros.charAt(tamanho - i) * pos--;

				if (pos < 2)

					pos = 9;

			}

			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

			if (resultado != digitos.charAt(0)){

				return false;

			}

			tamanho = tamanho + 1;

			numeros = cnpj.substring(0,tamanho);

			soma = 0;

			pos = tamanho - 7;

			for (i = tamanho; i >= 1; i--){

				soma += numeros.charAt(tamanho - i) * pos--;

				if (pos < 2)

					pos = 9;

			}

			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;

			if (resultado != digitos.charAt(1)){

				return false;

			}

			return true;

		}

		else {

			return false;		

		}

	} 

	else {	

		var s = cpf;   

		var i;	

		var c = s.substr(0,9);   

		var dv = s.substr(9,2);  

		var d1 = 0;   

		

		for (i = 0; i < 9; i++) { 

			d1 += c.charAt(i)*(10-i); 

		} 

	  

		if (d1 == 0){   

			return false;   

		} 

	  

		d1 = 11 - (d1 % 11); 

		  

		if (d1 > 9)

			d1 = 0; 	  

		if (dv.charAt(0) != d1) { 

			return false;   

		} 

		

		d1 *= 2;   

		for (i = 0; i < 9; i++) { 

			d1 += c.charAt(i)*(11-i); 

		}   

		

		d1 = 11 - (d1 % 11);   

		if (d1 > 9)

			d1 = 0;   

		if (dv.charAt(1) != d1) { 

			return false;   

		}   

		return true;   

	}

} 



//Retorna as cidades de um estado selecionado.

function getCidade(estado){	

	var ajaxRequest;  

	url = "../funcoes/senge_ajax.asp?cod=cidade&estado="+estado

	

	try{

		// Opera 8.0+, Firefox, Safari

		ajaxRequest = new XMLHttpRequest();

	} catch (e){

		// Internet Explorer Browsers

		try{

			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

		} catch (e) {

			try{

				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

			} catch (e){

				// Something went wrong

				alert("Seu navegador não está funcionando corretamente!");

				return false;

			}

		}

	}

	// Create a function that will receive data sent from the server

	ajaxRequest.onreadystatechange = function(){

		if(ajaxRequest.readyState == 4 || ajaxRequest.readyState=="complete"){			

			var texto = ajaxRequest.responseText;			

			document.getElementById("spanCidade").innerHTML = texto;

		}

	}	

	ajaxRequest.open("GET",url, true);	

	ajaxRequest.send(null);

}
