// JavaScript Document
// limita textbox

function limitatexto(campo, camporestam, botao, limite){
	
if (campo.value.length  > limite){ //alert("Limite de 326 caracteres"); 
campo.value = campo.value.substring(0,limite); }

var conta = limite - campo.value.length  ;
document.getElementById(camporestam).innerHTML = "Restam: " + conta + " caracteres";

}

//------------------------------------------------------
// ex onblur = "javascript: testacnpj(this.value, this);" essa funcao interage com a funcao ValidaCNPJ()

function testacnpj(cnpj, campo) {
var teste = ValidaCNPJ(cnpj);
if (teste == "invalido") {
	alert("O CNPJ informado não é válido");
	campo.value="";
	campo.focus();} 
 else if (teste == "qtd"){
	alert("O CNPJ deve possuir 14 números");
	campo.value="";
	campo.focus();} 

}
//---------------------------------------

// ex: funcao de teste retorna "vazio" se tiver vazaio, "qtd" se nao tiver 14 caracteres , "invalido" se tiver incorreto e true se tiver certo usa-se var teste = ValidaCNPJ(cnpj);

function ValidaCNPJ(cnpj) { 
var i = 0;
var l = 0; 
var strNum = "";  
var strMul = "6543298765432"; 
var character = ""; 
var iValido = 1;  
var iSoma = 0;  
var strNum_base = "";  
var iLenNum_base = 0;  
var iLenMul = 0;  
var iSoma = 0;  
var strNum_base = 0;  
var iLenNum_base = 0;  
if (cnpj == "")        
return ("vazio");  
l = cnpj.length;  
for (i = 0; i < l; i++) {       
caracter = cnpj.substring(i,i+1)        
if ((caracter >= '0') && (caracter <= '9'))         
strNum = strNum + caracter;  };  
if(strNum.length != 14)      
return ("qtd"); 
strNum_base = strNum.substring(0,12);  
iLenNum_base = strNum_base.length - 1;  
iLenMul = strMul.length - 1; 
for(i = 0;i < 12; i++)       
iSoma = iSoma + parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) * parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10); 
iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11); 
if(iSoma == 11 || iSoma == 10)       
iSoma = 0;  
strNum_base = strNum_base + iSoma;  
iSoma = 0; 
iLenNum_base = strNum_base.length - 1  
for(i = 0; i < 13; i++)        
iSoma = iSoma +  parseInt(strNum_base.substring((iLenNum_base-i),(iLenNum_base-i)+1),10) * parseInt(strMul.substring((iLenMul-i),(iLenMul-i)+1),10)  
iSoma = 11 - (iSoma - Math.floor(iSoma/11) * 11);  
if(iSoma == 11 || iSoma == 10)        
iSoma = 0;  strNum_base = strNum_base + iSoma;  
if(strNum != strNum_base)        
return ("invalido");  
return (true);}

//-------------------------


function valida_cpf(cpf)
      {
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11)
            return false;
      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))
                  return false;
            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))
                  return false;
            return true;
            }
      else
            return false;
      }
//--------------------------------

function testacpf(cpf, campo) {
if (cpf != "") {
cpf =  limpacpf(cpf);

if (cpf.length == 11 ) {var teste = valida_cpf(cpf);} 
 else {var teste = "qtd"}

if (teste == false) {
	alert("O CPF informado não é válido");
	campo.value="";
	campo.focus();} 
 else if (teste == "qtd"){
	alert("O CPF deve possuir 11 números");
	campo.value="";
	campo.focus();} 

}}
//--------------------------------

//ex : onblur="javascript: consultadados(this.value, 'cnpj', this, 'consultadados.php', 'O CNJP', 'Já está cadastrado.');" a segunda string 'cnpj' é o campo do mysql

function consultadados(tabela, dado, nome, campo, paginadeconsulta, mensagema, mensagemb){
if (dado != "") {
$.post("" + paginadeconsulta + "", { info: dado, tipo: nome, tabela: tabela },
  function(data){
   if (data == "sim" ) {
	alert( mensagema + " " + dado + " " + mensagemb);
	campo.value = "";
	campo.focus();
  } //else { var teste = ValidaCNPJ(dado);
   //if( teste == "invalido") { alert(); }}
  },"text");}

}
//------------------------------------

// ex: onkeypress="javascript: return formatar_mascara(this, event, '##.###.###/####-##')" ou onkeypress="javascript: return formatar_mascara(this, event, '##-####-####')"

