// JavaScript Document
//<input name="cep" type="text" id="cep" onkeypress="return formataCampo(event,this,'####-###');" size="10" maxlength="9">

function mostraCat(cat,id){
	var fundo = "";
	if (id%2 > 0){
		fundo = "2";
	}
	if (document.getElementById("status"+cat).value == 'fechado'){
		document.getElementById("seta"+cat).src = "images/setaFecha.gif";
		document.getElementById("status"+cat).value = 'aberto';
	} else {
		document.getElementById("seta"+cat).src = "images/setaAbre.gif";
		document.getElementById("status"+cat).value = 'fechado';
	}

	
}

function remove(str, sub) {
	i = str.indexOf(sub);
   	r = "";
   	if (i == -1) return str;
   	r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   	return r;
}


function formataCampo(e,src,mask) {
	var _TXT = (e.which) ? e.which : e.keyCode;
	
    if(_TXT > 47 && _TXT < 58) {
	var i = src.value.length; var saida = mask.substring(0,1); var texto = mask.substring(i)
	if (texto.substring(0,1) != saida) { src.value += texto.substring(0,1); }
		return true;
	} else {
		// 8 = backspace, 9 = Tab, 37 = seta esquerda, 39 = seta direita, 46 = delete
		if ((_TXT != 8) && (_TXT != 9) && (_TXT != 0) && (_TXT != 37) && (_TXT != 39) && (_TXT != 46)) { return false; }
		else { return true; }
    }
}
function formataLetrasCampo(e,src,mask) {
	var _TXT = (e.which) ? e.which : e.keyCode;
    if (_TXT > 64 && _TXT < 91) {
		var i = src.value.length;
		var saida = mask.substring(0,1);
		var texto = mask.substring(i)
		if (texto.substring(0,1) != saida) { 
			src.value += texto.substring(0,1);
		}
		return true;
	} else {
		// 8 = backspace, 9 = Tab, 37 = seta esquerda, 39 = seta direita, 46 = delete
		if ((_TXT != 8) && (_TXT != 9) && (_TXT != 0) && ((_TXT < 37) || (_TXT > 40)) && (_TXT != 46)) {
			return false;
		} else { 
			return true;
		}
    }
}

function verificaDatas(dataInicio,dataFim,separador){
	// verifica se os campos estão vazios
	conteudo = dataInicio.replace(separador,"");
	if (conteudo.length == 0){
		return "Insira uma data de início!";
	}
	
	conteudo2 = dataFim.replace(separador,"");
	if (conteudo2.length == 0){
		return "Insira uma data de término!";
	}
	// converte as strings em datas
	aux = dataInicio.split(separador);
	inicio = new Date(aux[2],aux[1],aux[0]);
	
	aux2 =dataFim.split(separador);
	fim = new Date(aux2[2],aux2[1],aux2[0]);
	
	// compara as datas
	if (inicio > fim){
		return("A data de término deve ser após a data de início!");
	} else if (fim < new Date()){
		return("Data de término inválida!");
	}
	
	return null;
}

function verificaDDD(componente){
	if(componente.value.length == 2){
		document.contato.telefone.focus();
	}
}
//<input name="valor" type="text" onKeyPress="return(formataMoeda(this,12,'.',',',event))"/>
function formataMoeda(objTextBox, limite, SeparadorMilesimo, SeparadorDecimal, e){
	if (objTextBox.value.length > limite){
		objTextBox.value = objTextBox.value.substr(1,limite);
	}
	//máscara de moeda 0.000.000,00
	SeparadorMilesimo='.';
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which: e.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc    
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
    	return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave 
 
    if (strCheck.indexOf(key) == -1) 
    	return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) 
        	break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) 
        	aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) 
    	objTextBox.value = '';
    if (len == 1) 
    	objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) 
    	objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        	objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function mostraDiv(id){
	if (document.getElementById(id).style.display == 'none'){
		document.getElementById(id).style.display = 'block';
	} else {		
		document.getElementById(id).style.display = 'none';
	}
	return true;
}

function remover_espacos(str){
	r = "";
	for(i = 0; i < str.length; i++){
		if(str.charAt(i) != ' '){
			r += str.charAt(i);
		}
	}
	return r;
}

