﻿var MSIE = (document.all);
var NSN4 = (document.layers);


function capturaTecla(e) {
    if (MSIE) {

        if (e != null) {
            tecla = event.keyCode; //captura o ASC da tecla pressionada	
        } else {
            tecla = 7;
        }

    } else {
        document.captureEvents(Event.KEYPRESS | Event.KEYUP);
        tecla = e.which;
    }
    return tecla;
}

/*inicio funções gerais*/

function LimpaFormato(campo) {
    // pode passar o campo como parametro ou o valor
    if (campo == "") {
        return "";
    }



    if (isNaN(campo)) { // se for campo
        vr = document.aspnetForm[campo].value;
    } else { // se for o valor
        vr = campo;
        vr = vr.toString();
    }

    valor = "";

    for (pos = 0; pos < vr.length; pos++) {
        sinalmenos = vr.charAt(pos) != '-';
        sinalponto = vr.charAt(pos) != '.';
        sinalvirgula = vr.charAt(pos) != ',';
        sinalbarra = vr.charAt(pos) != '/';

        if ((sinalmenos) && (sinalponto) && (sinalvirgula) && (sinalbarra)) {
            valor = valor + vr.charAt(pos);
        }
    }
    return valor;
}



//---------------------------------------------------------------------
// Verifica se a string digitada é numerica
//---------------------------------------------------------------------	

function Verifica_se_Numero(campo) {
    /*
    Verifica se os dados digitados é numerico
    finalidade : Verificar se o valor do campo é numerico testar sempre ao sair de um campo do tipo numerico
    evitando assim que o usuario copie e cole valores indevidos.
    Obs se vc usa no evento onBlur alguma funcao do tipo Validar_cpf, Validar_Cnpj não é necessário 
    fazer uso desta funcao pois a mesma ja está inclusa.
    Modo de Usar :  TextBox.Attributes.Add("onBlur", "Verifica_se_Numero(this.name)")
    */

    var valor = LimpaFormato(campo);

    if (valor != "") {
        if (isNaN(valor)) {
            window.alert("O valor digitado nao e valido, verifique sua digitacao");
            document.aspnetForm[campo].focus();
            document.aspnetForm[campo].select();
            return false;
        }
    }

    return valor;
} //func
      


//---------------------------------------------------------------------
// Permite apenas as teclas numéricas
//---------------------------------------------------------------------

function VerificaTecla(campo, evento) {
    tecla = capturaTecla(evento);
    if (tecla == 0) { // retorna 0 se a tecla for especia com setinhas por exemplo
        return 0;
    }
    //esta condicao permite ele digitar apenas um sinal -
    // para se permitir valor negativo em um campo, é necessário que seu 
    //id | nome possua a flasg _neg. o JS identifica esse campo e permite o sinal de - como sendo 
    //o primeiro caractere
    if ((campo.indexOf("_neg") != -1) && document.aspnetForm[campo].value.length == 0) { // encontrar string neg no nome do campo , habilita num negativos
        condicao = ((tecla > 47 && tecla < 58) || tecla == 45 || tecla == 0); ////número de 0 à 9 ou sinal de -
    } else {
        condicao = (tecla > 47 && tecla < 58 || tecla == 0); //número de 0 à 9
    }

    if (condicao)
        return 1;
    else

        if ((tecla != 8) && (tecla != 17) && (tecla != 16))//teclas de combinação
    {
        if (MSIE) {
            if (evento != null) {
                evento.keyCode = 0;
            }

        } else {
            evento.preventDefault(); // cancela digitação netscape
        }
        return 0;
    }
    else
        return 1;
}				

/*fim funções gerais*/

/*inicio funcões cpf e cnpj*/

