// ***************************************
// * VARIAVEIS DE CONTROLE AJAX - INICIO *
// ***************************************
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}
/*
Padawan's JavaScript-Mega-Validator 3000+
Todos os direitos reservados para Diego Pires Plentz
Você pode usar esse código nas suas páginas desde que mantenha os créditos ;-)
*/
//Verifica qual o browser do visitante e armazena na variável púbica clientNavigator,
//Caso Internet Explorer(IE) outros (Other)
if (navigator.appName.indexOf('Microsoft') != -1){
	clientNavigator = "IE";
}else{
	clientNavigator = "Other";
}
function Verifica_Data(data, obrigatorio){
//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
 var data = document.getElementById(data);
	var strdata = data.value;
	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
		//Verifica a quantidade de digitos informada esta correta.
		if (strdata.length != 10){
			alert("Formato da data não é válido. Formato correto:- dd/mm/aaaa.");
			data.focus();
			return false
		}
		//Verifica máscara da data
		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
			alert("Formato da data não é válido. Formato correto:- dd/mm/aaaa.");
			data.focus();
			return false
		}
		dia = strdata.substr(0,2)
		mes = strdata.substr(3,2);
		ano = strdata.substr(6,4);
		//Verifica o dia
		if (isNaN(dia) || dia > 31 || dia < 1){
			alert("Formato do dia não é válido.");
			data.focus();
			return false
		}
		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
			if (dia == "31"){
				alert("O mês informado não possui 31 dias.");
				data.focus();
				return false
			}
		}
		if (mes == "02"){
			bissexto = ano % 4;
			if (bissexto == 0){
				if (dia > 29){
					alert("O mês informado possui somente 29 dias.");
					data.focus();
					return false
				}
			}else{
				if (dia > 28){
					alert("O mês informado possui somente 28 dias.");
					data.focus();
					return false
				}
			}
		}
	//Verifica o mês
		if (isNaN(mes) || mes > 12 || mes < 1){
			alert("Formato do mês não é válido.");
			data.focus();
			return false
		}
		//Verifica o ano
		if (isNaN(ano)){
			alert("Formato do ano não é válido.");
			data.focus();
			return false
		}
	}
}
function Compara_Datas(data_inicial, data_final){
	//Verifica se a data inicial é maior que a data final
	var data_inicial = document.getElementById(data_inicial);
	var data_final   = document.getElementById(data_final);
	str_data_inicial = data_inicial.value;
	str_data_final   = data_final.value;
	dia_inicial      = data_inicial.value.substr(0,2);
	dia_final        = data_final.value.substr(0,2);
	mes_inicial      = data_inicial.value.substr(3,2);
	mes_final        = data_final.value.substr(3,2);
	ano_inicial      = data_inicial.value.substr(6,4);
	ano_final        = data_final.value.substr(6,4);
	if(ano_inicial > ano_final){
		alert("A data inicial deve ser menor que a data final."); 
		data_inicial.focus();
		return false
	}else{
 	if(ano_inicial == ano_final){
  	if(mes_inicial > mes_final){
   	alert("A data inicial deve ser menor que a data final.");
				data_final.focus();
				return false
			}else{
				if(mes_inicial == mes_final){
					if(dia_inicial > dia_final){
						alert("A data inicial deve ser menor que a data final.");
						data_final.focus();
						return false
					}
				}
			}
		}
	}
}
function Verifica_Hora(hora, obrigatorio){
//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
	var hora = document.getElementById(hora);
	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){
		if(hora.value.length < 5){
			alert("Formato da hora inválido. Por favor, informe a hora no formato correto: hh:mm");
			hora.focus();
			return false
		}
		if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){
			alert("Formato da hora inválido.");
			hora.focus();
			return false
		}
		if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
			alert("Formato do minuto inválido.");
			hora.focus();
			return false
		}
	}
}
function Verifica_Email(email, obrigatorio){
//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
	var email = document.getElementById(email);
	if((obrigatorio == 1) || (obrigatorio == 0 && email.value != "")){
		if(!email.value.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.[a-zA-Z0-9._-]+)/gi)){
			alert("Informe um e-mail válido");
			email.focus();
			return false
		}
	}
}
function Verifica_Tamanho(campo, tamanho){
//usado para campos textarea onde não se tem o atributo maxlenght
	var campo = document.getElementById(campo);
	if(campo.value.length > tamanho){
		alert("O campo suporta no máximo " + tamanho + " caracteres.");
		campo.focus();
		return false
	}
}
function Verifica_Cep(cep, obrigatorio){
//Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não
	var cep    = document.getElementById(cep);
	var strcep = cep.value;
	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
		if (strcep.length != 9){
			alert("CEP informado inválido.");
			cep.focus();
			return false
		}else{
			if (strcep.indexOf("-") != 5){
				alert("Formato de CEP informado inválido.");
				cep.focus();
				return false
			}else{
				if (isNaN(strcep.replace("-","0"))){
					alert("CEP informado inválido.");
					cep.focus();
					return false
				}
			}
		}
	}	  
}
function Bloqueia_Caracteres(evnt){

//Função permite digitação de números
	if (clientNavigator == "IE"){
		if (evnt.keyCode < 48 || evnt.keyCode > 57){
			return false
		}
	}else{
		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
		
		
			return false
		}
	}
}
//function SomenteNumero(e){
////<input type='text' size='10' value='' onkeypress='return SomenteNumero(event)'>
//    var tecla=(window.event)?event.keyCode:e.which;
//    if((tecla > 47 && tecla < 58)) return true;
//    else{
//    if (tecla != 8) return false;
//    else return true;
//    }
//}

