//---------------------------------------------------------------------------------------------------------------------------------------
// MASCARA DE CAMPO PARA QQ TIPO DE ENTRADA
//---------------------------------------------------------------------------------------------------------------------------------------

//Exemplo de chamada da função no formulário. 
//1º passo: chamar o arquivo, no caso dir_js eh o local onde vc vai colocar o bichaum!!! 
//<script src="dir_js/formata.js" type="text/javascript"></script> 
//2º passo: mandar a função no input!!!! 
//<input type="Text" name="teste1" size="17" maxlength="17" onkeydown="FormataCampo(this,event,'##/##:##-## ##:##')"> 

function FormataCampo(Campo,teclapres,mascara){ 
//pegando o tamanho do texto da caixa de texto com delay de -1 no event 
//ou seja o caractere que foi digitado não será contado. 
strtext = Campo.value 
tamtext = strtext.length 
//pegando o tamanho da mascara 
tammask = mascara.length 
//criando um array para guardar cada caractere da máscara 
arrmask = new Array(tammask) 
//jogando os caracteres para o vetor 
for (var i = 0 ; i < tammask; i++){ 
arrmask[i] = mascara.slice(i,i+1) 
} 
//alert (teclapres.keyCode) 
//começando o trabalho sujo 
if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){ 
if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){ 
Organiza_Casa(Campo,arrmask[tamtext],teclapres.keyCode,strtext) 
} 
else{ 
Detona_Event(Campo,strtext) 
} 
} 
else{//Aqui funcionaria a mascara para números mas eu ainda não implementei 
if ((arrmask[tamtext] == "A")) { 
charupper = event.valueOf() 
//charupper = charupper.toUpperCase() 
Detona_Event(Campo,strtext) 
masktext = strtext + charupper 
Campo.value = masktext 
} 
} 
} 
function Organiza_Casa(Campo,arrpos,teclapres_key,strtext){ 
if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){ 
separador = arrpos 
masktext = strtext + separador 
Campo.value = masktext 
} 
} 
function Detona_Event(Campo,strtext){ 
event.returnValue = false 
if (strtext != "") { 
Campo.value = strtext 
} 
} 

//---------------------------------------------------------------------------------------------------------------------------------------
//VALIDAÇÃO DE CGC
//---------------------------------------------------------------------------------------------------------------------------------------

function verificaCGC(scgc) { 
var cgc = trimtodigits(scgc); 
if((cgc.indexOf("-") != -1) ||(cgc.indexOf(".") != -1) ||(cgc.indexOf("/") != -1)){ 
return( false ) 
} 
var df, resto, dac = "" 
df = 5*cgc.charAt(0)+4*cgc.charAt(1)+3*cgc.charAt(2)+2*cgc.charAt(3)+9*cgc.charAt(4)+8*cgc.charAt(5)+7*cgc.charAt(6)+6*cgc.charAt(7)+5*cgc.charAt(8)+4*cgc.charAt(9)+3*cgc.charAt(10)+2*cgc.charAt(11) 
resto = df % 11 
dac +=((resto <= 1) ? 0 :(11-resto) ) 
df = 6*cgc.charAt(0)+5*cgc.charAt(1)+4*cgc.charAt(2)+3*cgc.charAt(3)+2*cgc.charAt(4)+9*cgc.charAt(5)+8*cgc.charAt(6)+7*cgc.charAt(7)+6*cgc.charAt(8)+5*cgc.charAt(9)+4*cgc.charAt(10)+3*cgc.charAt(11)+2*parseInt(dac) 
resto = df % 11 
dac +=((resto <= 1) ? 0 :(11-resto) ) 
return(dac == cgc.substring(cgc.length-2,cgc.length)) 
} 

//Remove todos os caracteres excetos 0-9 
function trimtodigits(tstring){ 
s=""; 
ts=new String(tstring); 
for(x=0;x<ts.length;x++){ 
ch=ts.charAt(x); 
if(asc(ch)>=48 && asc(ch)<=57){ 
s=s+ch; 
} 
} 
return s; 
} 


// Retorna o código ASC do caracter passada por parâmetro 
function asc(achar){ 
var n=0; 
var ascstr = makeCharsetString() 
for(i=0;i<ascstr.length;i++){ 
if(achar==ascstr.substring(i,i+1)){ 
n=i; 
break; 
} 
} 
return n+32 
} 

// Gera uma string com os caracteres básicos na sequência de códigos ASC 
function makeCharsetString(){ 
var astr 
astr = ' !"#$%&\'()*+,-./0123456789:;<=>?@' 
astr+= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
astr+= '[\]^_`abcdefghijklmnopqrstuvwxyz' 
astr+= '{|}~' 
return astr 
} 

//---------------------------------------------------------------------------------------------------------------------------------------
// MÁSCARA PARA DATAS
//---------------------------------------------------------------------------------------------------------------------------------------

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

//Instrução de chamada no <input>:
//onkeypress="FormataData('Campo',event)"


