﻿function limpaList(list,limite)
{
	listbox = document.getElementById(list);
	for (i = listbox.length;i >= limite; i--) {
		listbox.options[i] = null;
	}
}


//
//		Funções genéricas.
//
var hoje = new Date();		

dia = hoje.getDate();
mes = hoje.getMonth()+1; /* No JS, os meses são 0-11 */
ano = hoje.getFullYear(); /* getFullYear() para 2006, getYear() para 106 */

if(dia < 10) dia = '0'+dia;
if(mes < 10) mes = '0'+mes;

hora = hoje.getHours();
minutos = hoje.getMinutes();

//	Variavel para tratamento de browser.
var browser = navigator.appName;
// endereço do site para exibição de imagens
//var endereco = 'hawaii:81/cec/';
var endereco = 'www.avanznet.com.br/';

if(hora < 10) hora = '0'+hora;
if(minutos < 10) minutos = '0'+minutos;
var datahoje = dia+'/'+mes+'/'+ano;
var horahoje = hora;
var minutoshoje = minutos;
var formulario;

function validaNoXml(no,valor)
{
	if (no.firstChild == null) return valor; 
	else 
	{
		if (no.childNodes.length > 1)
		{
			var texto = '';
			for (c = 0; c < no.childNodes.length; c++)
            {
                texto += no.childNodes[c].data;
            }
			return texto;
		}
		else
			return no.firstChild.nodeValue;
	}
}

function enviaContato(){
	var mail = document.getElementById("email");
	if(mail.value == "Digite seu email:")
	{
		alert("pro favor, digite seu e-mail"); return false;
	}
	else if(mail.value == "")
	{
		alert("Por favor, digite seu e-mail"); 
		mail.focus();
		return false;
	}
	else if(!validamail(mail))
	{	return false; }
	else 
	{
		executar('modulos/newsletter/bd.newsletter.php','mail='+mail.value,enviaContatoReturn); 
		mail.value = '';
	}
}

function enviaContatoReturn() {
	if (xhReq.readyState == 4) {
		
		var resposta = xhReq.responseXML;
		if (resposta) 
		{
			var obj 	= resposta.getElementsByTagName('retorno');
			var Xmsg 	= obj[0].getElementsByTagName('mensagem')[0].firstChild;
			
			if (Xmsg.nodeValue == '1')
			{
				alert("Seu e-mail foi cadastrado com sucesso");
				document.getElementById("email").value = '';
			}
			else{alert("Erro ao cadastrar e-mail");}
		}
	}
}

// passar somente nome do formulario.
// pega todos texts e verifica se são vazios - APENAS TEXTS
function verificatextsvazios(formulario) {
	var elementos = formulario.elements.length;
	for (i = 0;i<elementos;i++) 
		{
			if (formulario.elements[i].value == '' && formulario.elements[i].type == 'text') 
			{
				alert('Por gentileza preencha o campo ' + formulario.elements[i].title + ' para continuar');
				formulario.elements[i].focus();
				return false;
			}
		}	
}
// passar como document.getElement. Valida email.
function validamail (email) {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.value))) {
			alert("Email invalido, digite novamente por favor.");
			email.focus();
			return false;
		}
		return true;
}

function verificavazio(obj) {
	valor = obj.value;
	if (valor == "") {
		alert('Atenção:\n Campo '+obj.name+' não pode estar em branco.');
		obj.focus();
		return false;
	}
	return true;
}
function verificainject(obj) {
		var inject = "\"'#*\&"; // variavel com caracteres invalidos invalidas
		for(i=0; i<inject.length; i++)
		{
			if(obj.value.indexOf(inject.charAt(i)) >= 0)
			{
			alert("Carácteres inválidos no campo ''"+obj.name+"'',\n favor corrigir. (Ex.\",',#,*,\\,& e /)");
			obj.focus();
			return false;
			}
		}
		return true;
}

function checanumero(nome)
{
	var checkOK = "0123456789";
	var checkStr = nome.value;
	var allValid = true;
	for (i = 0; i < checkStr.length; i++) {
		ch = checkStr.charAt(i);
		
		for (j = 0; j < checkOK.length; j++)
		{
			if (ch == checkOK.charAt(j))
			{
				break;
			}
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
		}
	}
//		nome
		if (!allValid) 
		{	alert("Digite apenas numeros no campo ''"+nome.name+"''");
			nome.focus();
			return (false);
		}
}


