var controle=0;
var cor_erro_borda, cor_foco_borda, cor_foco_fundo, cor_erro_fundo, ico_foco, ico_erro;
var controle_foco=0;
cor_erro_borda = "#990000";
cor_erro_fundo = "";//#D7B5D0
cor_foco_borda = "";
cor_foco_fundo = "";//#C89BC6
cor_normal="";
ico_foco=0 //0=não, 1=sim
ico_erro=0;

function limparstring(s){
	s=s.replace(/ /gi,"");
  	return(s);
}

var texto = new Array()
texto[1] = "dd/mm/aaaa"
texto[2]= "00000000"
texto[3] = ""
var flag='';

function validaform(form, tipo, naoExibirEfeito,flagValidar) {
	   var resp;
	   if(!flagValidar)
	   	flag=''
	   else
	    flag=flagValidar;
	   resp=validar(form)
	   if (resp==false){
		   if(tipo==1){
			  alert('Algum campo não foi preenchido corretamente.\nVerifique os campos preenchidos e tente novamente.');
		   }
		   else if(tipo==3)
		   {
				if(document.getElementById("alerta"))
			  	{
					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 
		   {
			   	if(!naoExibirEfeito)
			   		exibeEfeito();
			    iniciaAjax('../page/_boxAlerta.asp','', 'divResultado');
		   }
		return false;
	   }
	else{
		return(true);
	}
} 

function chamaFormDesfoca(e){
	criaEventAndThis(e)
	desfocaAreaRestrita()
}
criaOnFocus();
criaOnBlur();
criaOnKeyPress();
criaOnChange();
criaOnKeyUp();

function validar(fr) {
	var a, resp, limite, erro, senha;
	var i = 0;
	var s=new String;
	controle_foco=0;
	a=0;
	controle=0;
	resp=0;	
	for(i=0;i<fr.elements.length;i++)
	{ 
		if(fr.elements[i].getAttribute("Tipo")!="IGNORE" && (!fr.elements[i].getAttribute("flag") || fr.elements[i].getAttribute("flag")==flag))
		{
			fr.elements[i].style.borderColor =""
			if (fr.elements[i].getAttribute("Obrigatorio")=="1" || fr.elements[i].getAttribute("ob")=="1"){
				if(fr.elements[i].tagName=="SELECT"){	
					if (fr.elements[i].value=="") {
						ErroForm(fr.elements[i]);
						resp=resp+1;
					}
				} 
				else{ 
						s=fr.elements[i].value;
						s=limparstring(s);
						if (s.length==0) 
						{
							ErroForm(fr.elements[i]);
							resp=resp+1;
						}
						else{
							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 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" || campoform.getAttribute("ob")=="1" || s.length>0) 
		{
			temp=campoform.value;
			if (isNaN(parseInt(temp))){ 
			resposta=false;
			ErroForm(campoform);
			}
		}
	}
	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);
			}
		}
		else{
		resposta=false;
		ErroForm(campoform);
		}
	}

	if (campoform.getAttribute("Tipo")=="NOM") 
	{
		s=campoform.value;
		s=limparstring(s);
		if (campoform.getAttribute("Obrigatorio")=="1" || campoform.getAttribute("ob")=="1" || s.length>0) 
		{
		temp=campoform.value;
		if (temp.indexOf(" ")==-1)
		{ 
		resposta=false;
		ErroForm(campoform);
		} 
		}
	}
	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);
		}
	} 
	if (campoform.getAttribute("Tipo")=="LOG"){
		s=campoform.value;
		s=limparstring(s);
		padrao = /\W/;
		OK = padrao.exec(s);
		if (OK)
		{
		resposta=false;
		ErroForm(campoform);
		} 
	}
	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);
		} 
	}
	if (campoform.getAttribute("Tipo")=="SENHA2"){
		s=campoform.value;
		s=limparstring(s);
		if(s!=senha)
		{
		resposta=false;
		ErroForm(campoform);
		} 
	}
	if (campoform.getAttribute("Tipo")=="CPF"){
		s=campoform.value;
		s=limparstring(s);
		if(validaCPF(s)==false)
		{
		resposta=false;
		ErroForm(campoform);
		} 
	}
	if (campoform.getAttribute("Tipo")=="RADIO"){
		var chk=false;
		var campo_radio = document.getElementsByName(campoform.getAttribute("Name"))
		for (j=0;j<campo_radio.length;j++){ 
			if (campo_radio[j].checked) 
				chk=true; 
		} 
		if (chk==false)
		{
			resposta=false;
			var ach=0;
			for (j=0;j<campo_radio.length;j++) 
			{
				if(!campo_radio[j].getAttribute('parentEl') && ach==0)
				{
					campo_radio[j].parentNode.style.border='1px solid '+cor_erro_borda;					
				}
				else if(ach==0)
				{
					document.getElementById(campo_radio[j].getAttribute('parentEl')).style.border='1px solid '+cor_erro_borda;
					ach=1;
				}
			}
			if(controle_foco==0){
				var tr = campo_radio[0].parentNode.parentNode;
				var span = document.createElement("span");
				if(ico_erro==1){
					span.id="vld_img_"+campo_radio[0].id;
					span.innerHTML = "<img src='../conteudo/diversos/img_erro.gif' height=14>";
					tr.appendChild(span);
					controle_foco=1;
				}
			}
		}
		else
		{
			for (j=0;j<campo_radio.length;j++)
			{
				campo_radio[j].parentNode.style.border="";
				if(campo_radio[j].getAttribute('parentEl'))
					document.getElementById(campo_radio[j].getAttribute('parentEl')).style.border="";
			}
		}
	}
	if (campoform.getAttribute("Tipo")=="DATA"){
		s=campoform.value;
		s=limparstring(s);
		hoje = new Date();
		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 <= 2099 && ano >= 1900));
			if (!resultado) 
			{
				resposta=false;
				if(campoform.getAttribute("Focar"))
					ErroForm(document.getElementById(campoform.getAttribute("Focar")));
				else
					ErroForm(campoform);
			}
		} 
		else 
		{
			resposta=false;
			if(campoform.getAttribute("Focar"))
				ErroForm(document.getElementById(campoform.getAttribute("Focar")));
			else
				ErroForm(campoform);			
		}
	}
	if (campoform.getAttribute("Tipo")=="HORA"){
		s=campoform.value;
		s=limparstring(s);
		barras = s.split(":");
		if (barras.length == 3)
		{
			hora = barras[0];
			minuto = barras[1];
			segundo = barras[2];
			resultado = (!isNaN(hora) && (hora >= 0) && (hora < 24)) && (!isNaN(minuto) && (minuto >= 0) && (minuto < 60)) && (!isNaN(segundo) && (!isNaN(segundo)) && (segundo < 60 && segundo >= 0));
			if (!resultado) 
			{
			resposta=false;
			ErroForm(campoform);
			}
		} 
		else if(barras.length == 2){
			hora = barras[0];
			minuto = barras[1];
			resultado = (!isNaN(hora) && (hora >= 0) && (hora < 24)) && (!isNaN(minuto) && (minuto >= 0) && (minuto < 60));
			if (!resultado) 
			{
			resposta=false;
			ErroForm(campoform);
			}
		}
		else
		{
			resposta=false;
			ErroForm(campoform);
		}
	}
	return(resposta);
}	

