// JavaScript Document
/*
* @Validador Universal
* @copyleft (cc) 2008 UNIFACS - Desenvolvimento Web Sites - Turma 04. Alguns direitos reservados
* @licence http://www.gnu.org/licence/lgpl.html LGPL Licence
* @author Lucas Figueiredo - lukas.figueiredo@hotmail.com
* @author Gustavo Ramalho - gustavo@xisweb.com.br
* @author Elton Augusto - elton18augusto@hotmail.com
* @author Anderson Andrade - andrades23@gmail.com


CARACTERISTICAS DO VALIDADOR

* bloqeia digito de caracteres pré-definidos, nos campos numericos como CEP ipedi o digito de letras e em campos especifico de texto
como nome bloueia o digito de números
* valida cep de acordo com o estado
* valida CPF
* valida Data
* valida senha com restrição minima de 3 caracteres
* auto completar nos campos: CEP,CPF,RG,Data
* valida campo radio, checkbox no sbmit do formulário


// JavaScript Document
*/


//função que é chamda no onfocus e retorna mensagem na div correspondente ao campo
function mudacor(ref,cor){
	ref.style.backgroundColor=cor;
}

//função que restringe caracteres digitados. Números ou letras
function valida_digitos(Ncampo)
{
		 //caracteres permitidos
		 if(Ncampo=="nome")
		 er=/[0-9]/;
		 if(Ncampo=="cep" || Ncampo=="cpf" || Ncampo=="rg")
		 er=/[a-z]/;		 
		 digito=document.getElementById(Ncampo).value;
		 var tempor;
		 
		  for (var i=0;i<digito.length; i++) {
			tempor = digito.substring(i,i+1); 
			//se digitos não igual aos caracteres informado na variavel digitos, então é deletado
			  if (er.test(digito)) {
			  document.getElementById(Ncampo).value=digito.substring(0,digito.length-1);
			 
			 return false;
			  break;
    		}
   		}
 }






//função que retorna o erro na div correspondente ao campo, uando a vlaidação falha
function erro(Ncampo)
{
	//if(Ncampo=="nome")
	//resposta="nome deve ter no minimo 3 caracteres";
	if(Ncampo=="cpf")
	resposta="Número de CPF inválido";
	if(Ncampo=="cep")
	resposta="Número de CEP inválido";
	if(Ncampo=="email")
	resposta="E-mail Inválido";

	
	/*document.getElementById('resposta'+Ncampo).innerHTML="nome deve ter no minimo 3 caracteres";
	document.getElementById(Ncampo).style.background="red";
	document.getElementById(Ncampo).focus();
	return false;
	}*/
	document.getElementById(Ncampo).style.background="#FDD9DA";
	document.getElementById(Ncampo).value="";
	alert(resposta);
	document.getElementById(Ncampo).focus();
	return false;
}
//fnção que formata o campo se a validação estiver ok
function ok(Ncampo)
{
	return true;
}