function SomenteNumeros(evtKeyPress) {  
    var nTecla;  
    var detecta;  
    var boolean = false;  
  
    if(window.event){  
        nTecla = window.event.keyCode;  
        detecta = 0;  
    }else if (evtKeyPress){  
        nTecla = evtKeyPress.which;  
        detecta = 1;  
    }  
  
    if(detecta==0){  
        if(nTecla > 47 && nTecla < 58){  
            boolean = true;  
        }  
    }else{  
        if((nTecla > 47 && nTecla < 58)||(nTecla == 8)||(nTecla == 9)||(nTecla == 37)||(nTecla == 39)||(nTecla == 46)){  
            boolean = true;  
        }  
    }  
  
    return boolean;  
}  
////////////////////////////////////



function Ajusta_Data(input, evnt){
//Ajusta máscara de Data e só permite digitação de números
	if (input.value.length == 2 || input.value.length == 5){
		if(clientNavigator == "IE"){
			input.value += "/";
		}else{
			if(evnt.keyCode == 0){
				input.value += "/";
			}
		}
	}
//Chama a função Bloqueia_Caracteres para só permitir a digitação de números
 return Bloqueia_Caracteres(evnt);
}

//////////////////////////////////////////////////
function mascaraData(campoData){
 var data = campoData.value;
 if (data.length == 2){
     data = data + '/';
     campoData.value = data;
     return true;
 }
 if (data.length == 5){
     data = data + '/';
     campoData.value = data;
     return true;
 }
}
//////////////////////////////////////////////////