function ErroForm(campo){
	campo.setAttribute("foco", "1");
	if(controle_foco==0)
		focaPrimeiro(campo);
	if(cor_erro_borda!="")
		campo.style.border = "1px solid " + cor_erro_borda;	
	if(cor_erro_fundo!=""){
		campo.style.borderColor = cor_erro_borda;
	}
	if(campo.tagName=='SELECT'){
		campo.style.backgroundColor=cor_erro_fundo;
	}
}	

function focaPrimeiro(campo){
	campo.focus();
	controle_foco=1;
}
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 criaOnKeyUp()
{
	for (j=0;j<document.forms.length;j++){
		for (var i=0; i<document.forms[j].elements.length; i++){
			var numerico = !(isNaN(parseInt(document.forms[j].elements[i].getAttribute("prox"))))
			if(document.forms[j].elements[i].type == "text" && numerico){
				campoForm = document.forms[j].elements[i];
				campoForm.setAttribute("campoProx", document.forms[j].elements[i+1].id);
				adicionaEvento(campoForm, "keyup", formProximo);
			}
		}
	}
}


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", formBlur);
			}
		}
	}
}
function criaOnChange(){
	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 == "select-one"){
				campoForm = document.forms[j].elements[i];
				adicionaEvento(campoForm, "change", chamaFormDesfoca);
			}
		}
	}
}

function formFoca (e){
	criaEventAndThis(e)
	escondeTexto(source);
	if(source.getAttribute("foco")!=1)
	{
		source.className += ' inputFoca';
	}
}
function formDesfoca(campo, numtexto)
{
		source.className = source.className.replace('inputFoca','');
		mostraTexto(campo, numtexto);		
}
function formBlur (e){
	criaEventAndThis(e)
	if(source.getAttribute("tipo")=='CEP' || source.getAttribute("tipo")=='CPF' || source.getAttribute("tipo")=='IN')
		mostraTexto(source, 3)
	if(source.getAttribute("foco")!="1")
	{	
		source.className = source.className.replace('inputFoca','');		
	}
}

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 ="";
	source.style.backgroundColor ="";	
	source.setAttribute("foco", "0");
}
function formProximo(e){
	criaEventAndThis(e);
	var code=(window.event)?window.event.keyCode:e.which;
	if(source.value.length==source.getAttribute("prox") && code!=08 && code!=110){
		document.getElementById(source.getAttribute("campoProx")).focus();
	}
}