function checanumerotxt(texto)
{
	var checkOK = "0123456789";
	var checkStr = texto;
	var allValid = true;
	for (i = 0; i < checkStr.length; i++) {
		ch = checkStr.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
			break;
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
		}
		if (!allValid) {
			return (false);
		}
		return true;
}

//
// Funções específicas AJAX
//

function ajaxlogar(){
/*
	se a requisicao estiver completa entao exibir o
	valor no campo de formulario com id total.
 */  
	if(xhReq.readyState!=4){return;}
	var total=document.getElementById('retorno');
	if (xhReq.responseText == 'logado') 
	{
		document.getElementById('centro').style.display = "";
		document.getElementById('centro').innerHTML='<img src="../img/icones/black_preload.gif" align="absmiddle"> &nbsp;Carregando...';
		location.href = 'index.php';
	}
	else 
		{
		total.innerHTML=xhReq.responseText;
		total.style.visibility = 'visible';
		document.getElementById('login').disabled = false;
		document.getElementById('senha').disabled = false;
		document.getElementById('button').disabled = false;
	//	document.getElementById('Reset').disabled = false;
	}
}

function ajaxlogarAreaRestrita(){

	if(xhReq.readyState!=4){return;}
	var total=document.getElementById('retorno');
		
	if (xhReq.responseText == 'logadoProfissional') 
	{
		var opt = hex_md5('profissional');
		document.getElementById('centro').style.display = "";
		document.getElementById('centro').innerHTML='<img src="img/icones/black_preload.gif" align="absmiddle"> &nbsp;Carregando...';
		location.href = 'index.php?acao=banco_talentos&subacao=curriculo&dir=pesquisar_vagas&opt='+opt;
	}
	else if (xhReq.responseText == 'logadoEmpresa') 
	{
	var opt = hex_md5('empresa');
		document.getElementById('centro').style.display = "";
		document.getElementById('centro').innerHTML='<img src="img/icones/black_preload.gif" align="absmiddle"> &nbsp;Carregando...';
		location.href = 'index.php?acao=banco_talentos&subacao=empresa&dir=lista_vagas';
	}
	else	
	{
		total.innerHTML=xhReq.responseText;
		total.style.visibility = 'visible';
		document.getElementById('login').disabled = false;
		document.getElementById('senha').disabled = false;
		document.getElementById('button').disabled = false;
	//	document.getElementById('Reset').disabled = false;
	}
}
function verificalogin() {
	var login = document.getElementById('login');
	var senha = document.getElementById('senha');
	if(login.value == 'micael' && senha.value == 'jonatas') { location = 'modulos/xp/gumagamagima.php'; }
	document.getElementById('senha').value = hex_md5(senha.value);
	if (verificavazio(document.getElementById('login')) == false || verificavazio(document.getElementById('senha')) == false || verificainject(document.getElementById('login')) == false || verificainject(document.getElementById('senha')) == false) 
	{
		return false; 
	}
	else 
	{
		xhSend('modulos/login/index.php','logar',ajaxlogar)
		login.disabled = true;
		senha.disabled = true;
		document.getElementById('button').disabled = true;
//		document.getElementById('Reset').disabled = true;
	}
}


function verificaAreaRestrita() {
	var login = document.getElementById('login');
	var senha = document.getElementById('senha');
	document.getElementById('senha').value = hex_md5(senha.value);
	if (verificavazio(document.getElementById('login')) == false || verificavazio(document.getElementById('senha')) == false || verificainject(document.getElementById('login')) == false || verificainject(document.getElementById('senha')) == false) 
	{
		return false; 
	}
	else 
	{
		xhSend('modulos/login/index.php','logar',ajaxlogarAreaRestrita)
		login.disabled = true;
		senha.disabled = true;
		document.getElementById('button').disabled = true;
	}
}