function Ajusta_Hora(input, evnt){
//Ajusta máscara de Hora e só permite digitação de números
	if (input.value.length == 2){
		if(clientNavigator == "IE"){
			input.value += ":";
		}else{
			if(evnt.keyCode == 0){
				input.value += ":";
			}
		}
	}
//Chama a função Bloqueia_Caracteres para só permitir a digitação de números
	return Bloqueia_Caracteres(evnt);
}
function Ajusta_Cep(input, evnt){
//Ajusta máscara de CEP e só permite digitação de números
	if (input.value.length == 5){
		if(clientNavigator == "IE"){
			input.value += "-";
		}else{
			if(evnt.keyCode == 0){
				input.value += "-";
			}
		}
	}
//Chama a função Bloqueia_Caracteres para só permitir a digitação de números
	return Bloqueia_Caracteres(evnt);
}
function Atualiza_Opener(){
//Atualiza a página opener da popup que chamar a função
	window.opener.location.reload();
}
// **********************************************************
// * VERIFICA SE O CAMPO RECEBIDO COMO PARAMETRO ESTÁ VAZIO *
// **********************************************************
function isEmpty(pStrText){
  	var	len = pStrText.length;
  	var pos;
  	var vStrnewtext = "";

  	for (pos=0; pos<len; pos++){
   		if (pStrText.substring(pos, (pos+1)) != " "){
     			vStrnewtext = vStrnewtext + pStrText.substring(pos, (pos+1));
   		}
  	}

  	if (vStrnewtext.length > 0)
    		return false;
  	else
    		return true;
}
// ***********************************************************

// ***********************************************************
// * VERIFICA SE O CAMPO RECEBIDO COMO PARAMETRO É UM NUMERO *
// ***********************************************************
function isNumber(numero){
   var CaractereInvalido = false;

   for (i=0; i < numero.length; i++){
      var Caractere = numero.charAt(i);
      if(Caractere != "." && Caractere != "," && Caractere != "-"){
         if (isNaN(parseInt(Caractere))) CaractereInvalido = true;
      }
   }
   return !CaractereInvalido;
}
// ***********************************************************

// ***********************************************************
// * VERIFICA SE O CAMPO RECEBIDO COMO PARAMETRO É UM E-MAIL *
// ***********************************************************
function isEmail(text){
   var arroba = "@",
       ponto = ".",
       posponto = 0,
       posarroba = 0;

   if (text =="") return false;

   for (var indice = 0; indice < text.length; indice++){

       if (text.charAt(indice) == arroba) {
          posarroba = indice;
          break;
       }
   }

   for (var indice = posarroba; indice < text.length; indice++){
       if (text.charAt(indice) == ponto) {
          posponto = indice;
          break;
       }
   }

   if (posponto == 0 || posarroba == 0) return false;
   if (posponto == (posarroba + 1)) return false;
   if ((posponto + 1) == text.length) return false;
   return true;
}
// ***********************************************************

// ***********************************************************
// * ESCREVE A DATA E HORA POR EXTENSO                       *
//   Exemplo de Uso:    window.onload = tick;                *
//   Exemplo de Uso:    window.setTimeout("tick();", 100);   *
// ***********************************************************
   function tick()
   {
      var hours, minutes, seconds, ap;
      var intHours, intMinutes, intSeconds;
      var today, intAno, intMes, intDia, Mes, intSem, Dia;
      today      = new Date();
      intHours   = today.getHours();
      intMinutes = today.getMinutes();
      intSeconds = today.getSeconds();
      intAno     = today.getYear();
      intMes     = today.getMonth();
      Mes        = new Array("janeiro","fevereiro","março","abril","maio","junho","julho","agosto","setembro","outubro","novembro","dezembro") ;
      Mes        = Mes[intMes];
      intDia     = today.getDate();
      intSem     = today.getDay();
      Dia        = new Array("   Domingo   ","Segunda-feira"," Terça-feira "," Quarta-feira"," Quinta-feira"," Sexta-feira ","    Sábado   ") ;
      Dia        = Dia[intSem];
      if (intHours == 0)
      {
         hours = "12:";
         ap = "Meia-noite";
      }
      else if (intHours < 12)
      {
         hours = intHours+":";
         ap = "am";
      }
      else if (intHours == 12)
      {
         hours = "12:";
         ap = "Meio-dia";
      }
      else
      {
         intHours = intHours - 12
         hours = intHours + ":";
         ap = "pm";
      }
      if (intMinutes < 10) { minutes = "0"+intMinutes+":"; } else { minutes = intMinutes+":"; }
      if (intSeconds < 10) { seconds = "0"+intSeconds+" "; } else { seconds = intSeconds+" "; }
      timeString =  Dia+", "+intDia+" de "+Mes+" de "+intAno+" -   "+hours+minutes+seconds+ap
      document.all("clock").innerHTML = timeString;
      window.setTimeout("tick();", 100);
   }