function formatar_mascara(src, evt, mascara) {
	        var key_code = evt.keyCode  ? evt.keyCode  :
                       evt.charCode ? evt.charCode :
                       evt.which    ? evt.which    : void 0;
 if (key_code == 8  ||  key_code == 9  ||  key_code == 13  ||  key_code == 27 )// ||  key_code == 46 ||  key_code == 45 ||  key_code == 47)
        {return true}
        // Habilita teclas <HOME>, <END>, mais as quatros setas de navegação (cima, baixo, direta, esquerda)
        else if ((key_code >= 35)  &&  (key_code <= 40))
        { return true}
        // Habilita números de 0 a 9
        else if ((key_code >= 48)  &&  (key_code <= 57))
        { 	var campo = src.value.length;
	        var saida = mascara.substring(0,1);
	        var texto = mascara.substring(campo);
	       if(texto.substring(0,1) != saida) {
	        	src.value += texto.substring(0,1);}
	        	return true}
return false
}
//---------------------------------------------

// ex: onkeypress = "javascript: return numbers(event);"   so numeros sem formatacao
function numbers(evt)
    {
        var key_code = evt.keyCode  ? evt.keyCode  :
                       evt.charCode ? evt.charCode :
                       evt.which    ? evt.which    : void 0;
      // Habilita teclas <DEL>, <TAB>, <ENTER>, <ESC> e <BACKSPACE>
       //alert(key_code);
	    if (key_code == 8  ||  key_code == 9  ||  key_code == 13  ||  key_code == 27  )
        {
            return true;
        }

        // Habilita teclas <HOME>, <END>, mais as quatros setas de navegação (cima, baixo, direta, esquerda)
        else if ((key_code >= 35)  &&  (key_code <= 40))
        {
            return true
        }

        // Habilita números de 0 a 9
        else if ((key_code >= 48)  &&  (key_code <= 57))
        {
            return true
        }

        return false;
    }
//-----------------------------------------------

// ex: onkeypress="javascript: return soletras(this.value,event);" so letras 
function soletras(placa,evt){   
var tecla = evt.keyCode  ? evt.keyCode  :
                       evt.charCode ? evt.charCode :
                       evt.which    ? evt.which    : void 0;
     if (tecla == 8  || tecla == 9  ||  tecla == 13  ||  tecla == 27 )
        { return true; } //else { return false} 

var alfabeto = "ABCDEFGHIJKLMNOPQRSTUVWXYZÇÁÀÂÃÉÊÚÓÔÕ ";

var placa = String.fromCharCode(tecla); 
for (letrapos =1 ;letrapos <= alfabeto.length;letrapos++){
var alf = alfabeto.substring(letrapos-1,letrapos);
 if( placa.toUpperCase() == alf){
 var result= "ok";
 break; } else { result= "erro";
 } 
 }if (result== "erro"){return false}
 
 }
 //------------------------------------------------
 
//  ex: onblur="validaEmail(this.value, this);" testa se tem formato de email  dddd@fdff.com
 function validaEmail(email, campo) {
emailRE = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");
  var email = email;//document.getElementById("email").value
 if (email != "" ) {
  if (emailRE.test(email) ){
 //    alert("ok");
  //  var formulario = document.getElementById("formulario");
  //  formulario.action = "processa.php";
  //  formulario.submit();
  } else {
  alert("Email inválido");
campo.value = "";
campo.focus(); 
return false
}}}
//-------------------------------------------------

// ex: onblur="validaurl(this.value, this);" testa se tem formato de url 
  
