/* Índice de funções
 * formataCampo(e,src,mask) = máscara numérica de campos
 * verificaDDD(componente) = máscara de DDD, pula para o campo telefone após 2 digitos
 * mostraDiv(id) = mostra/oculta a tag com a id passada
 * remover_espacos(str) = equivalente ao trim(), remove espaços em branco
 * ajaxInit() = inicialização do ajax
 
 * ---------------- Gerência de galeria de imagens dinâmica ----------------
 * validaArquivos() = validação de sistema de inserção dinâmica de arquivos
 * adicionarArq(index) = adiciona nova linha com radio, input e botões de remover/adicionar, no índice passado
 * removerLinha(index, linha, tipo) = remove a linha deste botão
 * verificaPrincipal(hidden,principal,componente) = validação de campos "principal" dinâmicos
 
 * ---------------- Manipulação de galeria de imagens dinâmica ----------------
 * setLink(id,valor) = define links anterior/próximo de cada imagem do menu
 * setImagem(alvo,imagem) = troca a imagem da tag alvo para o valor passado
 * getAtual(obra) = retorna o valor da imagem atual. ("atual"+obra)
 * getProximo(idObra,id) = retorna a imagem seguinte à imagem do id. ("proximo"+idObra)
 * getAnterior(idObra,id) = retorna a imagem anterior à imagem do id. ("proximo"+idObra)
 * trocarDiv(atual,outro,obra) = muda menu [anteriorDiv/proximoDiv] => ("obra"+idObra+"_"+div)
 * atualizaLinks(indice) = Atualiza links ao trocar imagem pelo flash
 * mudaFotoDestaque(iframe,indice) = Troca a foto atual (caso tenha somente 1 galeria na página)
 * mudaFoto(iframe,idObra,indice) = Troca a foto atual (caso tenha várias galerias na página)
 * selecionaFoto(idObra,atual,arquivo) = Troca imagem ampliada ao selecionar uma imagem do menu
 
 * -------------------- Formulário de currículos ---------------------------
 * selecionaVaga() = setor > vaga
 * buscaEndereco(selecao)
 * check_date(DATA)
 * validaCurriculo()
 * validaCPF(cpf)
 */
