/**************************************************************
 *** Arquivo JavaScript principal da área do candidato      ***
 ***                                                        ***
 *** Contém funções de controle de apresentação             ***
 *** - Controla exibição/ocultação de itens                 ***
 *** - Controla apresentação de menus                       ***
 *** - Controla downloads de segmentos de páginas           ***
 ***                                                        ***
 **************************************************************/

var msgErrorDownload = "Erro ao fazer o download de uma página! \n\n Contate o suporte.";

// Função de carga inicial da HomePage do Candidato
function loadMain(){
	var query = "HomeCandidato.aspx";
	pageDownload(query, bodyMain);
}

// Função de carga inicial da página de cadastro de empresas parceiras
// - usada somente quando chamada através da área da empresa
// (verifica se recebeu algum parametro via query string e repassa-o)
function loadCadastroEmpresa(url){
	var query = "../Candidato/divCadastroEmpresaSimplificado.aspx";
	var pos = url.indexOf("?");
	if(pos != -1) query += url.substr(pos); 
	pageDownload(query, divWorkCadastroEmpresa);
}


//Paginação no Data Island XML
function backPage(){
	if(pageNumber.innerHTML!='1'){var n=0; n=pageNumber.innerText; n--; pageNumber.innerHTML=n;}
}
function nextPage(){
	if(pageNumber.innerHTML!=totalPages.innerHTML){var n=0; n=pageNumber.innerText; n++; pageNumber.innerHTML=n;}
}

//Navegação - Visuzalização de vagas
//------------------------------------------
function NavAnterior(atual,total){//Botão Anterior.
	if(atual>1)	{
		eval("tbVaga_" + atual + ".style.visibility='hidden'");
		eval("tbVaga_" + atual + ".style.display='none'");
		
		eval("tbVaga_" + (parseInt(atual)-1) + ".style.visibility='visible'");
		eval("tbVaga_" + (parseInt(atual)-1) + ".style.display=''");
	}
} 

function NavProximo(atual,total){//Botão Próximo
	if(atual<total)	{
		eval("tbVaga_" + atual + ".style.visibility='hidden'");
		eval("tbVaga_" + atual + ".style.display='none'");
		
		eval("tbVaga_" + (parseInt(atual) +1) + ".style.visibility='visible'");
		eval("tbVaga_" + (parseInt(atual) +1) + ".style.display=''");
	}
} 
// -------------------------------------------------

function toggleDetail(anchor, display, tableName){
	var tbls, tblDetail;
	tbls = anchor.parentElement.getElementsByTagName("table");
	tblDetail = null;
	for(i=0; i<tbls.length && tblDetail == null; i++) {
		if(tbls[i].name == tableName){
			tblDetail = tbls[i];
		}
	}
	if(tblDetail != null){
		if(display == null){
			display = (tblDetail.currentStyle.display == "none" ? "block" : "none");
		}
		tblDetail.style.display = display;
		
		if(display == "block"){
			if((tblDetail.offsetWidth + tblDetail.offsetLeft) > tblDetail.offsetParent.offsetWidth) {
				var newPos = tblDetail.offsetParent.offsetWidth - (tblDetail.offsetWidth + (tblDetail.parentElement.offsetWidth / 2) );
				tblDetail.style.left = newPos;
			}
		}
	}
}

function totalPaginas(xmlisland, tabela, labelTotal, labelAtual, navigationCell, tagName, divEmptyXMLMessage){
//Monta os links e exibe a tabela que estava oculta.
	var total, links, rows;
	rows = xmlisland.XMLDocument.selectNodes(tagName).length;

	if(rows == 0){
		tabela.parentElement.style.display = "none";
		if(divEmptyXMLMessage) divEmptyXMLMessage.style.display = "block";
	}
	else{
		if(divEmptyXMLMessage) divEmptyXMLMessage.style.display = "none";
		if(tabela.dataPageSize==0)
			tabela.dataPageSize = 10;
		total = Math.ceil(rows / tabela.dataPageSize);
		labelTotal.innerHTML = total;
		links = "";
		for(i=1; i<=total; i++){
			if(links != "") links += " |";
			links += "<a href=#divWorSpace onclick='javascript: goPage(";
			links += tabela.id;
			links += ", ";
			links += labelAtual.id;
			links += ", ";
			links += i;
			links += ");'>";
			links += i;
			links += "</a>";
		}
		navigationCell.innerHTML = links;
		tabela.parentElement.style.display = "block";
	}
}

