var controle=0;
var cor_erro, cor_focado, textoErro;

cor_erro = "#e42324";
cor_focado = "#a4cbe1";
cor_normal="#C2C0C0";

function limparstring(s)
{
  	while (s.search(" ")!=-1){
	s=s.replace(" ","");
	}
  	return(s);
}

var texto = new Array()
texto[1] = "dd/mm/aaaa"
texto[2]= "00000000"
texto[3] = "apenas números"

function validaform(form, tipo) 
{
	//try
	//{
	   var resp
	   resp=validar(form)
	   if (resp==false) 
	   {
		   if(tipo==1){
				if(document.getElementById("alerta").innerHTML == ''){
					document.getElementById("alerta").innerHTML="Preencha corretamente o(s) campo(s) abaixo.";
					document.getElementById("alerta").style.display="block";
				}
				else
					document.getElementById("alerta").style.display="block";
		   }
		   else
		   	document.getElementById("alerta2").style.display="block";
		return false;
	   }
	else{
		return(true);
	}
	
	//catch(e)
	//{
	//}
} 


function chamaFormDesfoca(e)
{
	criaEventAndThis(e)
	desfocaAreaRestrita()
}

criaOnFocus()
criaOnBlur()
criaOnKeyPress()

function exibeDiv(div)
{
	try
	{
		if(document.getElementById(div).style.display!="")
			document.getElementById(div).style.display="";
		else
			document.getElementById(div).style.display="none";
	}
	catch(e)
	{
	}
}
function ocultaDiv(div)
{
	document.getElementById(div).style.display="none";
}

function validar(fr) {
	var a, resp, limite, erro, senha;
	var i = 0;
	var s=new String;
	a=0;
	controle=0;
	resp=0;
	textoErro="";
	for(i=0;i<fr.elements.length;i++){ 
		if (fr.elements[i].getAttribute("Tipo")!="IGNORE"){
			fr.elements[i].style.borderColor ="";
			if (fr.elements[i].getAttribute("Obrigatorio")=="1"){
				if(fr.elements[i].tagName!="SELECT")
				{	
					s=fr.elements[i].value;
					s=limparstring(s);
					if (s.length==0) 
					{
						ErroForm(fr.elements[i]);
						resp=resp+1;
						erroTexto(fr.elements[i].getAttribute("Nome"), 'deve ser preenchido');
					}
					else{
						if (ValidacampoformsPreenchidos(fr.elements[i], i)==false)
							resp=resp+1;
					}
				} 
				else{ 
					if (fr.elements[i].value=="") {
						ErroForm(fr.elements[i]);
						erroTexto(fr.elements[i].getAttribute("Nome"), 'deve ser preenchido');
						resp=resp+1;
					}
				}
			}
			else
			{
			if(fr.elements[i].tagName!="SELECT")
				if(fr.elements[i].value.length!=0){
					if (ValidacampoformsPreenchidos(fr.elements[i], i)==false)
							resp=resp+1;
				}
			}
		}
	}
	if(resp>0){
		return false;
	}
}

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;
}
function validaCNPJ(caixa) {
	CNPJ = caixa;
	erroInterno = new String;
	if (CNPJ.length < 18) erroInterno += "Informe o CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	if (erroInterno.length == 0) erroInterno += "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)) erroInterno += "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])){
	erroInterno +="CNPJ Inválido!";
	}
	if (erroInterno.length > 0){
	//alert(erro);
	return false;
	} 
	return true;
}