// ***********************************************************

// ****************************************************************
// * POSICIONA O CURSOR NO PRIMEIRO CAMPO DO FORMS AO FAZER  LOAD *
// ****************************************************************
function PrimeiroFocus()
{
document.forms[0].elements[0].focus();
document.forms[0].elements[0].select();
//document.Formulário.nomecompleto.focus();
//document.Formulário.nomecompleto.select();
}
// ****************************************************************

function ProcessaContato(){
   // **************************************************
   // VERIFICA SE OS CAMPOS ESTÃO PREENCHIDOS - INICIO *
   // **************************************************
   // CONSISTE NOME COMPLETO
   if(isEmpty(document.getElementById('nomecompleto').value)){
      alert("Por favor preencha seu nome corretamente.");
      document.formcontato.nomecompleto.focus();
      return false;
   }

   // CONSISTE CIDADE PREENCHIDA
   if(isEmpty(document.getElementById('nomecidade').value)){
      alert("Por informe a cidade corretamente.");
      document.formcontato.nomecidade.focus();
      return false;
   }

   // CONSISTE O ESTADO INFORMADO
   if(isEmpty(document.getElementById('estado').value)){
      alert("Por favor informe seu estado.");
      document.formcontato.estado.focus();
      return false;
   }

   // CONSISTE EMAIL PREENCHIDO
   if(isEmpty(document.getElementById('email1').value)){
      alert("Por favor preencha o primeiro e-mail corretamente.");
      document.formcontato.email1.focus();
      return false;
   }
   // CONSISTE EMAIL1 VÁLIDO
   if(isEmail(document.getElementById('email1').value)==false){
      alert("Por favor informe um endereço de e-mail válido.");
      document.formcontato.email1.focus();
      return false;
   }

   if(isEmpty(document.getElementById('email2').value)){
      alert("Por favor preencha o segundo e-mail corretamente.");
      document.formcontato.email2.focus();
      return false;
   }
   // CONSISTE EMAIL2 VÁLIDO
   if(isEmail(document.getElementById('email2').value)==false){
      alert("Por favor informe um endereço de e-mail válido.");
      document.formcontato.email2.focus();
      return false;
   }

   // VERIFICA SE OS E-MAILS INFORMADOS SÃO IGUAIS
   if (!(document.getElementById('email1').value==document.getElementById('email2').value )) {
      alert("Por favor verifique os e-mails informados pois os mesmos são diferentes.");
      document.formcontato.email1.focus();
      return false;
   }

   // CONSISTE NUMERO DE TELEFONE
   if(isEmpty(document.getElementById('telefone').value)){
      alert("Por favor informe número de telefone.");
      document.formcontato.telefone.focus();
      return false;
   }

   // CONSISTE O TIPO DE IMOVEL
   if(isEmpty(document.getElementById('tipoimovel').value)){
      alert("Por favor informe o tipo de imóvel.");
      document.formcontato.tipoimovel.focus();
      return false;
   }
   // CONSISTE MENSAGEM PREENCHIDA
   if(isEmpty(document.getElementById('descricao').value)){
      alert("Por favor preencha a descrição corretamente.");
      document.formcontato.descricao.focus();
      return false;
   }
   // **************************************************
   // VERIFICA SE OS CAMPOS ESTÃO PREENCHIDOS - FIM    *
   // **************************************************



   // *****************************************
   // VALIDA INFORMAÇÕES PREENCHIDAS - FIM    *
   // *****************************************

   var vnomecompleto  =document.getElementById('nomecompleto').value;
   var vnomecidade    =document.getElementById('nomecidade').value;
   var vestado        =document.getElementById('estado').value;
   var vemail1        =document.getElementById('email1').value;
   var vtelefone      =document.getElementById('telefone').value;
   var vtelefone2     =document.getElementById('telefone2').value;
   var vhorariocontato=document.getElementById('horariocontato').value;
   var vhora1         =document.getElementById('hora1').value;
   var vhora2         =document.getElementById('hora2').value;
   var vtipoimovel    =document.getElementById('tipoimovel').value;
   var vdescricao     =document.getElementById('descricao').value;

   var vurl='processacontato.php' + '?pnomecompleto='   + vnomecompleto
                                  + '&pnomecidade='     + vnomecidade
                                  + '&pestado='         + vestado
                                  + '&pemail1='         + vemail1
                                  + '&ptelefone='       + vtelefone
                                  + '&ptelefone2='      + vtelefone2
                                  + '&phorariocontato=' + vhorariocontato
                                  + '&phora1='          + vhora1
                                  + '&phora2='          + vhora2
                                  + '&ptipoimovel='     + vtipoimovel
                                  + '&pdescricao='      + vdescricao
                                  + '&prandom='         + Math.random();
   http.abort();
   http.open("GET", vurl , true);
   http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('idblocoprincipal').innerHTML = http.responseText;
    }
   }
  http.send(null);
}