function verificaChar(str, array){
	for (var i = 0; i < str.length; i++){
		if (array.indexOf(str.charAt(i)) == -1){
			return false;
		}
	}
	return true;
}

function validaContato(){
	Form = document.contato;
	
	var conteudo = remover_espacos(Form.nome2.value);
	
	if (conteudo.length == 0){
		alert("O preenchimento do nome é obrigatório!");
		Form.nome2.focus();
		return false;
	}
	
	conteudo = remover_espacos(Form.email2.value);
	
	if (conteudo.length == 0){
		alert("Insira um email!");
		Form.email2.focus();
		return false;
	} else {
		invalidCharsList = " #$!*()[]^<>{}\'\"";
		// define a list of invalid characters
		if (conteudo.indexOf('@',0)==-1 ||
			conteudo.indexOf('@',0)== 0 ||
			conteudo.indexOf('.',3)==-1 ||
			conteudo.lastIndexOf('.') > conteudo.length-3) {
			alert("Formato de email inválido!");
			Form.email2.focus();
			return false;
		}
	
		for (i = 0; i < invalidCharsList.length; i++) {
			errorChar = invalidCharsList.charAt(i);
			if (conteudo.indexOf(errorChar,0) != -1) {
				alert("Caractere inválido!");
				Form.email2.focus();
				return false;
			}
		}
	}
	Form.email2.value = conteudo;
	
	Form.submit();
	return true;
}
function validaCNPJ(CNPJ) {
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
		   x = CNPJ.substring(0,2);
		   x += CNPJ. substring (3,6);
		   x += CNPJ. substring (7,10);
		   x += CNPJ. substring (11,15);
		   x += CNPJ. substring (16,18);
		   CNPJ = x;
	} else {
		   CNPJ = CNPJ. replace (".","");
		   CNPJ = CNPJ. replace (".","");
		   CNPJ = CNPJ. replace ("-","");
		   CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
	   a[i] = CNPJ.charAt(i);
	   b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="Dígito verificador com problema!";
	}
	if (erro.length > 0){
	   alert(erro);
	   return false;
	} else {
	  // alert("CNPJ valido!");
	}
	return true;
}

function addFunc(index){
	var table = document.getElementById("conteudo");
	
	var linha = table.insertRow(-1);
	linha.id = "tr0_"+index;
	td = document.createElement("TD");
	td.setAttribute("colspan","2");
	td.vAlign = "middle";
	td.align = "center";
	td.height = "20";
	td.innerHTML = '<hr width="95%" />';
	linha.appendChild(td);
	
	var linha2 = table.insertRow(-1);
	linha2.id = "tr1_"+index;
	td1 = document.createElement("TD");
	td1.innerHTML = '<strong>Nome:</strong>';
	td2 = document.createElement("TD");
	td2.innerHTML = '<input type="text" name="nome'+index+'" />';
	linha2.appendChild(td1);
	linha2.appendChild(td2);
	
	var linha3 = table.insertRow(-1);
	linha3.id = "tr2_"+index;
	td3 = document.createElement("TD");
	td3.innerHTML = '<strong>Setor:</strong>';
	td4 = document.createElement("TD");
	td4.innerHTML = '<input type="text" name="setor'+index+'" />';
	linha3.appendChild(td3);
	linha3.appendChild(td4);
	
	var linha4 = table.insertRow(-1);
	linha4.id = "tr3_"+index;
	td4 = document.createElement("TD");
	td4.innerHTML = '<strong>Função:</strong>';
	td5 = document.createElement("TD");
	td5.innerHTML = '<input type="text" name="funcao'+index+'" />';
	linha4.appendChild(td4);
	linha4.appendChild(td5);
	
	var linha5 = table.insertRow(-1);
	linha5.id = "tr4_"+index;
	td5 = document.createElement("TD");
	td5.innerHTML = '<strong>Indicação:</strong>';
	td6 = document.createElement("TD");
	td6.innerHTML = '<select name="indicado'+index+'"><option value="E">Eleito</option><option value="I">Indicado</option></select>';
	linha5.appendChild(td5);
	linha5.appendChild(td6);
	
	var linha6 = table.insertRow(-1);
	linha6.id = "tr5_"+index;
	td7 = document.createElement("TD");
	td7.setAttribute("colspan","2");
	td7.innerHTML = '<input type="button" value="Remover" onclick="removerLinha('+index+');" />&nbsp;';
	td7.innerHTML += '<input type="button" value="Adicionar Funcionário" id="btAdd'+index+'" onclick="this.style.display=\'none\';addFunc('+(index+1)+');" />';
	linha6.appendChild(td7);
	
	var hidden = document.getElementById("campos");
	hidden.value += index+";";
}
function removerLinha(index){
	// Antes de remover a linha, exibe o botão de adicionar anterior se este for o último da lista
	var table = document.getElementById("conteudo");
	var hidden = document.getElementById("campos");
	aux = hidden.value.split(";");
	for(var i = 0; i < aux.length-1; i++){
		if (aux[i] == index){
			if ((i+1 == aux.length-1) && (i > 0)){
				document.getElementById("btAdd"+aux[i-1]).style.display = "block";
			}
			
			for (j = 0; j < 6; j++){
				table.removeChild(document.getElementById("tr"+j+"_"+index));
			}			
			break;
		}
	}
	
	inicio = hidden.value.indexOf(index+";");
	aux2 = index+"";
	fim = inicio + aux2.length;	
	hidden.value = hidden.value.substr(0,inicio)+hidden.value.substr(fim+1);
}