//---------------------------------------------------------------------------------------------------------------------------------------
//MÁSCARA PARA FORMATCAO DE CPG
//---------------------------------------------------------------------------------------------------------------------------------------

function FormataCPF(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres){
var wTecla, wVr, wTam;

// alert(pForm[pCampo].value);

wTecla = pTeclaPres.keyCode;
wVr = pForm[pCampo].value;
wVr = wVr.toString().replace( "-", "" );
wVr = wVr.toString().replace( ".", "" );
wVr = wVr.toString().replace( ".", "" );
wVr = wVr.toString().replace( "/", "" );
wTam = wVr.length ;

if(wTam < pTamMax && wTecla != 8) { 
wTam = wVr.length + 1 ; 
}

if(wTecla == 8 ) { 
wTam = wTam - 1 ; 
}

if( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 ){
if( wTam <= 2 ){
pForm[pCampo].value = wVr ;
}
if(wTam > pPosTraco && wTam <= pTamMax) {
wVr = wVr.substr(0, wTam - pPosTraco) + '-' + wVr.substr(wTam - pPosTraco, wTam);
}
if( wTam == pTamMax){
wVr = wVr.substr( 0, wTam - pPos1 ) + '.' + wVr.substr(wTam - pPos1, 3) + '.' + wVr.substr(wTam - pPos2, wTam);
}
pForm[pCampo].value = wVr;

}

}


//---------------------------------------------------------------------------------------------------------------------------------------
// QQ TIPO DE MASCARA
//---------------------------------------------------------------------------------------------------------------------------------------
//Para usar é bem simples carrege esse arquivo em seu html e no onload do body execute 
//Mascaras.carregar();
//<body onload="Mascaras.carregar();">
//
//pontro o codigo vai percorrer todoseu html procurando as marcacoes abaixo em seus inputs e aplicando a mascara
//
//insira os seguintes atributos nos seus input 
//
//tipo = pode ser numerico ou decimal
//mascara = é a mascara a ser usada coloque # nas posições dos caracteres ex : "##:##"
//casasdecimais = para o caso do tiposer decimal aqui eh dito quantas casas decimais vaum ser usadas 
//negativo = isso define um sinal de negativo no inicio do valor 
//
//pronto é so isso 
//exemplos:
//<input type="text" tipo="numerico"> aqui so da para digitar numeros
//<input type="text" tipo="numerico" negativo=true> aqui so da para digitar numeros e no caso de precionar "-" umsinal de negativo vai aparecer
//<input type="text" tipo="decimal" negativo=true casasdecimais=3>
//<input type="text" tipo="numerico" mascara="##/##/####"> data
//<input type="text" tipo="numerico" mascara="###.###.###-##"> cpf


Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50)
   tamanho = 10;
  if (!casasdecimais)
   casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; return true;
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
aplicarMascara: function(campo, valor){
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
}
}

//---------------------------------------------------------------------------------------------------------------------------------------
// VERIFICAÇÃO DE CPF
//---------------------------------------------------------------------------------------------------------------------------------------
function isNum(str)
{
var VBlnIsNum;
VIntTam = str.length;
VBlnIsNum = true;
if (VIntTam == 0)
{
return false;
}
else
{
for (i=0; i < VIntTam; i++)
{
if (str.substring(i,i+1) < '0' || str.substring(i,i+1) >
'9')
{
VBlnIsNum = false;
}
}
return VBlnIsNum;
}
}

//Função de validação de CPF
function isCPF(st) {
if (st == "")
return (false);
l = st.length;

//aleterado para se usuário não digitar os zeros na frente do CPF, completar sozinho
if ((l == 9) || (l == 8))
{
for (i = l ; i < 10; i++)
{
st = '0' + st
}
}
l = st.length;
st2 = "";
for (i = 0; i < l; i++) {
caracter = st.substring(i,i+1);
if ((caracter >= '0') && (caracter <= '9'));
st2 = st2 + caracter;
}
if ((st2.length > 11) || (st2.length < 10))
return (false);
if (st2.length==10)
st2 = '0' + st2;
digito1 = st2.substring(9,10);
digito2 = st2.substring(10,11);
digito1 = parseInt(digito1,10);
digito2 = parseInt(digito2,10);
sum = 0; mul = 10;
for (i = 0; i < 9 ; i++) {
digit = st2.substring(i,i+1);
tproduct = parseInt(digit ,10) * mul;
sum += tproduct;
mul--;
}
dig1 = ( sum % 11 );
if ( dig1==0 || dig1==1 )
dig1=0;
else
dig1 = 11 - dig1;
if (dig1!=digito1)
return (false);
sum = 0;
mul = 11;
for (i = 0; i < 10 ; i++) {
digit = st2.substring(i,i+1);
tproduct = parseInt(digit ,10)*mul;
sum += tproduct;
mul--;
}
dig2 = (sum % 11);
if ( dig2==0 || dig2==1 )
dig2=0;
else
dig2 = 11 - dig2;
if (dig2 != digito2)
return (false);
return (true);
}