// JavaScript Document
//<input name="cep" type="text" id="cep" onkeypress="return formataCampo(event,this,'#####-###');" size="10" maxlength="9" autocomplete="off">
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 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 verificaDDD(componente){
	if(componente.value.length == 2){
		document.cadastro.telefone.focus();
	}
}
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 ajaxInit() {
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
	  ajax=new XMLHttpRequest();
	} else {// code for IE6, IE5
	  ajax=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return ajax;
}
function validaArquivos(){
	Form = document.getElementById("galeria");
	
	var conteudo = remover_espacos(Form.arq0.value);
		
	// Verifica Imagem
	if (conteudo.length == 0){
		if ((Form.desc0 == null) || (Form.desc0.value == "")){
			alert("Insira um arquivo válido!");
			Form.arq0.focus();
			return false;
		}
	}
	j = 0;
	principal = false;
	aux = null;
	var numArqs = Number(Form.numArquivos.value);
	
	// Procura pelos campos existentes para poder verificar
	// i é o contador de inputs lidos
	// j é o verificador do id do input
	for (i = 0; i < numArqs; i++){
		while ((document.getElementById("arq"+j) == null) && (j < 100)){
			j++;
		}
		var principalA = document.getElementById("destaque_"+j);
		if (principalA.checked){
			principal = true;
			aux = j;
		}
		j++;
	}
	// Se principal == true, pelo menos um campo foi selecionado como principal
	if (principal == false){
		alert("Selecione pelo menos um arquivo como principal!");
		Form.principal_0.focus();
		return false;
	} else { // Verifica se o campo selecionado é valido
		if ((document.getElementById("arq"+aux).value.length == 0) && (document.getElementById("desc"+aux).value == "")){
			alert("Selecione um arquivo válido como principal!");
			Form.principal_0.focus();
			return false;
		}
	}
	
	Form.submit();
	return true;
}
function adicionarArq(index){
	var table = document.getElementById("tabArq");
	
	var col0 = document.createElement("TD");
	col0.align = 'center';
	var col1 = document.createElement("TD");
	var col2 = document.createElement("TD");
	col2.align = "right";
	var col3 = document.createElement("TD");
	col3.align = "right";	
	var col4 = document.createElement("TD");
	col4.align = "right";
	
	var radio = document.createElement("input");
	radio.setAttribute("onClick","verificaPrincipal('numArquivos','destaque',this)");
	radio.type = 'radio';
	radio.name = "destaque_"+index;
	radio.id = "destaque_"+index;
	radio.value = 'S';
	col0.appendChild(radio);
	
	var hidden = document.createElement("input");
	hidden.type = 'hidden';
	hidden.name = "desc"+index;
	hidden.id = "desc"+index;
	col1.appendChild(hidden);
	
	var input = document.createElement("input");
	input.type = 'file';
	input.name = "arq"+index;
	input.id = "arq"+index;
	col1.appendChild(input);
	
	var btDel = document.createElement("input");
	btDel.type = 'button';
	btDel.value = "Remover";
	btDel.setAttribute("onClick","removerLinha("+(index-1)+",this.parentNode.parentNode,'add');");
	col2.appendChild(btDel);
	
	var btAdd = document.createElement("input");
	btAdd.type = 'button';
	btAdd.id = "add"+index;
	btAdd.value = "Adicionar";
	btAdd.setAttribute("onClick","this.style.display='none';adicionarArq("+(index+1)+",this);");
	col3.appendChild(btAdd);
		
	var linha = table.insertRow(-1);
	linha.id = "tr"+index;
	
	linha.appendChild(col0);
	linha.appendChild(col1);
	linha.appendChild(col2);
	linha.appendChild(col3);
	linha.appendChild(col4);
	var hidden = document.getElementById("numArquivos");
	hidden.value = Number(hidden.value)+1;
}
function removerLinha(index, linha, tipo){
	// Antes de remover a linha, exibe o botão de adicionar anterior se este for o último da lista
	var i;
	for (i = index; i > 0; i--){
		if (document.getElementById(tipo+i) != null){
			break;
		}
	}
	var linhas = document.getElementById("tabArq").getElementsByTagName("TR");
	var numArq = document.getElementById("numArquivos");
	numArq.value = Number(numArq.value) - 1;
	if (linhas.item(linhas.length-2) == document.getElementById(tipo+i).parentNode.parentNode){
		document.getElementById(tipo+i).style.display = 'block';
	}
	linha.parentNode.removeChild(linha);	
}
function verificaPrincipal(hidden,principal,componente){
	var valor = document.getElementById(hidden).value;
	var j = 0;
	for (var i = 0; i < valor; i++){
		while ((document.getElementById(principal+"_"+j) == null) && (j < 100)){
			j++;
		}
		var radio = document.getElementById(principal+"_"+j);
		if (radio != componente){
			if (radio.checked){
				radio.checked = false;
			}
		}
		j++;
	}
}
// Os valores da próxima foto/video é guardada em um hidden com a identificação da mesma. O mesmo vale para a foto anterior
// Define o valor do hidden: setLink('hidden','valor');
function setLink(id,valor){
	document.getElementById(id).value = valor;
}
// define imagem para o componente alvo
function setImagem(alvo,imagem){
	document.getElementById(alvo).src = imagem;
}
// define imagem para o hidden alvo
function setArquivo(alvo,imagem){
	document.getElementById(alvo).arquivo = imagem;
}
// Retorna o índice da imagem atual
function getAtual(obra){
	return (document.getElementById("atual"+obra)) ? document.getElementById("atual"+obra).value : null;
}
// Se houver um hidden do próximo, retorna o valor, senão retorna nulo
function getProximo(idObra,id){
	return (document.getElementById("proximo"+idObra+"_"+id)) ? document.getElementById("proximo"+idObra+"_"+id).value : null;
}
// Se houver um hidden do anterior, retorna o valor, senão retorna nulo
function getAnterior(idObra,id){
	return (document.getElementById("anterior"+idObra+"_"+id)) ? document.getElementById("anterior"+idObra+"_"+id).value : null;
}
// Esconde a div atual e mostra o anterior/próximo
function trocarDiv(atual,outro,obra){
	divAnterior = document.getElementById(obra+"_"+(outro-1));
	divProximo =  document.getElementById(obra+"_"+(outro+1));

	// Oculta menu atual e mostra a outra (anterior/próxima)
	document.getElementById(obra+"_"+atual).style.display = "none";
	document.getElementById(obra+"_"+outro).style.display = "block";
	
	// extrai o id da div da obra se houver
	obra = obra.replace((/\D/g),"");
	// Se for a primeira div
	if (divAnterior == null){
		document.getElementById("anteriorDiv"+obra+"_"+atual).style.display = "none";
		document.getElementById("proximoDiv"+obra+"_"+outro).style.display = "block";
		if (obra != ""){
			document.getElementById("proximoDiv"+obra+"_"+outro).style.width = "100%";
		}
	} else {
		if (obra != ""){
			document.getElementById("proximoDiv"+obra+"_"+outro).style.width = "50%";
		}
	}
	// Se for a última div
	if (divProximo == null){
		document.getElementById("anteriorDiv"+obra+"_"+outro).style.display = "block";
		document.getElementById("proximoDiv"+obra+"_"+atual).style.display = "none";
	}
}
function atualizaLinks(indice,idObra){ // Atualiza links ao trocar imagem pelo flash

	if (document.getElementById("atual")){
		document.getElementById("atual").value = indice;
		linkAnt = document.getElementById("antPrincipal");
		linkProx = document.getElementById("proxPrincipal");
	} else {
		document.getElementById("atual"+idObra).value = indice;
		linkAnt = document.getElementById("antPrincipal"+idObra);
		linkProx = document.getElementById("proxPrincipal"+idObra);
	}
	
	if (indice > 0){//proximo
		
		proximo = getProximo(idObra,indice);
		if ((proximo == null) || (proximo == "")){		
			linkProx.style.display = 'none';
		}
		
		if (linkAnt.style.display == "none"){
			linkAnt.style.display = "block";
		}
		
	} else { //anterior	
		anterior = getAnterior(idObra,indice);
		
		if (anterior == ""){
			return;
		}
		if (anterior == 0){
			linkAnt.style.display = "none";
		}
		
		if (linkProx.style.display == "none"){
			linkProx.style.display = 'block';
		}
	}
}
// Muda a foto atual e esconde/mostra os links de anterior/próximo se necessário
function mudaFotoDestaque(iframe,indice){
	linkAnt = document.getElementById("antPrincipal");
	linkProx = document.getElementById("proxPrincipal");
	var atual = getAtual('');
	if (indice > 0){//proximo		
		proximo = getProximo('',atual);
		if ((proximo == null) || (proximo == "")){
			return;
		}
		// Busca atributo "arquivo" e passa para a variável
		foto = document.getElementById("proximo_"+atual).arquivo+"&id="+proximo;
		
		// Caso o próximo seja o último, oculta o botão
		if ((proximo == null) || (proximo == "")){		
			linkProx.style.display = 'none';
		}
		// Caso o atual era o primeiro, mostra o botão
		if (linkAnt.style.display == "none"){
			linkAnt.style.display = "block";
		}
	} else { //anterior	
		anterior = getAnterior('',atual);
		if (anterior == ""){
			return;
		}
		// Busca atributo "arquivo" e passa para a variável
		foto = document.getElementById("anterior_"+atual).getAttribute('arquivo')+"&id="+anterior;
		// Caso o anterior seja o primeiro, oculta o botão
		if (anterior == 0){
			linkAnt.style.display = "none";
		}
		// Caso o atual seja o último, mostra o botão
		if (linkProx.style.display == "none"){
			linkProx.style.display = 'block';
		}
	}
	// atribui nova foto ao iframe
	document.getElementById('Ampliado').src="fotoAmpliada.php?src="+foto;
}
// Muda a foto atual e esconde/mostra os links de anterior/próximo se necessário
function mudaFoto(iframe,idObra,indice){
	linkAnt = document.getElementById("antPrincipal"+idObra);
	linkProx = document.getElementById("proxPrincipal"+idObra);
	
	atual = getAtual(idObra);
	if (indice > 0){//proximo
		proximo = getProximo(idObra,atual);
		seguinte = getProximo(idObra,proximo);
		if ((seguinte == "") || (seguinte == null)){
			linkProx.style.display = "none";
			linkAnt.style.width = "100%";
		}
		document.getElementById("atual"+idObra).value = proximo;
		
		foto = document.getElementById("proximo"+idObra+"_"+atual).arquivo;
		if (linkAnt.style.display = "none"){			
			linkProx.style.width = "50%";			
			linkAnt.style.display = "block";
		}
	} else { //anterior	
		anterior = getAnterior(idObra,atual);
		
		if (anterior == 0){
			linkAnt.style.display = "none";
			linkProx.style.width = "100%";
			
		} 
		
		document.getElementById("atual"+idObra).value = anterior;
		foto = document.getElementById("anterior"+idObra+"_"+atual).getAttribute("arquivo");
		
		if (linkProx.style.display = "none"){
			linkProx.style.display = "block";
			linkAnt.style.width = "50%";
		}
	}
	// atribui nova foto ao iframe
	setImagem(iframe,"images/obras/"+foto);
}
function selecionaFoto(idObra,atual,arquivo){
	if (idObra == ""){
		
	}
	document.getElementById("atual"+idObra).value = atual;
	anterior = document.getElementById("antPrincipal"+idObra);
	proximo = document.getElementById("proxPrincipal"+idObra);
	
	if (idObra == ""){ // foto da página principal
		if ((getProximo(idObra,atual) == null) || (getProximo(idObra,atual) == "")){
			proximo.innerHTML = "";
			anterior.style.cursor = "default";
		} else {			
			anterior.style.cursor = "pointer";
			proximo.innerHTML = "&raquo;";			
		}
		if ((getAnterior(idObra,atual) == null) || (getAnterior(idObra,atual) == "")){
			anterior.innerHTML = "";
			anterior.style.cursor = "default";
		} else {
			anterior.style.cursor = "pointer";
			anterior.innerHTML = "&laquo;";
		}
	} else { // foto da página de obras
		if ((getProximo(idObra,atual) == null) || (getProximo(idObra,atual) == "")){
			proximo.style.display = "none";
		}else {
			if ((getAnterior(idObra,atual) != null) && (getAnterior(idObra,atual) != "")){
				proximo.style.width = "50%";
			}
			proximo.style.display = "block";
		}
		if ((getAnterior(idObra,atual) == null) || (getAnterior(idObra,atual) == "")){
			anterior.style.display = "none";
		} else {
			anterior.style.display = "block";
		}
	}
	// atribui nova foto ao iframe
	setImagem("Ampliado"+idObra,"images/obras/"+arquivo);
}
//----------------- Formulário de curriculos