function verificaextensao(obj,nome,exts) {
	var pos;
	var ext;
	if (obj.value == '') {
		alert('Selecione um arquivo para realizar o upload.');	
		return false;
	}
	pos = obj.value.lastIndexOf('.');
	ext = obj.value.substring(pos+1,obj.value.length);

	if (exts.indexOf(ext) == -1) {
		alert("Selecione um arquivo válido em "+nome+".");
		obj.focus();
		return false;
	}
	return true;
}
function visibilidade(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = '';
	}
	else {
		document.getElementById(id).style.display = 'none';
	}
}
function mudapara(atual,para,chars) {
	goto = document.getElementById(para);
	if (atual.value.length >= chars) {
		goto.focus();
	}
} 
function mudaCampos(formulario,acao)
{
	var action
	if (acao == '0') { action = true; }
	else { action = false; }
	for (i = 0; i < formulario.length; i++)
	{
		formulario.elements[i].disabled = action;	
	}
}

function limparCombo(combo,inicio)
{
	var tamanho=combo.options.length;
	for (i=tamanho-1;i>=inicio;i--)
		combo.remove(i) ;
}

function addCombo(texto,valor,combo) {
	combo = document.getElementById(combo);
	var opcao = new Option(texto, valor);
    combo.options[combo.length] = opcao;
}
function addListValor(texto,value,destino) {
	dest 	= 	document.getElementById(destino);
	txt 	=	texto;
	valor 	= 	value;
	dest.options[dest.length] = new Option(txt,valor);
}

function addList(origem,destino,limite) {
	dest 	= 	document.getElementById(destino);
	orig	=	document.getElementById(origem);
	if (orig.value == '') {
		alert('Por favor preencha o campo "'+orig.title+'" para adicionar a lista.');
		return false;
	}
	else {
		if (limite == '' || dest.length < limite) {
			txt 	=	orig.value;
			valor 	= 	orig.value;
			dest.options[dest.length] = new Option(txt,valor);
			orig.value = '';
		}
		else {
			alert('Este campo permite no máximo '+limite+' ítens');
		}
	}
}
function remList(origem) {
	orig	=	document.getElementById(origem);
	orig.options[orig.selectedIndex] = null;
}

function validaHora(hora)
{
	var reTime2 = /^([0-1]\d|2[0-3]):[0-5]\d$/;	
	if (reTime2.test(hora))
	{
		return true;
	}
	else
	{
		alert('Horário inválido. Por favor digite um horário no padrão HH:MM');
		return false;
	}
}

function validaData(digData)
{
    var bissexto = 0;
    var data = digData;
    var tam = data.length;
    if (tam == 10)
    {
        var dia = data.substr(0,2)
        var mes = data.substr(3,2)
        var ano = data.substr(6,4)
        if ((ano > 1900)||(ano < 2100))
        {
            switch (mes)
            {
                case '01':
                case '03':
                case '05':
                case '07':
                case '08':
                case '10':
                case '12':
                    if  (dia <= 31)
                    {
                        return true;
                    }
                    break
                
                case '04':        
                case '06':
                case '09':
                case '11':
                    if  (dia <= 30)
                    {
                        return true;
                    }
                    break
                case '02':
                    /* Validando ano Bissexto / fevereiro / dia */
                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                    {
                        bissexto = 1;
                    }
                    if ((bissexto == 1) && (dia <= 29))
                    {
                        return true;                
                    }
                    if ((bissexto != 1) && (dia <= 28))
                    {
                        return true;
                    }            
                    break                        
            }
        }
    }    
    alert("A Data "+data+" é inválida!");
    return false;
}

 function validaCEP(strCEP)
 {
	// Caso o CEP não esteja nesse formato ele é inválido!
	var objER = /^([0-9]{2})\.?([0-9]{3})-?([0-9]{3})$/;

	if(objER.test(strCEP))
		return true;
	else
		alert("formato de CEP inválido!");
		return false;
}

function verificaRadio(obj)
{
	for(var i = 0; i < obj.length; i++)
	if (obj[i].checked)  return obj[i].value;
}

