// =====================================================================================================
//	Validação de formulário
//
//	Tipos: TXT, NUM, CEP, TEL, PW1, PW2, DAT, HOR, EML, CPF, CMB, RDO, IPE, CNP, DIN, FLO
//	Obrigatório: 1 = sim, 0 = não.
//	Nome do campo: caracteres alfanuméricos com acentos permitidos
//
//  Sintaxe: [Nome do campo] + _ + [Tipo] + [Obrigatório] + _ + [Número mínimo de caracteres]
// =====================================================================================================



// ======================================================================
//	getElementById	(navegadores velhos)
// ======================================================================
if (!document.getElementById){
	if (document.all) {
		document.getElementById = function() {
			if (typeof document.all[arguments[0]] != 'undefined') {
				return document.all[arguments[0]];
			} else {
				return null;
			}
		}
	} else if (document.layers) {
		document.getElementById = function() {
			if (typeof document[arguments[0]] != 'undefined') { 
				return document[arguments[0]];
			} else {
				return null;
			}
		}
	}
}

// ======================================================================
//	document.all (navegadores velhos)
// ======================================================================
if (!document.all) {
	document.all = document.getElementsByTagName('*');
}

// ======================================================================
//	alias getElementById
// ======================================================================
function getElm(tmp_id) {
	return document.getElementById(tmp_id);	
}