//função que valida o cep de acorodo com o estado selecionado, é feito um loop e de acorodo com o indice do estado é verificado
//a expressão regular correspondente ao cep no indice
function valida_cep(Ncampo)
{
	var er;
	var cep = document.getElementById(Ncampo).value;
	var uf=new Array('AM','SP','RJ','MS','MG','MT','AC','AL','AP','CE','DF','ES','GO','MA','PA','PE','PI','PR','RN','RO','RR','RS','SC','SE','TO','BA');
	var ers=new Array(/^[6][9][0-8][0-9]{2}-[0-9]{3}$/,/^([1][0-9]{3}|[01][0-9]{4})-[0-9]{3}$/,/^[2][0-8][0-9]{3}-[0-9]{3}$/,
	/^[2][0-8][0-9]{3}-[0-9]{3}$/,/^[2][0-8][0-9]{3}-[0-9]{3}$/,/^[7][8][8][0-9]{2}-[0-9]{3}$/,/^[6][9]{2}[0-9]{2}-[0-9]{3}$/,
	/^[5][7][0-9]{3}-[0-9]{3}$/,/^[6][89][9][0-9]{2}-[0-9]{3}$/,/^[6][0-3][0-9]{3}-[0-9]{3}$/,/^[7][0-3][0-6][0-9]{2}-[0-9]{3}$/,
	/^[2][9][0-9]{3}-[0-9]{3}$/,/^[7][3-6][7-9][0-9]{2}-[0-9]{3}$/,/^[6][5][0-9]{3}-[0-9]{3}$/,/^[6][6-8][0-8][0-9]{2}-[0-9]{3}$/,
	/^[5][0-6][0-9]{2}-[0-9]{3}$/,/^[6][4][0-9]{3}-[0-9]{3}$/,/^[8][0-7][0-9]{3}-[0-9]{3}$/,/^[5][9][0-9]{3}-[0-9]{3}$/,
	/^[7][8][9][0-9]{2}-[0-9]{3}$/,/^[6][9][3][0-9]{2}-[0-9]{3}$/,/^[9][0-9]{4}-[0-9]{3}$/,/^[8][89][0-9]{3}-[0-9]{3}$/,
	/^[4][9][0-9]{3}-[0-9]{3}$/,/^[7][7][0-9]{3}-[0-9]{3}$/,/^[4][0-8][0-9]{3}-[0-9]{3}$/);
	
		
		//document.getElementById('resposta'+Ncampo).innerHTML="";
			
	/*if(document.getElementById('uf').value=="selecione")
	{
		document.getElementById('resposta'+Ncampo).innerHTML="selecione o estado";
		return false;
	}*/
	if(document.getElementById('uf').value=="selecione" && document.getElementById('cep').value!="")
	{
		document.getElementById(Ncampo).style.background="red";
		document.getElementById(Ncampo).innerHTML ="selecione o estado antes de informar o CEP";
		return false;
	}
	
	for(i=0;i<uf.length;i++)
	{	
			if(uf[i]==document.getElementById('uf').value)
			{	
				if(cep!="")
				{	
					er=ers[i];
					if(!er.test(cep))
					{	
						return erro(Ncampo);						
					}		
					else
					{	
						return ok(Ncampo);					
					}
				}
				

		 }	document.getElementById(Ncampo).style.background="#FFFFFF";
			document.getElementById(Ncampo).innerHTML.value="";
	}	
}


//valida os campos
function valida_campos(Ncampo)

{   
		//de acorodo com o campo a var er recebe uma expressão regular que vai vlaidar o campo exceto  CPF,CEP e Data que valida atrave da função
		//validar_CPF()		
			if(Ncampo=="senha")
				var er =/^\w{3,6}$/;
			if(Ncampo=="rg")
				var er =/^[0-9]{8}-[0-9]{2}$/;		
			if(Ncampo=="nome")
				var er=/[a-zA-Z]{3,}/;
			if(Ncampo=="email")
				  var er=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/
				
			 b=document.getElementById(Ncampo).value;
			if(b != "")
			{ 
				if(!er.test(b))
				{	
					return erro(Ncampo);			
				}		
				//se Ncampo passar na ER, então é feita a formatação do campo CEP = xxxxx-xxx
				else
				{	
					return ok(Ncampo);					
				}
			}

			
}   