function ValidacampoformsPreenchidos(campoform, i)
{
	var resposta=true;
	var x;
	x=0;
	if (campoform.getAttribute("Tipo")=="IN")
	{  
		s=campoform.value;
		s=limparstring(s);
		if (campoform.getAttribute("Obrigatorio")=="1" || s.length>0) {
		temp=campoform.value;
		if (isNaN(parseInt(temp))){ 
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve conter um número');
		}
	}
	}
	if (campoform.getAttribute("Tipo")=="CNPJ") 
	{
		s=campoform.value;
		s=limparstring(s);
		if(validaCNPJ(s)==false)
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser um cnpj válido');
		} 
	}
	if (campoform.getAttribute("Tipo")=="CEP")
	{  
		s=campoform.value;
		s=limparstring(s);
		temp=campoform.value;
		if (!isNaN(parseInt(temp))){
			if(temp.length!=8){
			resposta=false;
			ErroForm(campoform);
			erroTexto(campoform.getAttribute("Nome"), 'deve ser um cep válido');
			}
		}
		else{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser um cep válido');
		}
	}

	if (campoform.getAttribute("Tipo")=="NOM") 
	{
		s=campoform.value;
		s=limparstring(s);
		if (campoform.getAttribute("Obrigatorio")=="1" || s.length>0) 
		{
		temp=campoform.value;
		if (temp.indexOf(" ")==-1)
		{ 
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve conter nome e sobrenome');
		} 
		}
	}
	if (campoform.getAttribute("Tipo")=="MAIL") 
	{
		s=campoform.value;
		s=limparstring(s);
		temp=campoform.value;
		if (temp.indexOf("@")==-1 || temp.indexOf(".")==-1)
		{ 
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser um e-mail válido');
		}
	} 
	if (campoform.getAttribute("Tipo")=="LOG") 
	{
		s=campoform.value;
		s=limparstring(s);
		padrao = /\W/;
		OK = padrao.exec(s);
		if (OK)
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'não pode conter caracteres especiais');
		} 
	}
	if (campoform.getAttribute("Tipo")=="SENHA") 
	{
		s=campoform.value;
		s=limparstring(s);
		padrao = /\W/
		OK = padrao.exec(s);
		senha=s;
		if (OK)
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'não pode conter caracteres especiais');
		} 
	}
	if (campoform.getAttribute("Tipo")=="SENHA2") 
	{
		s=campoform.value;
		s=limparstring(s);
		if(s!=senha)
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve coincidir com o campo senha');
		} 
	}
	if (campoform.getAttribute("Tipo")=="CPF") 
	{
		s=campoform.value;
		s=limparstring(s);
		if(validaCPF(s)==false)
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser um cpf válido');
		} 
	}
	if (campoform.getAttribute("Tipo")=="DATA") 
	{
		s=campoform.value;
		s=limparstring(s);
		hoje = new Date();
		anoAtual = hoje.getFullYear();
		barras = s.split("/");
		if (barras.length == 3)
		{
		dia = barras[0];
		mes = barras[1];
		ano = barras[2];
		resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
		if (!resultado) 
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser uma data válida');
		}
		} 
		else 
		{
		resposta=false;
		ErroForm(campoform);
		erroTexto(campoform.getAttribute("Nome"), 'deve ser uma data válida');
		}
	}
	return(resposta);
}	
function ErroForm(campo)
{
	campo.style.borderColor = cor_erro;
	campo.style.backgroundColor = "#FDF2F3";
}	

function erroTexto(campo, texto2)
{
	var novo = "O campo <b>"+campo+"</b> "+texto2;
	textoErro=textoErro+"<br>"+novo;
}	

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 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);
			}
		}
	}
}

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);
			}
		}
	}
}

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!=cor_erro){
	source.style.borderColor = cor_focado;
	source.style.borderWidth = "1px";
	escondeTexto(source);
	}
}
function formDesfoca (campo, numtexto)
{
	if(source.style.borderColor!=cor_erro){
		source.style.borderColor = "";
		source.style.borderWidth = "";
		mostraTexto(campo, numtexto);
	}
}
function desfocaAreaRestrita()
{
	formDesfoca(source,'');
}
function escondeTexto(campo)
{
	for (var i=1; i <= texto.length; i++){
		if (campo.value == texto[i]){
			campo.value = ""
		}
	}
}
function mostraTexto(campo, numtexto)
{
	if (campo.value == "" && numtexto != ""){
		campo.value = texto[numtexto];
	}
}
function formNormal (e){
	criaEventAndThis(e);
	source.style.borderColor ="";
}