// JavaScript Document
/*--------------------------------------------------------------------------------
 Função que valida qualquer tipo de dado para forms (Validação de Folumário)
	Autor: Lucas Reis (lucas@e-value.com.br)
	
	-------------| Documentação |-------------
	Exemlo: valida("Nome",form.nome,1,"T");
	(texto, nome do campo, numero mínimo de caracters, tipo de dado)
	* texto = texto que aparece no alert (O campo 'NOME' bla bla bla)
	* Nome do Campo = formulario.campo (form.nome)
	* Mínimo de caracters = número mínimo de caraxters (2)
	* Tipo do dado:
		- T = Texto  	| "exemplo"
		- N = Número 	| 123
		- E = E-Mail 	| teste@teste.com
		- D = Data   	| 10/10/1990
		- J = CNPJ		| 33684222000120
		- C = CPF		| 17195386899
--------------------------------------------------------------------------------*/
function valida(texto,campo,nCatacters,tipo){
			try{
				switch (tipo){
					case "T":
						if (campo.value.length <= nCatacters){
							alert("Atenção!\nO campo " + texto + " deve ser preechido corretamente!");
							campo.focus();
							return false;
						}
						break;
					case "N":
						if (isNaN(campo.value)){
							alert("Atenção!\nO campo " + texto + " deve ser preechido com apena números!");
							campo.focus();
							return false;
						}
						if (campo.value.length <= nCatacters){
							alert("Atenção!\nO campo " + texto + " deve ser preechido corretamente!");
							campo.focus();
							return false;
						}
						break;
					case "E":
						var regexEmail = /^(([^<>()[\]\\!?.,;áàãâäéèêëíìîïóòõôöúùûüç:\s@\""]+(\.[^<>()[\]\\.,;áàãâäéèêëíìîïóòõôöúùûüç:\s@\""]+)*)|(\"".+\""))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$$/;
						
						if (campo.value.length == 0){
							alert("O campo " + texto + " deve ser preenchido corretamente!")
							campo.focus();
							return false;
						}else{
						
							if (regexEmail.test( campo.value ) == false)
							{
								alert(campo.value + " não é um endereço de e-mail válido!")
								campo.focus();
								return false;
							}
						}
						break;
					case "D":
						var date = campo.value;
						if (date.length == 0){
							alert("Atenção!\nO campo " + texto + " deve ser preenchido corretamente.");
							campo.focus();
							return false;
						}else{
							var array_data = new Array;
							var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
							//vetor que contem o dia o mes e o ano
							array_data = date.split("/");
							erro = false;
							//Valido se a data esta no formato dd/mm/yyyy e se o dia tem 2 digitos e esta entre 01 e 31
							//se o mes tem d2 digitos e esta entre 01 e 12 e o ano se tem 4 digitos e esta entre 1000 e 2999
							if ( date.search(ExpReg) == -1 )
								erro = true;
							//Valido os meses que nao tem 31 dias com execao de fevereiro
							else if ( ( ( array_data[1] == 4 ) || ( array_data[1] == 6 ) || ( array_data[1] == 9 ) || ( array_data[1] == 11 ) ) && ( array_data[0] > 30 ) )
								erro = true;
							//Valido o mes de fevereiro
							else if ( array_data[1] == 2 ) {
								//Valido ano que nao e bissexto
								if ( ( array_data[0] > 28 ) && ( ( array_data[2] % 4 ) != 0 ) )
									erro = true;
								//Valido ano bissexto
								if ( ( array_data[0] > 29 ) && ( ( array_data[2] % 4 ) == 0 ) )
									erro = true;
							}
							if ( erro ) {
								alert("O campo " + texto + " está com a data Invalida.");
								campo.focus();
								return false;
							}
						}
					break;
					case "C":
						if (campo.value.length == 0){
							alert('Atenção!\nO campo ' + texto + ' deve ser preenchido corretamente.');
							campo.focus();
							return false;
						}else{
								cpf = campo.value;
								cpf = cpf.replace(".","").replace(".","").replace("-","");
								
								var numeros, digitos, soma, i, resultado, digitos_iguais;
								digitos_iguais = 1;
								if (cpf.length < 11){
									alert("O " + texto + " está incorreto!");
									campo.focus();
									return false;
								}
								for (i = 0; i < cpf.length - 1; i++)
									if (cpf.charAt(i) != cpf.charAt(i + 1))
									{
										digitos_iguais = 0;
										break;
									}
									if (!digitos_iguais)
									{
										numeros = cpf.substring(0,9);
										digitos = cpf.substring(9);
										soma = 0;
										for (i = 10; i > 1; i--)
										  soma += numeros.charAt(10 - i) * i;
										resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
										if (resultado != digitos.charAt(0)){
											alert("O " + texto + " está incorreto!");
											campo.focus();
											return false;
										}
										numeros = cpf.substring(0,10);
										soma = 0;
										for (i = 11; i > 1; i--)
										  soma += numeros.charAt(11 - i) * i;
										resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
										if (resultado != digitos.charAt(1)){
											alert("O " + texto + " está incorreto!");
											campo.focus();
											return false;
										}
										  
										return true;
									}else{
										alert("O " + texto + " está incorreto!");
										campo.focus();
										return false;
									}
							}
						break;
						case "J":
							if (campo.value.length == 0){
								alert("Atenção!\nO campo " + texto + " deve ser preenchido corretamente.");
								campo.focus();
								return false;
							}else{
								
								cnpj = campo.value;
								cnpj = cnpj.replace(".","").replace(".","").replace("/","").replace("-","");
								
								var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
								digitos_iguais = 1;
								if (cnpj.length < 14 && cnpj.length < 15){
									alert("Atenção!\nO " + texto + " está incorreto.");
									campo.focus();
									return false;
								}
								
								for (i = 0; i < cnpj.length - 1; i++)
									if (cnpj.charAt(i) != cnpj.charAt(i + 1))
									{
										digitos_iguais = 0;
										break;
									}
								
								if (!digitos_iguais)
								{
									tamanho = cnpj.length - 2
									numeros = cnpj.substring(0,tamanho);
									digitos = cnpj.substring(tamanho);
									soma = 0;
									pos = tamanho - 7;
									for (i = tamanho; i >= 1; i--)
										  {
										  soma += numeros.charAt(tamanho - i) * pos--;
										  if (pos < 2)
												pos = 9;
										  }
									resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
									if (resultado != digitos.charAt(0)){
										alert("Atenção!\nO " + texto + " está incorreto.")
										return false;
									}
									tamanho = tamanho + 1;
									numeros = cnpj.substring(0,tamanho);
									soma = 0;
									pos = tamanho - 7;
									for (i = tamanho; i >= 1; i--)
										  {
										  soma += numeros.charAt(tamanho - i) * pos--;
										  if (pos < 2)
												pos = 9;
										  }
									resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
									if (resultado != digitos.charAt(1)){
										alert("Atenção!\nO " + texto + " está incorreto.");
										return false;
									}
										return true;
								}else{
									alert("Atenção!\nO " + texto + " está incorreto.");
									campo.focus();
									return false;
								}
							}
						break;
					default:
						break;
				}
			}
			catch (e){
				alert("erro ao enviar: " + e);
				return false;
			}
		}