function is_date(DATA) {
    var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	var msgErro = 'Formato inválido de data.';
	var vdt = new Date();
	var vdia = vdt.getDay();
	var vmes = vdt.getMonth();
	var vano = vdt.getFullYear();
	if ((DATA.value.match(expReg)) && (DATA.value!='')){
		var dia = DATA.value.substring(0,2);
		var mes = DATA.value.substring(3,5);
		var ano = DATA.value.substring(6,10);
		if((mes==04 && dia > 30) || (mes==06 && dia > 30) || (mes==9 && dia > 30) || (mes==11 && dia > 30)){
			alert("Dia incorreto !!! O mês especificado contém no máximo 30 dias.");
			DATA.focus();
			return false;
		} else{ //1
			if(ano%4!=0 && mes==2 && dia>28){
				alert("Data incorreta!! O mês especificado contém no máximo 28 dias.");
				DATA.focus();
				return false;
			} else{ //2
				if(ano%4==0 && mes==2 && dia>29){
					alert("Data incorreta!! O mês especificado contém no máximo 29 dias.");
					DATA.focus();
					return false;
				} else{ //3
					return true;
				} //3-else
			}//2-else
		}//1-else                       
	} else { //5
		alert(msgErro);
		DATA.focus();
		return false;
	} //5-else
}