function goPage(tabela, labelAtual, destino){//Números de página
	atual = new Number(labelAtual.innerText);
	if(atual<destino){
		for(i=atual; i<destino; i++) tabela.nextPage();
	} else {
		for(i=atual; i>destino; i--) tabela.previousPage();
	}
	labelAtual.innerHTML = destino;
}

function changeRowsPerPage(rows, tabela, xmldata, labelTotal, labelAtual, navigationCell){
	tabela.dataPageSize = rows; 
	totalPaginas(xmldata, tabela, labelTotal, labelAtual, navigationCell); 
	labelAtual.innerHTML = "1";
	tabela.firstPage(); 
}

function addArgument(buffer, checkbox) {
	var argumentos = "";
	if(checkbox.checked) {
		argumentos = "|" + checkbox.parentElement.lastChild.innerText;
		buffer.value += (buffer.value == "" ? argumentos.substr(1) : argumentos );
	} else {
		allchecks = document.getElementsByName(checkbox.name);
		for(i=0; i<allchecks.length; i++) {
			if(allchecks[i].checked){
				argumentos += ("|" + allchecks[i].parentElement.lastChild.innerText); 
			}
		}
		buffer.value = argumentos.substr(1);
	}
}

function setArgument(buffer, td) {
	var argumentos = "";
	argumentos = td.lastChild.innerText;
	buffer.value = argumentos;
}

//Função para voltar a tela de Seleção de Universiade
function VoltarSelecaoUniversidade(idVaga,IdCandidato,IdLocalTrabalhoVaga,idFase,idInstituicao,nomeInstituicao){
	var complemento = "";
	if(idInstituicao != null) complemento = "&IdInstituicao=" + idInstituicao + "&nomeInstituicao=" + nomeInstituicao;
	document.location.replace('../Empresa/divSelecionarInstituicaoContrato.aspx?idVaga=' + idVaga + '&IdCandidato=' + IdCandidato + '&IdLocalTrabalhoVaga=' + IdLocalTrabalhoVaga + '&idFase=' + idFase + complemento);
}

// Função que é chamada ao terminar o download de um segmento de página
// Recebe:
// - content = string com o conteúdo da página descarregada
// Obs.: Esta função faz o parsing do conteúdo, buscando somente os dados
//       retornados que estejam entre as tags <xml id="htmlData"> e </xml>.
//       O atributo "target" desta mesma tag é utilizado para identificar qual 
//       DIV irá ser preenchida com este conteúdo.
function finishedDownload(content){
	try {
		oIfr = document.createElement("iframe");
		oIfr.id = "parseResponse_" + (document.frames.length + 3);
		oIfr.style.display = "none";
		document.body.appendChild(oIfr);
		
		oDoc = document.frames(oIfr.id).document;
		oDoc.write(content);
		oDoc.close();

		//  verifica se o retorno foi redirecionado pelo ASP.Net
		// (Não autenticado ou Sessão expirada)
		var scriptToRun = verifyRedirection(oDoc);
		if(scriptToRun == null){
			oNode = oDoc.getElementById("htmlData");
			targetName = oNode.getAttribute("target");
			scriptToRun = oNode.getAttribute("onload");

			target = document.getElementById(targetName);
			var timerId = new Number(target.getAttribute("timeoutId"));
			window.clearTimeout(timerId);
			target.removeAttribute("timeoutId");
			target.innerHTML = oNode.innerHTML;
		}
		document.body.removeChild(oIfr);
		oNode = null;
		oDoc = null;
		oIfr = null;
		
		if(scriptToRun != null){
		    //alert(scriptToRun);
			eval(scriptToRun);
		}
	} catch(e) {
		//alert(msgErrorDownload); //ALERT comentado por causa do novo tratamento de erro.
	}
}

// Função que verifica se houve um redirecionamento pelo ASP.Net
// devido à expiração da sessão ou falta de autenticação
// Recebe:
// - oDoc = objeto que referencia o documento
// Retorna:
// - redirScript = string com o script de redirecionamento
function verifyRedirection(oDoc){
	var canBeRedirection = oDoc.body.getAttribute("canBeRedirection");
	var redirScript = null;
	if(canBeRedirection == "true")
		redirScript = "window.location = \"" + oDoc.body.getAttribute("redirectTo") + "\"";
	return(redirScript);
}

