//variáveis para controle das cores
var corErro="red"
var corFoco="#ffffff"

function valida(f)
{
	var DeuErro=false;
	var DeuErroAlgum=false;
	var primeiro="";
	for(var i=0;i<f.elements.length;i++)
	{
		DeuErro=false;
		if((f.elements[i].getAttribute("validar")=="1"))
		{			
			var undef;
			if(!(f.elements[i].Tipo===undef))
			{				
				var TipoValidacao=f.elements[i].getAttribute("Tipo");	
				//alert(TipoValidacao)
				switch(TipoValidacao)
				{	
					case "CPF":
						if(f.elements[i].value=='')
						{
							f.elements[i].erro="Digite seu CPF!"
							DeuErro=true;
						}							
						else
						{
							if(!validaCPF(f.elements[i].value.replace(".","").replace("-","").replace(".","")))
							{
								f.elements[i].erro="CPF inválido!"
								DeuErro=true;
							}
						}
						break
					case "CNPJ":
						if(!validaCNPJ(f.elements[i]))
							DeuErro=true;
						break
					case "NUMERO":
						f.elements[i].value=f.elements[i].value.toString().replace(",",".");
						if((f.elements[i].value=='')||(isNaN(f.elements[i].value)))
							DeuErro=true;
						break
					case "EMAIL":
					
						if(f.elements[i].value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/)==-1) 
							DeuErro=true;
						break					
					case "CEP":
						if(validaCEP(f.elements[i]))
							DeuErro=true;
						break
					case "DATA":
						if(validaData(f.elements[i]))
							DeuErro=true;
						break
					case "SENHA2":
						if(validaSenha2(f.elements[i]))
							DeuErro=true;
						break
					default:
					{						
						if(f.elements[i].value=='')
							DeuErro=true;						
					}
				}
			
			}
			else
			{
				if(f.elements[i].value=='')
					DeuErro=true;
			}			
			if(DeuErro)
			{
				mostraSpan(f.elements[i]);
				DeuErroAlgum=true;
				if(primeiro=="")
					primeiro=f.elements[i].id;
			}
			else
				oculpaSpan(f.elements[i]);
		}
	}
	if(DeuErroAlgum)
	{								
		piscar(document.getElementById(primeiro))
		return false;			
	}
}

function mostraSpan(objeto)
{	
	if(document.getElementById("valid"+objeto.id))
		document.getElementById("valid"+objeto.id).style.visibility='visible';
	objeto.style.border='solid '+corErro+' 1px';
}

function piscar(objeto,semfoco)
{	
	try
	{	objeto.focus(); }
	catch(err)
	{	
	}	
	corInicial="#E8E8E8";
	for(var k=0;k<30;)
	{
		setTimeout("document.getElementById('"+objeto.id+"').style.backgroundColor='#cccccc';",k*100);		
		setTimeout("document.getElementById('"+objeto.id+"').style.backgroundColor='"+corInicial+"';",(k+3)*100);
		k=k+6;
	}
	//if(semfoco.toString()!='1')
	try
	{	objeto.focus(); }
	catch(err)
	{	}	
}

function oculpaSpan(objeto)
{	
	if(document.getElementById("valid"+objeto.id))
		document.getElementById("valid"+objeto.id).style.visibility='hidden';
	objeto.style.borderColor='#ffffff';
}

function validaSenha2(objeto)
{
	var senha
	senha = form1.senha.value;
	return (objeto.value != senha) 
}

function validaData(objeto)
{
	return !(trim(objeto.value).toUpperCase().match(/^\d{1,2}\/\d{1,2}\/\d{4}$/));
}

function validaCEP(objeto) 
{
	return !(trim(objeto.value).toUpperCase().replace('-','').match(/^\d{8,8}$/));
}

function validaCNPJ(caixa) {
	CNPJ = caixa.value;
	erro = new String;
	if (CNPJ.length < 18) erro += "Informe o CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	if (erro.length == 0) erro += "Informe o CNPJ! \n\n";
	}
	//substituir os caracteres que nao sao numeros
	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 += "CNPJ Inválido! \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 +="CNPJ Inválido!";
	}
	if (erro.length > 0){
	//alert(erro);
	return false;
	} 
	return true;
}

function trim(str)
{
	while (str.substring(0,1) == ' ')
	{
		str = str.substring(1, str.length);
	}
	while (str.substring(str.length-1, str.length) == ' ')
	{
		str = str.substring(0,str.length-1);
	}
	return str;
}

function validaCPF(cpf) 
{
	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)
		return false;
	else
		return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//  Eventos do site
//////////////////////////////////////////////////////////////////////////////////////////////
	

function adicionaEvento(campo, evento, funcao)
{
	if (campo.addEventListener)
		campo.addEventListener(evento, funcao, true)
	if (campo.attachEvent)
		campo.attachEvent("on"+evento, funcao)
}


function criaEventAndThis(e)
{
	if(typeof(e)=='undefined')var e=window.event
	source=e.target?e.target:e.srcElement
	if(source.nodeType == 3)source = source.parentNode
}

function chamaFormDesfoca(e)
{
	criaEventAndThis(e)
	formDesfoca(source)
}

//onFocus
function criaOnFocus()
{
	for (j=0;j<document.forms.length;j++)
	{
		for (var i=0; i<document.forms[j].elements.length; i++)
		{
			if (document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password" || document.forms[j].elements[i].type == "textarea" || document.forms[j].elements[i].type == "select-one" || document.forms[j].elements[i].type == "file")
			{
				campoForm = document.forms[j].elements[i]
				adicionaEvento(campoForm, "focus", formFoca)
			}
		}
	}
}

//onKeyPress
function criaOnKeyPress()
{
	for (j=0;j<document.forms.length;j++)
	{
		for (var i=0; i<document.forms[j].elements.length; i++)
		{
			if (document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password" || document.forms[j].elements[i].type == "textarea" || document.forms[j].elements[i].type == "select-one" || document.forms[j].elements[i].type == "file")
			{
				campoForm = document.forms[j].elements[i]
				adicionaEvento(campoForm, "keypress", formNormal)
			}
		}
	}
}

//onMouseMove
function criaOnBlur()
{
	for (j=0;j<document.forms.length;j++)
	{
		for (var i=0; i<document.forms[j].elements.length; i++)
		{
			if (document.forms[j].elements[i].type == "text" || document.forms[j].elements[i].type == "password" || document.forms[j].elements[i].type == "textarea" || document.forms[j].elements[i].type == "select-one" || document.forms[j].elements[i].type == "file")
			{
				campoForm = document.forms[j].elements[i]
				adicionaEvento(campoForm, "blur", chamaFormDesfoca)
			}
		}
	}
}


function formFoca (e)
{
	criaEventAndThis(e)
	if(source.style.borderColor!=corErro)
	{
	source.style.border='solid '+corFoco+' 1px';
	}
}

function formDesfoca (campo)
{
	if(source.style.borderColor!=corErro)
	{
		source.style.borderColor = ""
		source.style.borderWidth = ""
	}
}

function formNormal (e)
{
	criaEventAndThis(e)
	source.style.borderColor =""
}