function selecionaVaga(selecao,resposta,url){
	var valIni = selecao.value;	
	var div = document.createElement("SELECT");
	div.id="vaga";
	div.name="vaga";
	var url = url+valIni;
	
	ajax = ajaxInit();
	ajax.open("GET",url,false);
	ajax.send(null);	
	
 	var aux = document.createElement("div");
	aux.appendChild(div);
	div.innerHTML = "&nbsp;<option value=''>-- Selecione --</option>";
	div.innerHTML += ajax.responseText;
	document.getElementById("linhaVaga").innerHTML = aux.innerHTML;
}
function buscaEndereco(selecao){
	if (selecao.value == ""){
		return false;
	}
	var itens = new Array();
	var url = "../scripts/ajax.php?busca=";
	// Cria novo select para substituir o antigo
	var div = document.createElement("SELECT");
	if (selecao.id == "estado"){
		div.id="cidade";
		div.name="cidade[]";
		url += "cidade";
		div.multiple="multiple";
		div.setAttribute("class","seletor");
	} else {
		div.id="bairro";
		div.name="bairro[]";
		url += "bairro";
		div.multiple="multiple";
		div.setAttribute("class","seletor");
	}
	
	var qtd = 0;
	// Gera os parâmetros (GET) a serem passados para o ajax
	for (i = 1; i < selecao.options.length; i++){
		if (selecao.options[i].selected){
			url += "&item"+qtd+"="+selecao.options[i].value;
			qtd++;
		}
	}
	
	ajax = ajaxInit();
	ajax.open("GET",url,false);
	ajax.send(null);	
	
 	var aux = document.createElement("div");
	aux.appendChild(div);
	div.innerHTML = "&nbsp;<option value=''>-- Selecione --</option>";
	div.innerHTML += ajax.responseText;
	if (selecao.id == "estado"){
		document.getElementById("linhaCidade").innerHTML = aux.innerHTML;
	} else {
		document.getElementById("linhaBairro").innerHTML = aux.innerHTML;
	}
	// Cria evento para o objeto criado
	if (selecao.id == "estado"){
		document.getElementById(div.id).onchange = function(){
			buscaEndereco(this);
		}
	}
}
function check_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.getDate();
	var vmes = vdt.getMonth()+1;
	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==09 && 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
					if (ano > vano) {
						//alert("Data incorreta!! Ano informado maior que ano atual.");
						DATA.focus();
						return false;
					}else{ //4
						//alert ("Data correta!");
						return true;
					} //4-else
				} //3-else
			}//2-else
		}//1-else                       
	} else { //5
		//alert(msgErro);
		DATA.focus();
		return false;
	} //5-else
}
function validaCurriculo(){
	Form = document.getElementById("curriculo");
	
	var campos = new Array();
	var msg = new Array();
	var i = 0;
	var erro = false;
	
	var conteudo =  remover_espacos(Form.nome.value);

	if (conteudo.length == 0){
		campos[i] = "nome";
		msg[i] = "Nome\r\n";
		erro = true;
		i++;
	}
	
	if (Form.sexo.value == ""){
		campos[i] = "sexo";
		msg[i] = "Sexo\r\n";
		erro = true;
		i++;
	}
	
	conteudo = remover_espacos(Form.email.value);
	
	if (conteudo.length == 0){
		campos[i] = "email";
		msg[i] = "Email\r\n";
		erro = true;
		i++;
	} 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) {
			campos[i] = "email";
			msg[i] = "Email (Formato inválido)\r\n";
			erro = true;
			i++;
		}
	
		for (i = 0; i < invalidCharsList.length; i++) {
			errorChar = invalidCharsList.charAt(i);
			if (conteudo.indexOf(errorChar,0) != -1) {
				campos[i] = "email";
				msg[i] = "Email (Caractere(s) inválido(s))\r\n";
				erro = true;
				i++;
			}
		}
	}
	Form.email.value = conteudo;
	
	conteudo = remover_espacos(Form.cpf.value);
	if (conteudo.length == 0){
		campos[i] = "cpf";
		msg[i] = "CPF\r\n";
		erro = true;
		i++;
	} else {
		if (validaCPF(conteudo) == false){
			campos[i] = "cpf";
			msg[i] = "CPF inválido\r\n";
			erro = true;
			i++;
		}
	}
	
	if (Form.estadoCivil.value == ""){
		campos[i] = "estadoCivil";
		msg[i] = "Estado Civil\r\n";
		erro = true;
		i++;
	}
	
	if (Form.dataNasc.value.length < 10){
		campos[i] = "dataNasc";
		msg[i] = "Data de Nascimento\r\n";
		erro = true;
		i++;
	} else {
		if (check_date(Form.dataNasc) == false){
			campos[i] = "dataNasc";
			msg[i] = "Data de nascimento inválida\r\n";
			erro = true;
			i++;
		}
	}
	
	var conteudo =  remover_espacos(Form.endereco.value);

	if (conteudo.length == 0){
		campos[i] = "endereco";
		msg[i] = "Endereço\r\n";
		erro = true;
		i++;
	}
	
	var conteudo =  remover_espacos(Form.bairro.value);

	if (conteudo.length == 0){
		campos[i] = "bairro";
		msg[i] = "Bairro\r\n";
		erro = true;
		i++;
	}
	
	var conteudo =  remover_espacos(Form.cidade.value);

	if (conteudo.length == 0){
		campos[i] = "cidade";
		msg[i] = "Cidade\r\n";
		erro = true;
		i++;
	}
	
	if (Form.estado.value == ""){
		campos[i] = "estado";
		msg[i] = "Estado\r\n";
		erro = true;
		i++;
	}
	
	var conteudo =  remover_espacos(Form.pais.value);

	if (conteudo.length == 0){
		campos[i] = "pais";
		msg[i] = "País\r\n";
		erro = true;
		i++;
	}
	
	if (Form.setor.value == ""){
		campos[i] = "setor";
		msg[i] = "Setor\r\n";
		erro = true;
		i++;
	}
	
	if (Form.vaga.value == ""){
		campos[i] = "vaga";
		msg[i] = "Vagas\r\n";
		erro = true;
		i++;
	}
	
	if (document.getElementById("statusES1").checked){
		conteudo = remove_espacos(Form.anoES.value);
		if (conteudo.length == 0){
			campos[i] = "anoES";
			msg[i] = "Ano de conclusão\r\n";
			i++;
			erro = true;
		}
	} else if (document.getElementById("statusES2").checked){
		if (Form.semestreES.value == ""){
			campos[i] = "semestreES";
			msg[i] = "Semestre do curso\r\n";
			i++;
			erro = true;
		}
	}
	if (document.getElementById("statusPG").checked){
		conteudo = remove_espacos(Form.anoES.value);
		if (conteudo.length == 0){
			campos[i] = "anoPG";
			msg[i] = "Ano de conclusão\r\n";
			i++;
			erro = true;
		}
		if ((!document.getElementById("tipoPG1").checked) && 
			(!document.getElementById("tipoPG2").checked) && 
			(!document.getElementById("tipoPG3").checked)){
			campos[i] = "tipoPG";
			msg[i] = "Categoria do curso\r\n";
			i++;
			erro = true;
		}
	} 
	
	conteudo = remover_espacos(Form.idioma1.value);
	if ((conteudo.length > 0) && (Form.nivel1.value == "")){
		campos[i] = "nivel1";
		msg[i] = "Nível do Idioma 1\r\n";
		i++;
		erro = true;
	}
	conteudo = remover_espacos(Form.idioma2.value);
	if ((conteudo.length > 0) && (Form.nivel2.value == "")){
		campos[i] = "nivel2";
		msg[i] = "Nível do Idioma 2\r\n";
		i++;
		erro = true;
	}
	conteudo = remover_espacos(Form.idioma3.value);
	if ((conteudo.length > 0) && (Form.nivel3.value == "")){
		campos[i] = "nivel3";
		msg[i] = "Nível do Idioma 3\r\n";
		i++;
		erro = true;
	}
	
	if (erro == true){		
		document.getElementById(campos[0]).focus();
		alerta = "Os seguintes campos devem ser preenchidos corretamente:\r\n";
		for (x = 0; x < i; x++){
			alerta += msg[x];
		}
		alert(alerta);
		return false;
	}
	
	if (Form.salario.value.length != 0){
		Form.salario.value.replace(".","");
		Form.salario.value.replace(",",".");
	}
	
	return true;
}
function validaCPF(cpf){
	var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
	if(!filtro.test(cpf)){
		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"){
	  	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))){
		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))){
	 	return false;
	}
	return true;
}
 
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 verificaNewsletter(Form) {
	
	if (Form.nome.value == "Nome" || Form.nome.value == "") {
		alert("O preenchimento do nome é obrigatório!");
		Form.nome.focus();
		return false;
	}
	if (Form.email.value == "Email" || Form.email.value == "") {
		alert("O preenchimento do email é obrigatório!");
		Form.email.focus();
		return false;
	}
	return true;
}

function verificaLogin(Form) {
	
	if (Form.login.value == "Login" || Form.login.value == "") {
		alert("O preenchimento do login é obrigatório!");
		Form.login.focus();
		return false;
	}
	if (Form.senha.value == "Senha" || Form.senha.value == "") {
		alert("O preenchimento da senha é obrigatório!");
		Form.senha.focus();
		return false;
	}
	return true;
}

function showMenu(div) {
	document.getElementById(div).style.display = "block";	
	//document.getElementById(div2).style.display = "none";	
}
function showMenuOver(div, div1) {
	document.getElementById(div).style.display = "block";
	document.getElementById(div1).style.display = "block";
	//document.getElementById(div2).style.display = "none";	
}
function hideMenu(div) {
	document.getElementById(div).style.display = "none";
}
function abrirHTML(caminho,altura,largura){
	Shadowbox.open({
		content:    caminho,
		player:     "iframe",
		height: altura,
		width: largura,
		onClose: function() {
			window.location.reload();
		}
	});
}