//função que valida o cpf
function validar_CPF(Ncampo)   
{   	
		erro = new String;   
  		cpf=document.getElementById(Ncampo);
        if (cpf.value.length == 14)   
   		 {     
				cpf.value = cpf.value.replace('.', '');   
				cpf.value = cpf.value.replace('.', '');   
				cpf.value = cpf.value.replace('-', ''); 
	  
				var nonNumbers = /\D/;   
				
				if (nonNumbers.test(cpf.value))   
				{   
						erro = "A verificacao de CPF suporta apenas números!";   
				}   
				else   
				{   
						if (cpf.value == "00000000000" ||   
								cpf.value == "11111111111" ||   
								cpf.value == "22222222222" ||   
								cpf.value == "33333333333" ||   
								cpf.value == "44444444444" ||   
								cpf.value == "55555555555" ||   
								cpf.value == "66666666666" ||   
								cpf.value == "77777777777" ||   
								cpf.value == "88888888888" ||   
								cpf.value == "99999999999") {   
								   
								erro = "Número de CPF inválido 1!"   
								//document.getElementById(Ncampo).value = cpf.value;
						}   
						
						
						var a = [];   
						var b = new Number;   
						var c = 11;   
	  
						for (i=0; i<11; i++){   
								a[i] = cpf.value.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.value.charAt(9) != a[9]) || (cpf.value.charAt(10) != a[10])) {   
							erro = "Número de CPF inválido.";  
							//document.getElementById(Ncampo).value = cpf.value; 
						}   
				}   
		}   
		else   
		{   
			if(cpf.value.length == 0)  
			{
				//document.getElementById('resposta'+Ncampo).innerHTML="";
				document.getElementById(Ncampo).style.background="#FFFFFF" 
				return false;   
			}
			else   
				erro = "Número de CPF inválido.";   
		}   
		if (erro.length > 0) {   
				alert(erro);   

				if (cpf.value.length == 11)   
				{     
					str = cpf.value;
					str2 = cpf.value.substring(0,3);
					str3 = cpf.value.substring(3,6);
					str4 = cpf.value.substring(6,9);
					str5 = cpf.value.substring(9,12);
					result=str.replace(str,str2+'.');
					result2=str.replace(str,str3+'.');
					result3=str.replace(str,str4+'-');
					document.getElementById(Ncampo).value = result + result2 + result3 + str5;
					document.getElementById(Ncampo).style.background="red";
					document.getElementById(Ncampo).focus(); 
					return false;   
				}				
			
				document.getElementById(Ncampo).value = cpf.value;
				document.getElementById(Ncampo).style.background="red";
				document.getElementById(Ncampo).focus(); 
				return false;   
		}     
		document.getElementById(Ncampo).style.background="#98EE84";
		//document.getElementById('resposta'+Ncampo).innerHTML="";
		str = cpf.value;
		str2 = cpf.value.substring(0,3);
		str3 = cpf.value.substring(3,6);
		str4 = cpf.value.substring(6,9);
		str5 = cpf.value.substring(9,12);
		result=str.replace(str,str2+'.');
		result2=str.replace(str,str3+'.');
		result3=str.replace(str,str4+'-');
		document.getElementById(Ncampo).value = result + result2 + result3 + str5;
		return true;       
}   




//função que formata os campos - auto completa os campos cep,cpf,rg e data
function formata(Ncampo)
{
	var campo=document.getElementById(Ncampo).value;
	var str;
	var str2;
	var str3;

	if(Ncampo=='cep')
	{	
		if(campo.length==5)
		{	
			var str = campo.substring(0,5);
			document.getElementById(Ncampo).value = str+"-";
		}
	}
	if(Ncampo=='rg')
	{	
		if(document.getElementById(Ncampo).value.length==8)
		{	
			var str = document.getElementById(Ncampo).value.substring(0,8);
			document.getElementById(Ncampo).value = str+"-";
		}
	}
	
	if(Ncampo=='data')
	{	
		if(document.getElementById(Ncampo).value.length==2)
		{	
			var str = document.getElementById(Ncampo).value.substring(0,2);
			pt1=document.getElementById(Ncampo).value = str+"/";
		}
		if(document.getElementById(Ncampo).value.length==5)
		{	
			var str2 = document.getElementById(Ncampo).value.substring(3,5);
			pt2=document.getElementById(Ncampo).value = pt1+str2+"/";
		}
	}
	
	if(Ncampo=="cpf")
	{
		if(document.getElementById(Ncampo).value.length==3)
			{
				
				valor=document.getElementById(Ncampo).value;
				str = document.getElementById(Ncampo).value.substring(0,3);
				result=valor.replace(valor,str+'.');
				document.getElementById(Ncampo).value = result;
			}
		if(document.getElementById(Ncampo).value.length==7)
			{
				valor1=document.getElementById(Ncampo).value;
				str2 = document.getElementById(Ncampo).value.substring(4,8);
				result2=valor1.replace(valor1,str2+'.');
				document.getElementById(Ncampo).value = result + result2;
			}
		if(document.getElementById(Ncampo).value.length==11)
			{
				valor2=document.getElementById(Ncampo).value;
				str3 = document.getElementById(Ncampo).value.substring(8,11);

				result3=document.getElementById(Ncampo).value = result + result2 + str3 + "-";
			}
		if(document.getElementById(Ncampo).value.length==15)
			{
				valor3=document.getElementById(Ncampo).value;
				str3 = document.getElementById(Ncampo).value.substring(12,15);
				result4=valor3.replace(valor3,str3);
				document.getElementById(Ncampo).value = result + result2 + result3 + result4;
			}
					
	}
	
}