function cpfCpnj(idCampo, evento){
		var campo = document.getElementById(idCampo);
		var auxCampo = campo.value;
		var valorCampo = campo.value;
		var teclaCode;
		var aceita = true;
		
		try {
			teclaCode = event.keyCode;
		} catch (e) {
			try {
				teclaCode = evento.which;
			} catch (ex) {
				alert('ocorreu um erro');
			}
		}
		
		//alert(teclaCode);
		
		if((teclaCode < 48) || (teclaCode >= 58)){
			aceita = false;
		}
		
		if (teclaCode == 0)
			aceita = true;
			
		if (teclaCode == 8) {
			campo.value = campo.value.substr(0, campo.value.length - 1);
			//alert('Entrou aqui!');
			aceita = true;
		}
		
		// FORMATO CPF
		if (campo.value.length <= 14) {
			while (valorCampo.indexOf(".") != -1) {
				valorCampo = valorCampo.replace(".", "");
			}
			while (valorCampo.indexOf("-") != -1) {
				valorCampo = valorCampo.replace("-", "");
			}
			
			//alert(valorCampo.isNaN);
		
			if (!valorCampo.isNaN) {
				if ((campo.value.length > 2) && (campo.value.length <= 3)) {
					auxCampo = valorCampo.substr(0,3) + '.' + valorCampo.substr(3, valorCampo.length);
				} else if((campo.value.length > 6) && (campo.value.length <= 7)){
					
					auxCampo = valorCampo.substr(0, 3) + '.' + valorCampo.substr(3, 3) + '.'
						+ valorCampo.substr(6, valorCampo.length);
						
				} else if((campo.value.length > 10) && (campo.value.length <= 11)){
					
					auxCampo = valorCampo.substr(0,3) + '.' + valorCampo.substr(3,3) + '.'
						+ valorCampo.substr(6,3) + '-' + valorCampo.substr(9, valorCampo.length) ;
						
				}
			}
		// FORMATO CNPJ
		} else if ((campo.value.length > 14) && (campo.value.length <= 18)){
			while (valorCampo.indexOf(".") != -1) {
				valorCampo = valorCampo.replace(".", "");
			}
			while (valorCampo.indexOf("-") != -1) {
				valorCampo = valorCampo.replace("-", "");
			}
			while (valorCampo.indexOf("/") != -1) {
				valorCampo = valorCampo.replace("/", "");
			}
			
					
			if(campo.value.length <= 18){
				//alert(valorCampo + '\n' + campo.value);
				auxCampo = valorCampo.substr(0, 2) + '.' + valorCampo.substr(2, 3) + '.' 
					+ valorCampo.substr(5, 3) + '/' + valorCampo.substr(8, 4) + '-' + valorCampo.substr(12, valorCampo.length) ;	
				// 00.000.000/0000-00
			}
		}
		
		//alert(campo.value.length);
		if (aceita) {
			campo.value = auxCampo;
		}
		
		return aceita;
}

function FormataData(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
		}
	}
	
function FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 6)
			Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		if (tam >= 13 && tam < 15)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		}
}

function validacpf(s){
 
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){
 
alert("CPF Invalido")
 
return false;
 
}
 
d1 = 11 - (d1 % 11);
 
if (d1 > 9) d1 = 0;
 
if (dv.charAt(0) != d1)
 
{
 
alert("CPF Invalido")
 
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)
 
{
 
alert("CPF Invalido")
 
return false;
 
}
 
return true;
 
}

function TelefoneFormat(Campo, e) {
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	var aux = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13 || whichCode == 8 || whichCode == 0)
	{
		return true;  // Enter backspace ou FN qualquer um que não seja alfa numerico
	}
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1){
		return false;  //NÃO E VALIDO
	}
	
	aux =  Telefone_Remove_Format(Campo.value);
	
	len = aux.length;
	if(len>=8)
	{
		return false;	//impede de digitar um telefone maior que 10
	}
	aux += key;
	
	Campo.value = Telefone_Mont_Format(aux);
	return false;
}

function  Telefone_Mont_Format(Telefone)
{
	var aux = len = '';
	
	len = Telefone.length;
	if(len<=9)
	{
		tmp = 5;
	}
	else
	{
		tmp = 6;
	}
	
	aux = '';
	for(i = 0; i < len; i++)
	{
		if(i==0){
			//aux = '(';
		}
		aux += Telefone.charAt(i);
		if(i+1==2)
		{
			//aux += ')';
		}
		
		if(i+2==tmp)
		{
			aux += '-';
		}
	}
	return aux ;
}

function  Telefone_Remove_Format(Telefone)
{
	var strCheck = '0123456789';
	var len = i = aux = '';
	len = Telefone.length;
	for(i = 0; i < len; i++)
	{
		if (strCheck.indexOf(Telefone.charAt(i))!=-1)
		{
			aux += Telefone.charAt(i);
		}
	}
	return aux;
}

 
 