//---------------------------------------------------------------------
// Formata cpf durante a digitacao
//---------------------------------------------------------------------	
function FormataCpf(campo, evento) {
    /*Modo de usar:  TxtBox1.Attributes.Add("onKeyPress", "javascript:FormataCpf(this.name,event);")
    TxtBox1.Attributes.Add("onBlur", "javascript:FormataCpf(this.name,event);valida_cpf(this.name);") */
    var tammax = 11;

    
    var Numero = VerificaTecla(campo, evento);
    if (Numero == 0) {
        return false;
    }
    
    vr = Verifica_se_Numero(campo); // ja tem o limpaformato
    if (!vr) { return false; }
    var tam = vr.length;
    if (tam >= tammax) {
        if (Numero == 0)// esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
        {				//caracteres maior que o tamanho maximo (tammax)
            vr = vr.slice(0, tammax);
            tam = vr.length;
        }
        else {
            return false;
        }
    }
    tam = vr.length + Numero;

    if (tam <= 2) {
        document.aspnetForm[campo].value = vr;
    }
    if ((tam > 2) && (tam <= 5)) {
        document.aspnetForm[campo].value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 6) && (tam <= 8)) {
        document.aspnetForm[campo].value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 9) && (tam <= 11)) {
        document.aspnetForm[campo].value = vr.substr(0, tam - 8) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 12) && (tam <= 14)) {
        document.aspnetForm[campo].value = vr.substr(0, tam - 11) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    }
    if ((tam >= 15) && (tam <= 17)) {
        document.aspnetForm[campo].value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    }

}
//---------------------------------------------------------------------
// VALIDAR NÚMERO DE "CPF"
//---------------------------------------------------------------------	
function valida_cpf(campo, evento) {
    // esta opção deve ser chamado juntamente com o formata_cpf ver exeplo no formata_cpf

    var Numero = VerificaTecla(campo, evento);
    vr = Verifica_se_Numero(campo); // ja tem o limpaformato
    if (!vr) { return false; }

    cpf = vr;
    Retorno = 1;
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
        Retorno = 0;
    for (i = 0; i < cpf.length - 1; i++)
        if (cpf.charAt(i) != cpf.charAt(i + 1)) {
        digitos_iguais = 0;
        break;
    }
    if (!digitos_iguais) {
        numeros = cpf.substring(0, 9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--)
            soma += numeros.charAt(10 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
            Retorno = 0;
        numeros = cpf.substring(0, 10);
        soma = 0;
        for (i = 11; i > 1; i--)
            soma += numeros.charAt(11 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
            Retorno = 0;
    }
    else
        Retorno = 0;
    if (Retorno == 0) {
        if (document.aspnetForm[campo].value != "") {
            window.alert("CPF Incorreto !");
            document.aspnetForm[campo].focus();
            return false;
        }

    }
} 

//---------------------------------------------------------------------
// Formata cpnj durante a digitacao
//---------------------------------------------------------------------	
function FormataCnpj(campo,evento) 
{	/*Modo de usar:  TxtBox1.Attributes.Add("onKeyPress", "javascript:FormataCnpj(this.name);")
					 TxtBox1.Attributes.Add("onBlur", "javascript:FormataCnpj(this.name);valida_cnpj(this.name);") */
	var tammax = 14  ;
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	var tam = vr.length;
	if (tam >= tammax)
	{ 
		if (Numero == 0)// esta formatação so vai ocorrer caso o usuariio colar no campo a quantidade de 
		{				//caracteres maior que o tamanho maximo (tammax)
			vr = vr.slice(0, tammax);
			tam = vr.length;
		}
		else
		{
			return false;
		}
	} 
	tam = vr.length + Numero;		
	
	if ( tam <= 2 ){ 
		document.aspnetForm[campo].value = vr ; }
	if ( (tam > 2) && (tam <= 6) ){
		document.aspnetForm[campo].value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 7) && (tam <= 9) ){
		document.aspnetForm[campo].value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 10) && (tam <= 12) ){
		document.aspnetForm[campo].value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 13) && (tam <= 14) ){
		document.aspnetForm[campo].value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	if ( (tam >= 15) && (tam <= 17) ){
		document.aspnetForm[campo].value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
			
}				

//---------------------------------------------------------------------
// FUNÇÃO PARA VALIDAR NÚMERO DE "CNPJ"
//---------------------------------------------------------------------	

function valida_cnpj(campo,evento) 
{ 	/*esta funcao deve ser chamado junto com o formata_cnpj ver exemplo na funcao formata_cnpj */
	
	var Numero = VerificaTecla(campo,evento);
	vr=Verifica_se_Numero(campo); // ja tem o limpaformato
	if (!vr) {return false;}
	
	cnpj = vr
	
	retorno=1;
   
     var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais; 
     digitos_iguais = 1; 
      if (cnpj.length < 14 ){retorno=0;}
     
     for (i = 0; i < cnpj.length - 1; i++)
     { 
           if (cnpj.charAt(i) != cnpj.charAt(i + 1)) 
           { 
                digitos_iguais = 0; 
                break; 
           } 
     }
      
      if (!digitos_iguais) 
       { 

            tamanho = cnpj.length - 2 
            numeros = cnpj.substring(0,tamanho); 
            digitos = cnpj.substring(tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(0))
            { 
                  retorno=0;//return false; 
            }
            tamanho = tamanho + 1; 
            numeros = cnpj.substring(0,tamanho); 
            soma = 0; 
            pos = tamanho - 7; 
            for (i = tamanho; i >= 1; i--) 
                  { 
                  soma += numeros.charAt(tamanho - i) * pos--; 
                  if (pos < 2) 
                        pos = 9; 
                  } 
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11; 
            if (resultado != digitos.charAt(1)) 
            {
                  retorno=0;
             }

       } 
      else {
			retorno=0;
            //return false; 
      } 
      
      if(retorno==0)
      {
		window.alert("CNPJ Incorreto !")
		document.aspnetForm[campo].focus();
		return 0;
      }
      
 }//function

function Valida_Cpf_Cnpj(campo,evento) {
 	valorcampo=document.aspnetForm[campo].value; 			
 	valorcampo=LimpaFormato(campo);
 	if(valorcampo.length<=11){	
 		valida_cpf(campo,evento); 		
 	}else{	
 		valida_cnpj(campo,evento); 		
 	} 
 	
 	
 }	   
 
 function Formata_Cpf_Cnpj(campo,evento) { 
 	valorcampo=document.aspnetForm[campo].value; 	
 	if(valorcampo.length<=14){	
 		FormataCpf(campo,evento);
 		titulo="Consulta por CPF";
 	}else{	
 		FormataCnpj(campo,evento);
 		titulo="Consulta por CNPJ";
 	} 
 	document.aspnetForm[campo].title= titulo;
 }

/*fim funções cpf e cnpj*/

function fncSoNumeros()
{
        //Pega o Codigo ascii da tecla digitada
    var tecla = event.keyCode;     

    if ((tecla > 47 && tecla < 58) || tecla ==13)     
    {event.returnValue = true;}
    else
    {event.returnValue= false;}
}

function MaxLength(textAreaField, limit)
{
    var ta = document.getElementById(textAreaField);
    
    if (ta.value.length >= limit)
    {
        ta.value = ta.value.substring(0, limit-1);
    }
}