function Mascara(objeto){ 
   if(objeto.value.length == 0)
     objeto.value = '(' + objeto.value;

   if(objeto.value.length == 3)
      objeto.value = objeto.value + ')';

 if(objeto.value.length == 8)
     objeto.value = objeto.value + '-';
}

// -----------------------------------------------------------------
//-----------------------------------------------------------------
// -----------------------------------------------------------------
//-----------------------------------------------------------------
// -----------------------------------------------------------------
//-----------------------------------------------------------------
// -----------------------------------------------------------------
//-----------------------------------------------------------------

function isNUMB(c) 
 { 
 if((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+"."+c.substring(cx+1); 
  } 
 if((parseFloat(c) / c != 1)) 
  { 
  if(parseFloat(c) * c == 0) 
   { 
   return(1); 
   } 
  else 
   { 
   return(0); 
   } 
  } 
 else 
  { 
  return(1); 
  } 
 } 
function LIMP(c) 
 { 
 while((cx=c.indexOf("-"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("/"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("."))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("("))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(")"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(" "))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 return(c); 
 } 

function VerifyCNPJ(CNPJ) 
 { 
 CNPJ = LIMP(CNPJ); 
 if(isNUMB(CNPJ) != 1) 
  { 
  return(0); 
  } 
 else 
  { 
  if(CNPJ == 0) 
   { 
   return(0); 
   } 
  else 
   { 
   g=CNPJ.length-2; 
   if(RealTestaCNPJ(CNPJ,g) == 1) 
    { 
    g=CNPJ.length-1; 
    if(RealTestaCNPJ(CNPJ,g) == 1) 
     { 
     return(1); 
     } 
    else 
     { 
     return(0); 
     } 
    } 
   else 
    { 
    return(0); 
    } 
   } 
  } 
 } 
function RealTestaCNPJ(CNPJ,g) 
 { 
 var VerCNPJ=0; 
 var ind=2; 
 var tam; 
 for(f=g;f>0;f--) 
  { 
  VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind; 
  if(ind>8) 
   { 
   ind=2; 
   } 
  else 
   { 
   ind++; 
   } 
  } 
  VerCNPJ%=11; 
  if(VerCNPJ==0 || VerCNPJ==1) 
   { 
   VerCNPJ=0; 
   } 
  else 
   { 
   VerCNPJ=11-VerCNPJ; 
   } 
 if(VerCNPJ!=parseInt(CNPJ.charAt(g))) 
  { 
  return(0); 
  } 
 else 
  { 
  return(1); 
  } 
 } 
  

  function FormataCGC(Formulario, Campo, TeclaPres) 
  { 
    var tecla = TeclaPres.keyCode; 
    var strCampo; 
    var vr; 
    var tam; 
    var TamanhoMaximo = 14; 
  
    eval("strCampo = document." + Formulario + "." + Campo); 
  
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    tam = vr.length; 

    if (tam < TamanhoMaximo && tecla != 8) 
    { 
      tam = vr.length + 1; 
    } 

    if (tecla == 8) 
    { 
      tam = tam - 1; 
    } 

    if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) 
    { 
      if (tam <= 2) 
      { 
        strCampo.value = vr; 
      } 
       if ((tam > 2) && (tam <= 6)) 
       { 
         strCampo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam); 
       } 
       if ((tam >= 7) && (tam <= 9)) 
       { 
         strCampo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 10) && (tam <= 12)) 
       { 
         strCampo.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)) 
       { 
         strCampo.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)) 
       { 
         strCampo.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); 
      } 
    } 
  } 

function TESTA() 
 { 
 if(VerifyCNPJ(document.forms[0].CNPJ.value) != 1 && document.forms[0].CNPJ.value != "") 
  { 
  alert("CNPJ não é válido!"); 
  document.forms[0].CNPJ.focus(); 
  } 

 return; 
 } 