function validaCPF(cpf){
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	if(!filtro.test(cpf)){
		window.alert("CPF inválido. Verifique se seu cpf foi digitado corretamente.");
		return false;
	}
	
	cpf = remove(cpf, ".");
	cpf = remove(cpf, "-");
	
	if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  	cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	 	cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  	cpf == "88888888888" || cpf == "99999999999"){
	  	window.alert("CPF inválido. Verifique se seu cpf foi digitado corretamente.");
	  	return false;
	}
	
	soma = 0;
	for(i = 0; i < 9; i++)
		soma += parseInt(cpf.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
		resto = 0;
	if(resto != parseInt(cpf.charAt(9))){
		window.alert("CPF inválido. Verifique se seu cpf foi digitado corretamente.");
		return false;
	}
	soma = 0;
	for(i = 0; i < 10; i ++)
	 	soma += parseInt(cpf.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if(resto == 10 || resto == 11)
	 	resto = 0;
	if(resto != parseInt(cpf.charAt(10))){
	 	window.alert("CPF inválido. Verifique se seu cpf foi digitado corretamente.");
	 	return false;
	}
	return true;
}
function validaCurriculo(Form){
	
	if ($("#nome").val() == ""){
		alert("Favor informar seu nome!");
		$("#nome").addClass("error");
		$("#nome").focus();
		return false;
	}
	$("#nome").removeClass("error");
	
	if ($("#nascimento").val() == ""){
		alert("Favor informar sua data de nascimento!");
		$("#nascimento").addClass("error");
		$("#nascimento").focus();
		return false;
	} else {
		if(!is_date(Form.nascimento)){
			$("#nascimento").addClass("error");
			$("#nascimento").focus();
			return false;
		}
	}
	$("#nascimento").removeClass("error");
	
	if ($("#rg").val() == ""){
		alert("Favor informar seu RG!");
		$("#rg").addClass("error");
		$("#rg").focus();
		return false;
	}
	$("#rg").removeClass("error");
	
	if ($("#orgao").val() == ""){
		alert("Favor informar o orgão emissor de seu RG!");
		$("#orgao").addClass("error");
		$("#orgao").focus();
		return false;
	} else {
		var rule = /[a-z]{2,3}(\-|\/)?[a-z]{2}/i;
		var orgao = $("#orgao").val();
		if (!orgao.match(rule)){
			alert("Orgão emissor inválido!");
			$("#orgao").addClass("error");
			$("#orgao").focus();
			return false;
		}
	}
	$("#orgao").removeClass("error");
	
	if ($("#cpf").val() == ""){
		alert("Favor informar seu cpf!");
		$("#cpf").addClass("error");
		$("#cpf").focus();
		return false;
	} else {
		if(!validaCPF($("#cpf").val())){
			$("#cpf").addClass("error");
			$("#cpf").focus();
			return false;
		}
	}
	$("#cpf").removeClass("error");
	
	if ($("#email").val() == ""){
		alert("Favor informar seu email!");
		$("#email").focus();
		return false;
	} else {
		conteudo = $("#email").val();
		invalidCharsList = " #$!*()[]^<>{}\'\"";
		// define a list of invalid characters
		if (conteudo.indexOf('@',0)==-1 ||
			conteudo.indexOf('@',0)== 0 ||
			conteudo.indexOf('.',3)==-1 ||
			conteudo.lastIndexOf('.') > conteudo.length-3) {
			alert("Formato de email inválido!");
			$("#email").focus();
			return false;
		}
	
		for (i = 0; i < invalidCharsList.length; i++) {
			errorChar = invalidCharsList.charAt(i);
			if (conteudo.indexOf(errorChar,0) != -1) {
				alert("Caractere inválido!");
				$("#email").focus();
				return false;
			}
		}
	}
	$("#email").removeClass("error");
	
	if ($("#endereco").val() == ""){
		alert("Favor informar seu endereço!");
		$("#endereco").addClass("error");
		$("#endereco").focus();
		return false;
	}
	$("#endereco").removeClass("error");
	
	if ($("#cidade").val() == ""){
		alert("Favor informar sua cidade!");
		$("#cidade").addClass("error");
		$("#cidade").focus();
		return false;
	}
	$("#cidade").removeClass("error");
	
	if ($("#escolaridade").val() == ""){
		alert("Favor informar sua escolaridade!");
		$("#escolaridade").addClass("error");
		$("#escolaridade").focus();
		return false;
	} else {
		if ($("#escolaridade").val() == "ESI" || $("#escolaridade").val() == "ESC"){
			if ($("#curso").val() == ""){
				alert("Favor informar seu curso!");
				$("#curso").addClass("error");
				$("#curso").focus();
				return false;
			}
			$("#curso").removeClass("error");
			if ($("#universidade").val() == ""){
				alert("Favor informar a instituição de seu curso!");
				$("#universidade").addClass("error");
				$("#universidade").focus();
				return false;
			}$("#universidade").removeClass("error");
		}
	}
	$("#escolaridade").removeClass("error");
	
	if ($("#vaga").val() == ""){
		alert("Favor informar a vaga que pretende se candidatar!");
		$("#vaga").addClass("error");
		$("#vaga").focus();
		return false;
	}
	$("#vaga").removeClass("error");
	
	return true;
}

function verificaCampo(componente,tamanho,proximo){
	if(componente.value.length == tamanho){
		$("#"+proximo).focus();
	}
}
function verificaGraduacao(campo){
	if (campo.value == "ESI" || campo.value == "ESC"){
		$("#ESrow").css("display","");
		$("#ESrow2").css("display","");
	} else {
		$("#ESrow").css("display","none");
		$("#ESrow2").css("display","none");
	}
}