//############################################################################################
//PROCESSA TRABALHE - BEGIN
//############################################################################################
function ProcessaTrabalhe(){
   // **************************************************
   // VERIFICA SE OS CAMPOS ESTÃO PREENCHIDOS - INICIO *
   // **************************************************
   // CONSISTE NOME COMPLETO
   if(isEmpty(document.getElementById('nomecompleto').value)){
      alert("Por favor preencha seu nome corretamente.");
      document.formtrabalhe.nomecompleto.focus();
      return false;
   }

   // CONSISTE DATA SEXO
//var found_it
//found_it=0;
//for (var i=0; i<document.formtrabalhe.sexo.length; i++)  {
//				if (document.formtrabalhe.sexo[i].checked) {
//							found_it=1;
//				}
//}
//if (found_it==0) {
//      alert("Por informe o sexo.");
//      document.formtrabalhe.sexo[0].focus();
//      return false;
//   }

   // CONSISTE DATA NASCIMENTO
   if(isEmpty(document.getElementById('datanascimento').value)){
      alert("Por informe a data de nascimento.");
      document.formtrabalhe.datanascimento.focus();
      return false;
   }

   // CONSISTE NUMERO DE TELEFONE
   if(isEmpty(document.getElementById('telefonecelular').value)){
      alert("Por favor informe número de telefone celular.");
      document.formtrabalhe.telefonecelular.focus();
      return false;
   }
			
   // CONSISTE HORÁRIO DE CONTATO
   if(isEmpty(document.getElementById('horariocontato').value)){
      alert("Por informe o horário de contato corretamente.");
      document.formtrabalhe.horariocontato.focus();
      return false;
   }

   // CONSISTE EMAIL VÁLIDO
   if(isEmail(document.getElementById('email').value)==false){
      alert("Por favor informe um endereço de e-mail válido.");
      document.formtrabalhe.email.focus();
      return false;
   }
   if(isEmail(document.getElementById('emailconfirm').value)==false){
      alert("Por favor informe um endereço de e-mail válido.");
      document.formtrabalhe.emailconfirm.focus();
      return false;
   }
			
   // VERIFICA SE OS E-MAILS INFORMADOS SÃO IGUAIS
   if (!(document.getElementById('email').value==document.getElementById('emailconfirm').value )) {
      alert("Por favor verifique os e-mails informados pois os mesmos são diferentes.");
      document.formtrabalhe.email.focus();
      return false;
   }
			
   // CONSISTE O ESTADO INFORMADO
   if(isEmpty(document.getElementById('rua').value)){
      alert("Por favor informe corretamente a rua.");
      document.formtrabalhe.rua.focus();
      return false;
   }
			
   // CONSISTE O NUMERO INFORMADO
   if(isEmpty(document.getElementById('numero').value)){
      alert("Por favor informe corretamente o numero.");
      document.formtrabalhe.numero.focus();
      return false;
   }
			
   // CONSISTE O BAIRRO INFORMADO
   if(isEmpty(document.getElementById('bairro').value)){
      alert("Por favor informe corretamente o bairro.");
      document.formtrabalhe.bairro.focus();
      return false;
   }
			
   // CONSISTE O CEP INFORMADO
   if(isEmpty(document.getElementById('cep').value)){
      alert("Por favor informe corretamente o cep.");
      document.formtrabalhe.cep.focus();
      return false;
   }
			
   // CONSISTE A CIDADE INFORMADA
   if(isEmpty(document.getElementById('cidade').value)){
      alert("Por favor informe corretamente a cidade.");
      document.formtrabalhe.cidade.focus();
      return false;
   }
			
   // CONSISTE O ESTADO INFORMADO
   if(isEmpty(document.getElementById('estado').value)){
      alert("Por favor informe corretamente o estado.");
      document.formtrabalhe.estado.focus();
      return false;
   }
			
   // CONSISTE A MENSAGEM ENVIADA
   if(isEmpty(document.getElementById('mensagem').value)){
      alert("Por favor informe corretamente a experiencia profissional.");
      document.formtrabalhe.mensagem.focus();
      return false;
   }
			
			if (document.formtrabalhe.mensagem.value.length > 500) {
      alert("Não é permitido mais que 500 caracteres na experiência profissional.");
      document.formtrabalhe.mensagem.focus();
      return false;
			}
   // **************************************************
   // VERIFICA SE OS CAMPOS ESTÃO PREENCHIDOS - FIM    *
   // **************************************************



   // *****************************************
   // VALIDA INFORMAÇÕES PREENCHIDAS - FIM    *
   // *****************************************
var vnomecompleto      =document.getElementById('nomecompleto').value;
var vsexo              =document.getElementById('sexo').value;
var vdatanascimento    =document.getElementById('datanascimento').value;
var vtelefonecelular   =document.getElementById('telefonecelular').value;
var vtelefonefixo      =document.getElementById('telefonefixo').value;
var vhorariocontato    =document.getElementById('horariocontato').value;
var vemail             =document.getElementById('email').value;
var vemailconfirm      =document.getElementById('emailconfirm').value;
var vrua               =document.getElementById('rua').value;
var vnumero            =document.getElementById('numero').value;
var vcomplemento       =document.getElementById('complemento').value;
var vbairro            =document.getElementById('bairro').value;
var vcep               =document.getElementById('cep').value;
var vcidade            =document.getElementById('cidade').value;
var vestado            =document.getElementById('estado').value;
var vmensagem          =document.getElementById('mensagem').value;

var vurl='processatrabalhe.php' + '?pnomecompleto='    +  vnomecompleto
                                + '&psexo='            +  vsexo
                                + '&pdatanascimento='  +  vdatanascimento
                                + '&ptelefonecelular=' +  vtelefonecelular
                                + '&ptelefonefixo='    +  vtelefonefixo
                                + '&phorariocontato='  +  vhorariocontato
                                + '&pemail='           +  vemail
                                + '&pemailconfirm='    +  vemailconfirm
                                + '&prua='             +  vrua
                                + '&pnumero='          +  vnumero
                                + '&pcomplemento='     +  vcomplemento
                                + '&pbairro='          +  vbairro
                                + '&pcep='             +  vcep
                                + '&pcidade='          +  vcidade
                                + '&pestado='          +  vestado
                                + '&pmensagem='        +  vmensagem
                                + '&prandom='          + Math.random();

   http.abort();
   http.open("GET", vurl , true);
   http.onreadystatechange=function() {
    if(http.readyState == 4) {
     document.getElementById('idblocoprincipal').innerHTML = http.responseText;
    }
   }
  http.send(null);
} 