// Função que executa o download de um segmento de página
// Recebe:
// - url = string com o endereço web da página a ser descarregada
// - divTarget = object referenciando o DIV que receberá o conteúdo descarregado
// Obs.: Para que esta função executar corretamente é necessário que o DIV
//       passado no parâmetro "target" possua o behavior download 
//       (style="behavior:url(#default#download)"). Este feature só funciona 
//       no IE e o ideal é que seja associado ao DIV através do arquivo CSS.
function pageDownload(url, divTarget){
	if(divTarget.innerHTML == ""){
		// só inicia o download se o DIV target não possui conteúdo
		divTarget.innerHTML = "<div class='clsDivWaitMessage'>Carregando... Aguarde um instante...</div>";
		timerId = window.setTimeout("timedOutDownload(" + divTarget.id + ")", 900000, "JavaScript");
		divTarget.setAttribute("timeoutId", timerId);
		try
		{
		    divTarget.startDownload(url, finishedDownload);
		}
		catch(e)
		{
		    alert('erro');
		}
	}
}

// Função que é chamada se ocorrer um timeout no download de um segmento de página
// Recebe:
// - oDiv = referência do objeto DIV que receberia o conteúdo do segmento de página
function timedOutDownload(oDiv){
	//var timerId = new Number(oDiv.getAttribute("timeoutId"));
	//window.clearTimeout(timerId);
	//oDiv.removeAttribute("timeoutId");
	//oDiv.innerHTML = "";
	//alert(msgErrorDownload);
}

// Função que troca o DIV que está sendo apresentado dentro de um workspace
// Recebe:
// - divWorkspace = object referenciando o DIV que contém vários DIVs (workspace)
// - divToDisplay = object referenciando o DIV que deverá ficar visível no workspace
function toggleWorkspace(divWorkspace, divToDisplay){
    for(i=0; i<divWorkspace.childNodes.length; i++){
		node = divWorkspace.childNodes[i];
		if(node.nodeType == 1) {
			node.style.display = "none";
		}
    }
    divToDisplay.style.display = "block";
}

// Função que chama as funções pageDownload e toggleWorkspace de uma só vez
// Recebe:
// - url = string com o endereço web da página a ser descarregada
// - divTarget = object referenciando o DIV que receberá o conteúdo descarregado
// - divWorkspace = object referenciando o DIV que contém vários DIVs (workspace)
function loadAndDisplay(url, divTarget, divWorkspace){
	try
	{
	    pageDownload(url, divTarget);
	    toggleWorkspace(divWorkspace, divTarget);
	}
	catch(ex)
	{
	    alert("erro");
	}
	    
}

// Função que apresenta/oculta um DIV qualquer 
// Recebe:
// - div = object referenciando o DIV a apresentar/ocultar
function toggleDisplay(div){
    div.style.display = (div.style.display != "block" ? "block" : "none");
}

// Função que apresenta/oculta o DIV que contém texto de ajuda, 
// além disso, troca o texto do link de chamada dela mesma.
// Recebe:
// - aLink = object referenciando o A (anchor) que disparou esta função
// - divHelp = object referenciando o DIV que contém o texto de ajuda
function toggleHelp(aLink, divHelp){
    aLink.innerText = (aLink.innerText != "X" ? "X" : "?");
    toggleDisplay(divHelp);
}

// Função que formata com uma máscara o texto digitado em um INPUT TYPE="TEXT"
// Recebe:
// - src = objeto com a referência para o INPUT que está sendo formatado
// - mask = string contendo a máscara de formatação. Ex.: "00/00/0000"
// Obs.: deve ser utilizada no evento onkeypress do campo
function formatar(src, mask) {
    var i = src.value.length;
    var saida = mask.substring(i,i+1);
    var ascii = event.keyCode;
    if (saida == "A") {
        if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }
        else { event.keyCode = 0; }
    } else if (saida == "0") {
        if ((ascii >= 48) && (ascii <= 57)) { return }
        else { event.keyCode = 0 }
    } else if (saida == "#") {
        return;
    } else {
        src.value += saida;
        i += 1
        saida = mask.substring(i,i+1);
        if (saida == "A") {
            if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }
            else { event.keyCode = 0; }
        } else if (saida == "0") {
            if ((ascii >= 48) && (ascii <= 57)) { return }
            else { event.keyCode = 0 }
        } else { event.returnValue=false;return ; }
    }
}