// Todas os links que contêm a classe urlfn abrem em nova janela
function MM_validateForm() {
//  ---------------------------------------
	if (document.getElementById) {
		var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
		firstField = new Array();
		for (i=0; i<(args.length-2); i+=4) {
			test=args[i+2];
			label = args[i+3];
			val=document.getElementById(args[i]);
			if (val) {
				nm=val.name;
				elInput = val;
				elInput.className = "";
				if ((val=val.value)!="") {
					if (test.indexOf('isEmail')!=-1) {
						p=val.indexOf('@');
						if (p<1 || p==(val.length-1)) {
							errors+='- '+label+' inválido.\n';
							elInput.className = "campoErrado";
							firstField.push(elInput);
						}
					} else if (test!='R') {
						num = parseFloat(val);
						if (isNaN(val)) {
							errors+='- '+label+' deve ser um número válido.\n';
							elInput.className = "campoErrado";
							firstField.push(elInput);
						}
						if (test.indexOf('inRange') != -1) {
							p=test.indexOf(':');
							min=test.substring(8,p);
							max=test.substring(p+1);
							if (num<min || max<num) {
								errors+='- '+label+' deve ser um número entre '+min+' e '+max+'.\n';
								elInput.className = "campoErrado";
								firstField.push(elInput);
							}
						}
					}
				} else if (test.charAt(0) == 'R') {
					errors += '- '+label+' é obrigatório.\n';
					elInput.className = "campoErrado";
					firstField.push(elInput);
				}
			}
		}
		if (errors) {
			alert('Os seguintes erros ocorreram:\n'+errors);
			firstField[0].focus();
		}
		document.MM_returnValue = (errors == '');
	}
}


//AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','name','bg','width','1280','height','1146','id','bg','src','img/swf/bg','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','wmode','transparent','movie','img/swf/bg','fundo' ); //end AC code