//############################################################################################
//PROCESSA TRABALHE - END
//############################################################################################


//############################################################################################
// MASCARAS DIVERSAS
//############################################################################################
// JavaScript Document
//<input type="text" name="cep" onKeyPress="MascaraCep(form1.cep);" maxlength="10" onBlur="ValidaCep(form1.cep)">

//adiciona mascara de cnpj
function MascaraCNPJ(cnpj){
    if(mascaraInteiro(cnpj)==false){
        event.returnValue = false;
    }
    return formataCampo(cnpj, '00.000.000/0000-00', event);
}
 
//adiciona mascara de cep
function MascaraCep(cep){
        if(mascaraInteiro(cep)==false){
        event.returnValue = false;
    }    
    return formataCampo(cep, '00.000-000', event);
}
 
//adiciona mascara de data
function MascaraData(data){
    if(mascaraInteiro(data)==false){
        event.returnValue = false;
    }    
    return formataCampo(data, '00/00/0000', event);
}
 
//adiciona mascara de data formato mysql
function MascaraDataSQL(data){
    if(mascaraInteiro(data)==false){
        event.returnValue = false;
    }    
    return formataCampo(data, '0000-00-00', event);
}
 
//adiciona mascara IP
function MascaraIP(ip){
    if(mascaraInteiro(ip)==false){
        event.returnValue = false;
    }    
    return formataCampo(ip, '000.000.000.000', event);
}
 