function formatar1(src, mask) {
    var i = src.value.length;
    var saida = mask.substring(i,i+1);
    var ascii=event.keyCode;
    if (saida == "A") {
        if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }
        else { event.keyCode = 0; }
    } else if (saida == "0") {
        if ((ascii >= 48) && (ascii <= 57)) { return }
        else { event.keyCode = 0 }
    } else if (saida == "#") {
        return;
    } else {
        src.value += saida;
        i += 1
        saida = mask.substring(i,i+1);
        if (saida == "A") {
            if ((ascii >=97) && (ascii <= 122)) { event.keyCode -= 32; }
            else { event.keyCode = 0; }
        } else if (saida == "0") {
            if ((ascii >= 48) && (ascii <= 57)) { return }
            else { event.keyCode = 0 }
        } else { if ((ascii >= 48) && (ascii <= 57)) { return }else{ event.returnValue=false; }}
    }
}

//VALIDA CARACTERES ESPECIAS DO APELIDO
function ValidaCaracteresEspeciais()
{
	var VetCaracterInvalido = new Array(34,33,35,36,37,38,39,42,40,41,43,123,125,59,58,60,62,63,64,44,46,92,47,124,168,94,94,32,180);
	var I = 0;
	
	for(I = 0; I < VetCaracterInvalido.length; I++)
	{
		if(event.keyCode == VetCaracterInvalido[I])
			return false;
	}
	return true;
}

//VALIDA EMAIL
function validaEmail(emailString){
    var expressao = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	return expressao.test(emailString);		
}

//VALIDA CPF
function validaCpf(valor){
	valor=valor.replace(".","");
	valor=valor.replace(".","");
	valor=valor.replace("-","");
	if(valor.length != 11) return false;
    if(modulo(valor.substring(0,valor.length - 2)) + "" + modulo(valor.substring(0,valor.length - 1)) != valor.substring(valor.length - 2,valor.length)) return false;
	return true;
}

function modulo(str){
   	soma=0;
   	ind=2;
   	for(pos=str.length-1;pos>-1;pos=pos-1){
   		soma = soma + (parseInt(str.charAt(pos)) * ind);
   		ind++;
   		if(str.length>11){
   			if(ind>9) ind=2;
   		}
    }
   	resto = soma - (Math.floor(soma / 11) * 11);
   	if(resto < 2){
    	return 0
   	}else{
   		return 11 - resto
   	}
}

//VALIDA DATA
function validaData(data){
	if(data.length != 10) return false;
	pos0 = data.indexOf("/");
	if(pos0 == -1) return false;
	pos1 = data.indexOf("/", pos0 + 1);
	if(pos1 == -1) return false;
	if(data.indexOf("/", pos1 + 1) != -1) return false;
	dia = data.substring(0,pos0);
	dia = (dia.charAt(0) == "0")?dia.charAt(dia.length - 1):dia
	mes = data.substring(pos0 + 1, pos1);
	mes = (mes.charAt(0) == "0")?mes.charAt(mes.length - 1):mes
	ano = data.substring(pos1 + 1, data.length);
	ano = (ano.charAt(0) == "0")?ano.charAt(ano.length - 1):ano
	if(isNaN(dia) || isNaN(mes) || isNaN(ano)) return false;
	if(parseInt(ano) >= 0 && parseInt(ano) < 1900) return false;
	if(parseInt(ano) > 2100 || parseInt(ano) < 0 || parseInt(mes) > 12 || parseInt(mes) < 1) return false;
	numero = ((parseInt(ano) - 1884) / 4)
	if(numero == Math.floor(numero)){
		dias = "312931303130313130313031";
	}else{
		dias = "312831303130313130313031";
	}
	diamax = parseInt(dias.substring((mes-1)*2,((mes-1)*2)+2));
	if(parseInt(dia) < 1 || parseInt(dia) > diamax) return false;
	
	return true;
}

