// JavaScript Document
 
//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;
    }    
    return formataCampo(tel, '(00) 0000-0000', event);
}
 
//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 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)){
        alert('E-mail Invalido!');
	} else {
        alert('E-mail Valido!');
	}
}

function validaURL(url){

    var exp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(!exp.test(url)){
		 alert('URL Invalida!');
        return true;
    }else{
		alert('URL Valida!');
        return false;
    }

	
	
	}
 
//valida o CPF digitado
function validaCPF(cpf){
			 exp = /\.|\-/g
   			 cpf = cpf.toString().replace( exp, "" );

              erro = new String;
                if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
                var nonNumbers = /\D/;
                if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
                if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                         erro += "Numero de CPF invalido!"
						 
               }
               var a = [];
               var b = new Number;
               var c = 11;
               for (i=0; i<11; i++){
                       a[i] = cpf.charAt(i);
                       if (i < 9) b += (a[i] * --c);
               }
               if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
               b = 0;
               c = 11;
               for (y=0; y<10; y++) b += (a[y] * c--);
               if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
               if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                       erro +="Digito verificador com problema!";
               }
               if (erro.length > 0){

				//aqui vai a mensagem de erro
				$("#erro_cpf").html(" <img src='icones/error_delete.png' width='16' height='16'  style='vertical-align:bottom'/> "+erro).fadeIn(300);
				//aqui asigna a classe do erro
				$("#cpf").addClass("error_class");
 
 						//alert(erro);
                       return false;
               } else {
				   
				   
				  $.post("comprova_cpf.php", { num_cpf: cpf },
 				  	function(data){
    					//alert("Este Numero de CPF " + data);
						if(data.length < 1) {

$("#erro_cpf").html(" <img src='icones/tick.png' width='16' height='16'  style='vertical-align:bottom'/>").fadeIn(300);
		$("#cpf").removeClass("error_class"); 
		
		} else {

$("#erro_cpf").html(" <img src='icones/error_delete.png' width='16' height='16'  style='vertical-align:bottom'/> O numero de CPF ja se encontra cadastrado!!!").fadeIn(300);
				//aqui asigna a classe do erro
				$("#cpf").addClass("error_class");
 
			}

				    });
				   
				   
		$("#erro_cpf").html(" <img src='icones/tick.png' width='16' height='16'  style='vertical-align:bottom'/>").fadeIn(300);
		$("#cpf").removeClass("error_class");

				   
				  // alert("Numero de CPF Valido!");
                   return true;
			   }
			   
}
 //valida o CNPJ digitado
 function validaCNPJ(CNPJ) {
                 //CNPJ = document.validacao.CNPJID.value;
				// exp = /\.|\-/g
	   			// CNPJ = CNPJ.toString().replace( exp, "" );
				 
                 erro = new String;
                 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
                 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
                 if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
                 }
                 //substituir os caracteres que não são números
               if(document.layers && parseInt(navigator.appVersion) == 4){
                       x = CNPJ.substring(0,2);
                       x += CNPJ. substring (3,6);
                       x += CNPJ. substring (7,10);
                       x += CNPJ. substring (11,15);
                       x += CNPJ. substring (16,18);
                       CNPJ = x;
               } else {
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace (".","");
                       CNPJ = CNPJ. replace ("-","");
                       CNPJ = CNPJ. replace ("/","");
               }
               var nonNumbers = /\D/;
               if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
               var a = [];
               var b = new Number;
               var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
               for (i=0; i<12; i++){
                       a[i] = CNPJ.charAt(i);
                       b += a[i] * c[i+1];
 }
               if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
               b = 0;
               for (y=0; y<13; y++) {
                       b += (a[y] * c[y]);
               }
               if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
               if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
                       erro +="Dígito verificador com problema!";
               }
               if (erro.length > 0){
 
				//aqui vai a mensagem de erro
				$("#erro_cnpj").html(" <img src='icones/error_delete.png' width='16' height='16'  style='vertical-align:bottom'/> "+erro).fadeIn(300);
				//aqui asigna a classe do erro
				$("#cnpj").addClass("error_class");
 
 					// alert(erro);
                       return false;
               } else {
				   
	$("#erro_cnpj").html(" <img src='icones/tick.png' width='16' height='16'  style='vertical-align:bottom'/>").fadeIn(300);
	$("#cnpj").removeClass("error_class");

                      // alert("CNPJ valido!");
               }
               return true;
       }
	   


//valida data
function validaDATA(obj){
	
	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(obj!='')
        {

        if(!exp.test(obj))
        {
        //alert('Data Inválida!');
		//aqui vai a mensagem de erro
		$("#erro_data").html(" <img src='icones/error_delete.png' width='16' height='16'  style='vertical-align:bottom'/> Data Inválida!").fadeIn(300);
		//aqui asigna a classe do erro
		$("#data").addClass("error_class");

        }else {
			
		$("#erro_data").html(" <img src='icones/tick.png' width='16' height='16'  style='vertical-align:bottom'/>").fadeIn(300);
		$("#data").removeClass("error_class");

		//alert('Data Valida!');
		}
	} else {
 		//aqui vai a mensagem de erro
		$("#erro_data").html(" <img src='icones/error_delete.png' width='16' height='16'  style='vertical-align:bottom'/> Data Vazía!").fadeIn(300);
		//aqui asigna a classe do erro
		$("#data").addClass("error_class");
	}
   
	
}

function primeiraLetraMaiuscula(str) {
	str1 = str.substring(0,1);
	return  str.replace(str1, str1.toUpperCase());
}


 
//valida numero inteiro com mascara
function mascaraInteiro(){
    if (event.keyCode < 48 || event.keyCode > 57){
        event.returnValue = false;
        return false;
    }
    return true;
}
 
 
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;
    }
}