//adiciona mascara ao telefone
function MascaraTelefone(tel){ 
    if(mascaraInteiro(tel)==false){
        event.returnValue = false;
    }

//	var campo = document.getElementById(tel);
	if(tel.value.length > 13){
//		campo.focus();
        event.returnValue = false;
	}
    return formataCampo(tel, '(00) 0000-0000', event);
}

function mascara_telefone(tel) {
if(tel.value.length == 2) {
tel.value += ' ';
}
if(tel.value.length == 7) {
tel.value += '-';
}
}

 
//adiciona mascara ao CPF
function MascaraCPF(cpf){
    if(mascaraInteiro(cpf)==false){
        event.returnValue = false;
    }    
    return formataCampo(cpf, '000.000.000-00', event);
}
 
//valida telefone
function ValidaTelefone(tel){
    exp = /\(\d{2}\)\ \d{4}\-\d{4}/
    if(!exp.test(tel.value))
        alert('Numero de Telefone Invalido!');
}
 
//valida CEP
function ValidaCep(cep){
    exp = /\d{2}\.\d{3}\-\d{3}/
    if(!exp.test(cep.value))
        alert('Numero de Cep Invalido!');        
}
 
//valida documentos
function ValidaDocs(doc){
    exp = /^[a-zA-Z0-9-_\.]+\.(pdf|txt|doc|xls|ppt)$/
    if(!exp.test(doc.value))
        alert('Documento Invalido!');        
}
 
//valida imagens
function ValidaImg(img){
    exp = /^[a-zA-Z0-9-_\.]+\.(jpg|gif|png)$/
    if(!exp.test(img.value))
        alert('Imagem Invalida!');        
}
 
//valida ip
function ValidaIp(ip){
    exp = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/
    if(!exp.test(ip.value))
        alert('Endereço IP Invalido!');        
}
 
//valida data mysql
function ValidaDataSQL(sql){
    exp = /^\d{4}-(0[0-9]|1[0,1,2])-([0,1,2][0-9]|3[0,1])$/
    if(!exp.test(sql.value))
        alert('Endereço IP Invalido!');        
}
 
//valida data
function ValidaData(data){
    exp = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/
    if(!exp.test(data.value))
        alert('Data Invalida!');            
}
 
 
//valida dígito
function ValidaDigito(digito){
    exp = /^\d+$/
    if(!exp.test(digito.value))
        alert('Dígito Invalido!');            
}
 
//valida email
function ValidaEmail(email){
    exp = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/
    if(!exp.test(email.value))
        alert('E-mail Invalido!');            
}
 