// ======================================================================
//	Enviar
// ======================================================================
function Enviar(tmp_id_form) {
	//variáveis globais
	x = 0; 								//contagem dos elementos do formulário
	erro = false;  						//controle de erro
	form = getElm(tmp_id_form);         //objeto do formulário
	numero_validos = '0123456789,.-';	//caracteres válidos para número
	cep_validos = '0123456789';	//caracteres válidos para cep	
	tmp_senha = '';						//senha temporária para comparar
	msgs = Array();
	msgs[0] = 'Por favor complete o campo "%1"';
	msgs[1] = 'Caracter inválido colocado no campo %1';
	msgs[2] = 'Você precisa digitar uma senha.';
	msgs[3] = 'A confirmação da senha não é válida.';
	msgs[4] = 'Por favor complete o campo "%1" com formato dd/mm/aaaa';
	msgs[5] = 'Dados inválidos colocados no campo %1';
	msgs[6] = 'CPF Inválido! Não utilize "-".';
	msgs[7] = 'Por favor selecione uma opção para o campo "%1"';
	msgs[8] = 'Por favor complete o campo "%1" com formato hh:mm';
	msgs[9] = 'O campo "%1" deve conter pelo menos %2 caracteres.' ;
	msgs[10] = '';	
	
	
	
	//while dos elementos
	while (form.elements[x]) {
		id = form.elements[x].id;		//id=""
		type = form.elements[x].type;   //type=""
		nomec = form.elements[x].name;  //nome=""
		obrigatorio = false;	        //obrigatório
		tipo = '';				        //tipo (TXT)
		nome = '';						//nome do campo (antes do _)
		
		//.pega tipo, nome, obrigatorio
		i = 0;
		underline = 0;
		qnt = 0;
		while (i < id.length) {
			if ((id.charAt(i) != '_') && (!underline)) {
				nome = nome + id.charAt(i);
			} else if (id.charAt(i) == '_') {
				underline++;	
			} else if (underline == 1) {
				if (tipo.length < 3) {
					tipo = tipo + id.charAt(i);
				} else {
					if (id.charAt(i) == '0') {
						obrigatorio = false;						
					} else {
						obrigatorio = true;	
					}
				}
			} else if (underline == 2) {
				qnt = qnt + '' + id.charAt(i);	
			}
			i++;	
		}
		
		if (qnt == '') {
			qnt = 0;
		} 
		
		qnt = parseInt(qnt);
		
		if (((tipo == 'TXT') || (tipo == 'CNP')) && (!erro)) {
			if (obrigatorio) {
				if (!getElm(id).value) {
					alert(msgs[0].replace('%1',nome));
					getElm(id).focus();
					erro = true;
					break;
				}
				if (getElm(id).value.length < qnt) {
					alert(msgs[9].replace('%1',nome).replace('%2',qnt));
					getElm(id).focus();
					erro = true;
					break;
				}
			}	
		} else if (((tipo == 'NUM') || (tipo == 'TEL') || (tipo == 'IP') || (tipo == 'DIN') || (tipo == 'FLO')) && (!erro)) {
			if (getElm(id).value) { 	
				var c;								
				var value = getElm(id).value;	
				i = 0;
				while (i < value.length) {
					c = value.charAt(i);		
					if (numero_validos.indexOf(c) == -1) {	
						alert(msgs[1].replace('%1',nome));
						getElm(id).focus();
						erro = true;
						break;
					}
					i++;
				}
				
				if (getElm(id).value.length < qnt) {
					alert(msgs[9].replace('%1',nome).replace('%2',qnt));
					getElm(id).focus();
					erro = true;
					break;
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}	
		} else if ((tipo == 'CEP') && (!erro)) {
			if (getElm(id).value) { 	
				var c;								
				var value = getElm(id).value;	
				var value2 = value.replace('-', '');
				
				i = 0;
				while (i < value.length) {
					c = value.charAt(i);		
					if (cep_validos.indexOf(c) == -1) {	
						erro = true;
					}
					i++;
				}
				
				if (value2.length < qnt) {
					alert(msgs[9].replace('%1',nome).replace('%2',qnt));
					getElm(id).focus();
					erro = true;
					break;
				} 

				if ((value2 == "00000000") || (value2 == "11111111") || (value2 == "22222222") || (value2 == "33333333") || (value2 == "44444444") || (value2 == "55555555") || (value2 == "66666666") || (value2 == "77777777") || (value2 == "88888888") || (value2 == "99999999")) {
					erro = true;
				}
				
				if (erro) {
					alert(msgs[6]);
					getElm(id).focus();
					erro = true;
					break;	
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}	
		} else if ((tipo == 'PW1') && (!erro)) {
			if ((!getElm(id).value) && (obrigatorio)) {
				alert(msgs[2]);
				getElm(id).focus();
				erro = true;
				break;					
			} else {
				tmp_senha = getElm(id).value;
			}
		} else if ((tipo == 'PW2') && (tmp_senha != null) && (!erro)) {
			if (getElm(id).value != tmp_senha) {
				tmp_senha = null;
				alert(msgs[3]);			
				getElm(id).focus();
				erro = true;
				break;
			} 
		} else if ((tipo == 'DAT') && (!erro))  {
			if (getElm(id).value) {
				var value = getElm(id).value;
				if ((value.length == 10) && (value.charAt(2) == '/') && (value.charAt(5) == '/') && (value.split('/')[0]*1 <= 31) && (value.split('/')[1]*1 <= 12) && (value.split('/')[2]*1 >= 1900)) {
					//Data válida...
				} else {
					alert(msgs[4].replace('%1',nome));
					getElm(id).focus();
					erro = true;
					break;
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}
		} else if ((tipo == 'HOR') && (!erro)) {
			if (getElm(id).value) {
				var value = getElm(id).value;
				if ((value.length == 5) && (value.charAt(2) == ':') && (value.split(':')[0]*1 <= 24) && (value.split(':')[1]*1 <= 59)) {
					//Hora válida
				} else {
					alert(msgs[8].replace('%1',nome));
					getElm(id).focus();
					erro = true;
					break;
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}
		} else if ((tipo == 'EML') && (!erro)) {
			if (getElm(id).value) { 
				var c;		
				var value = getElm(id).value;
				if ((value.indexOf(".")>1) && (value.indexOf("@")>0) && (value != '@.')) {
					//email está correto..
				} else {
					alert(msgs[5].replace('%1',nome));
					getElm(id).focus();
					erro = true;
					break;
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}
		} else if ((tipo == 'CPF') && (!erro)) {
			value = getElm(id).value;
			
			if (value) {
				var p1 = value.substring(0,3);								
				var p2 = value.substring(4,7);
				var p3 = value.substring(8,11);
				var p4 = value.substring(12,14);
				var cpf = p1 + p2 + p3 + p4;
				var cpf_ate_barra = cpf.substring(0,9);	
				var cpf_apos_barra = cpf.substring(9,11);	
				var c = 0;
				var posicao=1;
				/*
				for (i=0;i<9;i++) {
					c+=cpf.substring(i,posicao)*(10-i);
					posicao++;
				}
				
				c = (11-(c % 11));
				if (c > 9) { 
					c=0; 
				}	
				if (cpf_apos_barra.substring(0,1) != c) {
					alert(msgs[6]);
					document.getElementById(id).focus();
					erro = true;
					break;
				}
				
				c *= 2;
				posicao = 1;
				for (i=0; i<9; i++) {
					c+=cpf.substring(i,posicao)*(11-i);
					posicao++;
				}
				
				c = (11-(c % 11));
				if (c > 9) { c = 0; }
				if (cpf_apos_barra.substring(1,2) != c) {
					if (!erro) {
						alert(msgs[6]);
						getElm(id).focus();
						erro = 1;
						break;
					}
				}*/
				
				if ((cpf == '99999999999') && (cpf == '88888888888') && (cpf == '77777777777') && (cpf == '66666666666') && (cpf == '55555555555') && (cpf == '44444444444') && (cpf == '33333333333') && (cpf == '22222222222') && (cpf == '11111111111')) {
					if (!erro) {
						alert(msgs[6]);
						getElm(id).focus();
						erro = 1;
						break;
					}
				}
			} else if (obrigatorio) {
				alert(msgs[0].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}			
		} else if ((tipo == 'CMB') && (!erro)) {
			if (((getElm(id).selectedIndex == 0) || (getElm(id).selectedIndex == 1)) && (obrigatorio)) {
				alert(msgs[7].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}			
		} else if ((tipo == 'RDO') && (erro == 0)) {
			var ok = 0;
			var el = document.getElementsByName(nomec);
			//var el = eval("document." + tmp_id_form + "." + nomec + "[0]");
			//var el = eval("form.elements['" + id + "']");
			//alert(form.elements[nomec]);
			//alert(document.getElementsByName(nomec));
			//alert(nomec);
			//alert_r(el);
			//alert(el.length);

			for (i=0; i < el.length; i++) {
				var tmp = el[i].checked;
				if (tmp) { ok = 1; }
			}

			if ((obrigatorio) && (ok == 0)) {
				alert(msgs[7].replace('%1',nome));
				getElm(id).focus();
				erro = true;
				break;
			}			
		}
		
		x++;
	}
	
	if (!erro) {
		form.submit();
		return true;
//	} else {
	//	return false;	
	}
}

// ======================================================================
//	Adiciona máscaras
// ======================================================================
window.onload = function() {
	var inputs = document.getElementsByTagName('input');
	var total = inputs.length;
	var el = '';
	for (x=0; x<total; x++) {
		el = inputs[x];
		id = el.id;
		tipo = '';
		
		// quebra nome para pegar tipo
		for (i=(id.length-4); i<(id.length-1); i++) {
			tipo += id.charAt(i);
		}
		
		if (tipo == 'CPF') {
			el.onkeydown = function() {
				MascaraCPF(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraCPF(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraCPF(this.id, this.value);
			}
			el.maxLength = 14;
		} else if (tipo == 'DAT') {
			el.onkeydown = function() {
				MascaraData(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraData(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraData(this.id, this.value);
			}
			el.maxLength = 10;
		} else if (tipo == 'HOR') {
			el.onkeydown = function() {
				MascaraHora(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraHora(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraHora(this.id, this.value);
			}
			el.maxLength = 5;
		} else if (tipo == 'TEL') {
			el.onkeydown = function() {
				MascaraTelefone(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraTelefone(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraTelefone(this.id, this.value);
			}
			el.maxLength = 14;			
		} else if (tipo == 'IPE') {
			el.onkeydown = function() {
				MascaraIP(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraIP(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraIP(this.id, this.value);
			}
			el.maxLength = 15;	
		} else if (tipo == 'CNP') {
			el.onkeydown = function() {
				MascaraCNPJ(this.id, this.value);
			}
			el.onkeyup = function() {
				MascaraCNPJ(this.id, this.value);
			}
			el.onkeypress = function() {
				MascaraCNPJ(this.id, this.value);
			}
			el.onblur = function() {
				MascaraCNPJ(this.id, this.value);
			}
			el.onfocus = function() {
				MascaraCNPJ(this.id, this.value);
			}
			el.maxLength = 18;	
		} else if (tipo == 'CEP') {
			el.onkeyup = function() {
				MascaraCep(this.id, this.value);
			}
			el.maxLength = 8;
		} else if (tipo == 'DIN') {
			el.onkeyup = function() {
				MascaraDinheiro(this, 15);
			}
			el.maxLength = 15;
		} else if (tipo == 'NUM') {
			el.onkeyup = function() {
				MascaraNumero(this.id, this.value);
			}
		} else if (tipo == 'FLO') {
			el.onkeyup = function() {
				MascaraNumero2(this.id, this.value);
			}
		}
	}
}

// ======================================================================
//	Máscaras
// ======================================================================
function MascaraCPF(vCampoRecebido,vTextoRecebido) {
	var vCodKey;
	if (!window.event) {
		vCodKey = 0; // Caso Mozilla ou outro.. não checkar a tecla pressionada...
	} else {
		vCodKey = window.event.keyCode; // Capturando a tecla...
	}
	
	if (vCodKey != 8) {
		var vCPF='';
		vCPF=vCPF+vTextoRecebido;
		
		if (vCPF.length==3) {
			vCPF=vCPF+'.';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length==7){
			vCPF=vCPF+'.';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length==11){
			vCPF=vCPF+'-';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length > 14) {
			vTMP = '';
			for (i=0; i<14; i++) {
				vTMP = vTMP + vCPF.charAt(i);
			}
			vCPF = vTMP;
			document.getElementById(vCampoRecebido).value=vCPF;
		}
	} 
}

function MascaraData(vCampoRecebido,vTextoRecebido) {
	var vCodKey;
	if (!window.event) {
		vCodKey = 0;
	} else {
		vCodKey = window.event.keyCode;
	}
	
	if (vCodKey != 8) {
		var vData='';
		vData=vData+vTextoRecebido;
	
		if ((vData.length==1) && (vData.charAt(0) > 3)) {
			vData = '0' + vData.charAt(0);
			document.getElementById(vCampoRecebido).value=vData;
		} 
	
		if (vData.length==2) {
			vData=vData+'/';
			document.getElementById(vCampoRecebido).value=vData;
		} 
		if ((vData.length==4) && (vData.charAt(3) != 0) && (vData.charAt(3) != 1)) {
			vData = vData.charAt(0) + vData.charAt(1) + vData.charAt(2) + '0' + vData.charAt(3);
			document.getElementById(vCampoRecebido).value=vData;
		} 
		if (vData.length == 5) {
			vData=vData+'/';
			document.getElementById(vCampoRecebido).value=vData;
		}
		if (vData.length > 10) {
			document.getElementById(vCampoRecebido).value = vTextoRecebido.substr(0,10);
		}
	}
}

function MascaraHora(vCampoRecebido,vTextoRecebido) {
	var vCodKey;
	if (!window.event) {
		vCodKey = 0;
	} else {
		vCodKey = window.event.keyCode;
	}
	
	if (vCodKey != 8) {

		var vData='';
		vData=vData+vTextoRecebido;
	
		if ((vData.length==1) && (vData.charAt(0) > 2)) {
			vData = '0' + vData.charAt(0);
			document.getElementById(vCampoRecebido).value=vData;
		} 
		if ((vData.length==2) && (vData.charAt(0) != ':') && (vData.charAt(1) != ':'))  {
			vData=vData.charAt(0)+vData.charAt(1)+':';
			document.getElementById(vCampoRecebido).value=vData;
		} 
		if ((vData.length==4) && (vData.charAt(0) > 5)) {
			vData = vData.charAt(0) + vData.charAt(1) + ':' + '0' + vData.charAt(3);
			document.getElementById(vCampoRecebido).value=vData;
		} 
		if (vData.length > 5) {
			document.getElementById(vCampoRecebido).value = vTextoRecebido.substr(0,5);
		}
	}
}

function MascaraTelefone(vCampoRecebido,vTextoRecebido) {
	var vCodKey;
	if (!window.event) {
		vCodKey = 0;
	} else {
		vCodKey = window.event.keyCode;
	}
	
	if (vCodKey != 8) {
		if (document.getElementById(vCampoRecebido).value.length == 0)
			document.getElementById(vCampoRecebido).value = '(' + document.getElementById(vCampoRecebido).value;
		if (document.getElementById(vCampoRecebido).value.length == 3)
			document.getElementById(vCampoRecebido).value = document.getElementById(vCampoRecebido).value + ') ';
		if (document.getElementById(vCampoRecebido).value.length == 9)
			document.getElementById(vCampoRecebido).value = document.getElementById(vCampoRecebido).value + '.';
		if (document.getElementById(vCampoRecebido).value.length > 14)
			document.getElementById(vCampoRecebido).value = document.getElementById(vCampoRecebido).value.substr(0,14);
	}
}

function MascaraIP(vCampoRecebido,vTextoRecebido) {
	var vCodKey;
	if (!window.event) {
		vCodKey = 0; // Caso Mozilla ou outro.. não checkar a tecla pressionada...
	} else {
		vCodKey = window.event.keyCode; // Capturando a tecla...
	}
	
	if (vCodKey != 8) {
		var vCPF='';
		vCPF=vCPF+vTextoRecebido;
		
		if (vCPF.length==3) {
			vCPF=vCPF+'.';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length==7){
			vCPF=vCPF+'.';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length==11){
			vCPF=vCPF+'.';
			document.getElementById(vCampoRecebido).value=vCPF;
		} else if (vCPF.length > 15) {
			document.getElementById(vCampoRecebido).value=vCPF.substr(0,15);
		}
	} 
}

function MascaraCNPJ(vCampoRecebido,vTextoRecebido){
	Campo = document.getElementById(vCampoRecebido);
	
	var tecla;
	if (!window.event) {
		tecla = 0;
	} else {
		tecla = window.event.keyCode;
	}   
   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");
   tam = vr.length + 1;
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      else if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      else if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      else if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
	  else if (tam > 18) {
	  	 Campo.value = Campo.substr(0,18);
	  }
   }
}

function MascaraCep(id, valor) {

	objeto = document.getElementById(id);
	var valor = "";
	var tmp = objeto.value;
	var r = "";
	var numero_validos = "0123456789";
	var c;								
	var i = 0;
	
	while (i < tmp.length) {
		c = tmp.charAt(i);		
		if (numero_validos.indexOf(c) != -1) {	
			valor += c + '';
		}
		i++;
	}
	
	//if (valor.length < 5) {
		r = valor;	
	//} else {
		//r = valor.substr(0,5) + '-' + valor.substr(5,3);
	//}

	objeto.value = r;
}

function MascaraDinheiro(cur,len)
{
   possui_menos = false;
   n='__0123456789-';
   d=cur.value;
   l=d.length;
   r='';
   if (l > 0) {
	z=d.substr(0,l-1);
	s='';
	a=2;
	for (i=0; i < l; i++) {
		c=d.charAt(i);
		if (n.indexOf(c) > a) {
			a=1;
			s+=c;
			if (c == '-') {
				possui_menos = true;
			}
		};
	};
	l=s.length;
	t=len-1;
	if (l > t) {
		l=t;
		s=s.substr(0,t);
	};
	if (l > 2) {
		r=s.substr(0,l-2)+','+s.substr(l-2,2);
	} else {
		if (l == 2)	{
			r='0,'+s;
		} else {
			if (l == 1)	{
				r='0,0'+s;
			};
		};
	};
	if (r == '') {
		r='0,00';
	} else {
		l=r.length;
		
		if (possui_menos) {
			verificador = 7;
		} else {
			verificador = 6;
		}
		
		if (l > verificador) {
			j=l%3;
			w=r.substr(0,j);
			wa=r.substr(j,l-j-6);
			wb=r.substr(l-6,6);
			if (j > 0) {
				w+='.';
			};
			k=(l-j)/3-2;
			for (i=0; i < k; i++) {
				w+=wa.substr(i*3,3)+'.';
			};
			r=w+wb;
		};
	};
   };
   if (r.length <= len) {
	cur.value=r;
   } else {
	cur.value=z;
   };
};

function MascaraNumero(tmp_id, tmp_valor) {
	var numero_validos = "0123456789";
	var c;								
	var value = tmp_valor;	
	var txt = "";
	var i = 0;
	
	while (i < value.length) {
		c = value.charAt(i);		
		if (numero_validos.indexOf(c) != -1) {	
			txt += c;	
		}
		i++;
	}
	
	document.getElementById(tmp_id).value = txt;
}

function MascaraNumero2(tmp_id, tmp_valor) {
	var numero_validos = "0123456789,";
	var c;								
	var value = tmp_valor;	
	var txt = "";
	var i = 0;
	
	while (i < value.length) {
		c = value.charAt(i);		
		if (numero_validos.indexOf(c) != -1) {	
			txt += c;	
		}
		i++;
	}
	
	document.getElementById(tmp_id).value = txt;
}