//VERIFICA SE POSSUI NUMERO
function hasNumber(str){
	var ref="0123456789"
	for(i=0;i<str.length;i++){
		if(ref.indexOf(str.charAt(i))!=-1) return true;
	}
	return false;
}

//VERIFICA SE POSSUI LETRA
function hasLetter(str){
	var ref="abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ"
	for(i=0;i<str.length;i++){
		if(ref.indexOf(str.charAt(i))!=-1) return true;
	}
	return false;
}

//VERIFICA SE O SIMBOLO EXISTE NA STRING
function hasSymbol(str, symbol){
	if(str.indexOf(symbol)!=-1){
		return true;
	}else{
		return false;
	}
}

//CONTADOR DE CARACTERES EM TEXTAREA
function contador(field,td,max){
	var td=document.getElementById(td);
	var comp=field.value.length;
	
	if(comp>max){
		field.value = field.value.substr(0, max);
	}else{
		td.innerHTML=(max-comp) + " caracteres dispon&#237;veis";
	}
}

//TRIM
function Trim(s){
  while((s.substring(0,1)==' ')||(s.substring(0,1)=='\n')||(s.substring(0,1)=='\r')){
    s=s.substring(1,s.length);
  }

  while((s.substring(s.length-1,s.length)==' ')||(s.substring(s.length-1,s.length)=='\n')||(s.substring(s.length-1,s.length)=='\r'))
  {
    s=s.substring(0,s.length-1);
  }

  return s;
}

//Validação de Máscara
function mask (InString, Mask) {
	        LenStr = 1
	        LenMsk = 1
	        ContPonto = 0
	        if ((LenStr==0) || (LenMsk==0))
	                return(false);
	        if (LenStr!=LenMsk)
	                return(false);
	        TempString=""
	        for (Count=0; Count<=InString.length; Count++) {
	                StrChar = InString.substring(Count, Count+1);
	                MskChar = Mask.substring(Count, Count+1);
	                
	                
	                if (MskChar=='#') {
	                        if(!isNumberChar(StrChar))
	                                return(false);
	                }
	                else if (MskChar==',') {
	                        ContPonto++;
	                        if(ContPonto>1)
	                                return(false);
	                }
	                else if (MskChar=='?') {
	                        if(!isAlphabeticChar(StrChar))
	                                return(false);
	                }
	                else if (MskChar=='!') {
	                        if(!isNumOrChar(StrChar))
	                                return(false);
	                }
	                else if (MskChar=='*') {
	                }
	                else {
	                        if (MskChar!=StrChar)
	                                return(false);
	                }
	        }
        return (true);
}

function isNumberChar (InString) {
	        RefString="1234567890,";
	        if (RefString.indexOf (InString, 0)==-1)
	                return (false);
	        return (true);
}


function isAlphabeticChar (InString) {
	        if (InString.length!=1)
	                return (false);
	        InString=InString.toLowerCase();
	        RefString="abcdefghijklmnopqrstuvwxyz";
	        if (RefString.indexOf (InString.toLowerCase(), 0)==-1)
	                return (false);
	        return (true);
}

//Valida Pesquisa de Vagas
function consistePesquisaVaga()
{
	Submit();
}

//Verifica se o currículo esta incompleto
function isCurriculoIncompleto(){
	var result=false;
	var objAtivo=document.getElementById("curriculoativo");
	
	if((objAtivo!=null)&&(objAtivo.value!="1")) result=!result;

	return result;
}

//Avisa o usuário que o currículo dele está incompleto quando tenta sair
function avisaCurriculoIncompleto(){
	var msg=document.getElementById("avisocurriculoincompleto");
	alert(msg.value);
}

//Confirma a saída 
function confirmaCurriculoIncompleto(){
	var msg=document.getElementById("avisocurriculoincompleto");
	
	return(confirm(msg.value));
}

//Confirma Salvar
function confirmaCurriculoIncompletoAoSalvar(){
	var msg=document.getElementById("avisocurriculoincompletoaosalvar");
	return(confirm(msg.value));
}

function OpenResultWindow(IdErro)
{   
    var url = '../resultErrorWindow.aspx?IdErro=' + 
        IdErro;

    window.showModalDialog(url, '', 'dialogWidth:350px;dialogHeight:200px;scroll:no;status=no;help=no;');
}