function validaurl(url, campo){
    var RegExp = /^(([\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 (url != "") {
    if(RegExp.test(url)){
        
    }else{
        alert("URL Inválida");
         campo.value = "";
         campo.focus(); 
		 }  
}}
//-----------------------------------------------------

//ex: onchange="javascript: return comprova_extensao(this.form, this.value, this.id)" testa a extenção do arquivo selecionado e limpa se tiver errado

function comprova_extensao(formulario, arquivo, campo) { 
   extensoes_permitidas = new Array(".jpg"); 
   meuerro = ""; 
   if (!arquivo) { 
      //Se não tenho arquivo, é porque não se selecionou um arquivo no formulário. 
       meuerro = "Não foi selecionado nenhum arquivo"; 
   }else{ 
      //recupero a extensão deste nome de arquivo 
      extensao = (arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase(); 
      //alert (extensao); 
      //comprovo se a extensão está entre as permitidas 
      permitida = false; 
      for (var i = 0; i < extensoes_permitidas.length; i++) { 
         if (extensoes_permitidas[i] == extensao) { 
         permitida = true; 
         break; 
         } 
      } 
      if (!permitida) { 
         meuerro = "\nSó se podem subir arquivos com extensões: " + extensoes_permitidas.join(); 
	   }else{ 
		return 1; 

       } 
   } 
   //se estou aqui é porque não se pode submeter 
    alert (meuerro); 
var oCampo = document.getElementById(campo);var oNovoCampo = oCampo.cloneNode( true );oCampo.parentNode.replaceChild( oNovoCampo, oCampo );
   return 0; 
} 
//----------------------------------------------------------

// ex: onkeypress="javascript: return testaplaca(this.value,event);" permite que um campo para placa de viculo entre so o padrao LLL0000.

function testaplaca(placa,evt){   
var tecla = evt.keyCode  ? evt.keyCode  :
                       evt.charCode ? evt.charCode :
                       evt.which    ? evt.which    : void 0;
//if (placa.length == 3) {       
     if (tecla == 8  || tecla == 9  ||  tecla == 13  ||  tecla == 27 )
        { return true; } //else { return false} 
if (placa.length >= 3) { if ((tecla >= 48)  &&  (tecla <= 57)){return true} else {return false  }	}
	//	} else {
//var tecla = (window.addEventListener) ? event.which : event.keyCode;
  //;    if ((tecla >= 48)  &&  (tecla <= 57)){return false}

var alfabeto = "ABCDEFGHIJKLMNOPQRTUVWXYZ";

var placa = String.fromCharCode(tecla); 
for (letrapos =1 ;letrapos <= alfabeto.length;letrapos++){
var alf = alfabeto.substring(letrapos-1,letrapos);
 if(placa.toUpperCase() == alf){
 var result= "ok";
 break; } else { result= "erro";
 } 
 }if (result== "erro"){return false}
 
 }
 //-----------------------------------------------------------------
// ex: limpcpf(cpf.value)
function limpacpf(v)
{
v= v.replace(".","");
v= v.replace(".","");
v= v.replace(".","");
v= v.replace("-","");
/*
var p = "";
var sp = v.split(/([.-])/);
var t = sp.length;
  for (i=0; i < t; i++)
    {
    p += sp[i];
    }
*/
var p = v;
return (p);
}

//------------------------------------------------------
// primeira letra maiuscula
function primeiraLetraMaiuscula(str, campo)  {
	//str = "testando a primeira letra em maiúsculo";
	str1 = str.substring(0,1);
	str = str.replace(str1, str1.toUpperCase());
         campo.value = str;

}
//--------------------------------------------------------
function trim(str) { 
return str.replace(/^\s+|\s+$/g,""); 
} 
//-------------------------------------------------------
function voltavalor(campo, texto) {

if (campo.value	== "") { campo.value = texto;} 
 	
}

//-------------------------------------------------------
// codificador e decodificador
//ex v = Base64.encode(texto) , final = Base64.decode(v)


Base64 = {  
charset: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',       
charset_urlsafe: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',              
//--
encode: function(data, urlsafe) {                
var charset = urlsafe ? Base64.charset_urlsafe : Base64.charset;
var i = 0; 
var len = data.length; 
var output = '';     
var c1, c2, c3;      
var e1, e2, e3, e4;        
while (i < len) {         
c1 = data.charCodeAt(i++);        
c2 = data.charCodeAt(i++);                
c3 = data.charCodeAt(i++);                              
e1 = c1 >> 2;                     
e2 = ((c1 & 0x3) << 4) | (c2 >> 4);    
e3 = ((c2 & 0xf) << 2) | (c3 >> 6);      
e4 = c3 & 0x3f;      
if (isNaN(c2)) {     
e3 = e4 = 64;      
} else if (isNaN(c3)) {       
e4 = 64;                 
}                                   
output += charset.charAt(e1);       
output += charset.charAt(e2);        
output += charset.charAt(e3);         
output += charset.charAt(e4);     
}                        
return output;     
},           
//--
decode: function(data, urlsafe) { 
var charset = urlsafe ? Base64.charset_urlsafe : Base64.charset;  
var i = 0;        
var len = data.length;     
var output = '';      
var e1, e2, e3, e4;      
var c1, c2, c3;       
while (i < len) {     
e1 = charset.indexOf(data.charAt(i++));
e2 = charset.indexOf(data.charAt(i++));    
e3 = charset.indexOf(data.charAt(i++));     
e4 = charset.indexOf(data.charAt(i++));                
c1 = (e1 << 2) | (e2 >> 4);              
c2 = ((e2 & 0xf) << 4) | (e3 >> 2);      
c3 = ((e3 & 0x3) << 6) | e4;         
output += String.fromCharCode(c1);       
if (e3 != 64) output += String.fromCharCode(c2);
if (e4 != 64) output += String.fromCharCode(c3);  
}                  
return output;    
}


};
 