//valida o CPF digitado
function ValidarCPF(Objcpf){
    var cpf = Objcpf.value;
    exp = /\.|\-/g
    cpf = cpf.toString().replace( exp, "" );
    var digitoDigitado = eval(cpf.charAt(9)+cpf.charAt(10));
    var soma1=0, soma2=0;
    var vlr =11;
 
    for(i=0;i<9;i++){
        soma1+=eval(cpf.charAt(i)*(vlr-1));
        soma2+=eval(cpf.charAt(i)*vlr);
        vlr--;
    }    
    soma1 = (((soma1*10)%11)==10 ? 0:((soma1*10)%11));
    soma2=(((soma2+(2*soma1))*10)%11);
 
    var digitoGerado=(soma1*10)+soma2;
    if(digitoGerado!=digitoDigitado)    
        alert('CPF Invalido!');        
}
 
//valida numero inteiro com mascara
function mascaraInteiro(){
    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }
    return true;
}
 
//valida o CNPJ digitado
function ValidarCNPJ(ObjCnpj){
    var cnpj = ObjCnpj.value;
    var valida = new Array(6,5,4,3,2,9,8,7,6,5,4,3,2);
    var dig1= new Number;
    var dig2= new Number;
 
    exp = /\.|\-|\//g
    cnpj = cnpj.toString().replace( exp, "" );
    var digito = new Number(eval(cnpj.charAt(12)+cnpj.charAt(13)));
 
    for(i = 0; i<valida.length; i++){
        dig1 += (i>0? (cnpj.charAt(i-1)*valida[i]):0);    
        dig2 += cnpj.charAt(i)*valida[i];    
    }
    dig1 = (((dig1%11)<2)? 0:(11-(dig1%11)));
    dig2 = (((dig2%11)<2)? 0:(11-(dig2%11)));
 
    if(((dig1*10)+dig2) != digito)    
        alert('CNPJ Invalido!');
 
}
 
function ValidaDataHora(data){
exp = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4} \d{2}:\d{2}$/
if(!exp.test(data.value))
alert('Data Invalida!');
}
 
 
//formata de forma generica os campos
function formataCampo(campo, Mascara, evento) {
    var boleanoMascara;
 
    var Digitato = evento.keyCode;
    exp = /\-|\.|\/|\(|\)| /g
    campoSoNumeros = campo.value.toString().replace( exp, "" );
 
    var posicaoCampo = 0;    
    var NovoValorCampo="";
    var TamanhoMascara = campoSoNumeros.length;;
 
    if (Digitato != 8) { // backspace
        for(i=0; i<= TamanhoMascara; i++) {
            boleanoMascara  = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".")
                                || (Mascara.charAt(i) == "/"))
            boleanoMascara  = boleanoMascara || ((Mascara.charAt(i) == "(")
                                || (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
            if (boleanoMascara) {
                NovoValorCampo += Mascara.charAt(i);
                  TamanhoMascara++;
            }else {
                NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
                posicaoCampo++;
              }           
          }    
        campo.value = NovoValorCampo;
          return true;
    }else {
        return true;
    }
}

//Conta o numero de caracteres digitados num campo
//Util para campos de texto muito grandes.
function Contar(Campo, Limite){
var str=new String(str);
var msg='Caracteres restantes:'+(Limite-Campo.value.length);
document.getElementById("Qtd").innerText = msg;
if((Limite-Campo.value.length)<=0) {
   alert('Atenção, você atingiu o limite máximo de caracteres!');
   str=Campo.value;
			document.getElementById("Qtd").value=str.substring(0, Limite);
			return false;
}			
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
//		limitCount.value = limitNum - limitField.value.length;
		//limitCount.innerText = limitNum - limitField.value.length;
  var msg='Caracteres restantes:'+(limitNum-limitField.value.length);
  document.getElementById("Qtd").innerText = msg;
		
		
	}
}

