/*//////////// FORMULÁRIO INTELIGENTE
	A FUNÇÃO ANALISA UMA PROPRIEDADE QUE DEV SER INSERIDA NAS TAGS HTML( VALID ) // <input type='text' valid='V'>
	VALID	= "N"
		VALIDA SE EXISTEM DADOS PREENCHIDOS E SE OS DADOS INSERIDOS NO CAMPO SÃO SOMENTE NÚMEROS, PONTOS OU VIRGULAS
	
	VALID	= "V"
		VALIDA SE O CAMPO FOI PREENCHIDO OU NÃO
	
	VALID = "" OU SIMPLESMENTE NÃO ACHAR A TAG
		NÃO FAZ VALIDAÇÃO

	VALORES DE ENTRADA
	FRM	-> NAME DO FORM A SER ANALISADO
	
	OBS:
		IDENTIFICA AUTOMATICAMENTE SE O NOME DO CAMPO É "email" E FAZ A VERIFICAÇÃO DE EMAIL.
		CASO A VERIFICAÇÃO ESTEJA OK RETORNA TRUE
		CASO CONTRARIO EXIBE MENSAGEM APROPRIADA, DA O FOCU NO CAMPO ONDE OCORREU O ERRO, E RETORNA FALSE
*/
function vldForm(frm)
{
	var form		= eval('document.'+ frm);
	var qtdCampos	= form.length;
	var x;
	
	for(x=0;x<=qtdCampos-1;x++)
	{
		if(form.elements[x].valid != null)
		{
			if(form.elements[x].valid == 'n' || form.elements[x].valid == 'N')
			{
				if(isNaN(form.elements[x].value))
				{
					alert('Por favor preencha os campos corretamente *');
					form.elements[x].focus();
					return(false);
				}
			}
			else
			{
				if(form.elements[x].name.indexOf("email") != -1)
				{
					if(
						form.elements[x].value.indexOf("@") <= 0  ||
						form.elements[x].value.indexOf(".") == -1 ||
						form.elements[x].value.length <= 5
					)
					{
						alert('E-mail Inválido *');
						form.elements[x].focus();
						return(false)
					}
				}
				else if(form.elements[x].value == '' || form.elements[x].value == ' ')
				{
					alert('Por favor preencha os campos obrigatórios *');
					form.elements[x].focus();
					return(false);
				}
			}
		}
	}
	
	return(true);
}

/*
FUNÇÃO MONTA COMBO

PARAMETROS
	INICIO		-> Número inicial da comboBox
	FIM			-> Número final da comboBox
	NOME		-> Nome do campo
	COMPLEMENTO	-> Escrve o complemente como código
*/
function montaCombo(inicio,fim,nome,complemento)
{
	var x;
	inicio	= parseInt(inicio);
	fim		= parseInt(fim);

	document.write("<select name='"+ nome +"' id='"+ nome +"' "+ complemento +">");
		if(fim >= inicio)
		{
			for(x=inicio;x<=fim;x++)
			{
				document.write("<option value='"+ x +"'>"+ x +"</option>");
			}
		}
		else
		{
			for(x=inicio;x<=fim;x--)
			{
				document.write("<option value='"+ x +"'>"+ x +"</option>");
			}
		}
	document.write("</select>");
}

function comboData(nomeCampo,complemento,sDia,sMes,sAno){
	
	var anoInicial, anoAtual, data, dataAtual, anosMais, marcar, x, y, nomeCampo, Sdia, Smes, Sano, edicao, retorno;

			data = new Date();
			anoInicial = 1910;
			dataAtual = data.getDate() +'/'+ data.getMonth() +'/'+ data.getFullYear();
			anoAtual = data.getFullYear();
			anosMais = parseInt(anoAtual)+3;
			edicao = false;
			retorno	= "";

				if(sDia == undefined && sMes == undefined && sAno == undefined)
				{
					sDia	= data.getDate();
					sMes	= (data.getMonth())+1;
					sAno	= data.getFullYear();
				}
			//==================== DIA ====================>
			for(x=1;x<=31;x++){// Escrevendo o Combo com os Dias
				if(x == 1){
					retorno += "<select id='"+ nomeCampo +"cbDia' onChange=\"document.getElementById('"+ nomeCampo +"').value = document.getElementById('"+ nomeCampo +"cbDia').value +'/'+ document.getElementById('"+ nomeCampo +"cbMes').value +'/'+ document.getElementById('"+ nomeCampo +"cbAno').value;\" style='width:40px' "+ complemento +">";
				}
				if(x <= 9){
					y = "0"+ x;
				}
				else{
					y = x;
				}
					if(parseInt(sDia) == parseInt(y)){
						marcar = " selected";
					}
					else{
						marcar = "";
					}
				retorno += "<option value='"+ y +"'"+ marcar +">"+ y +"</option>";
				if(x == 31){
					retorno += "</select> / ";
				}
			}
			//==================== MES ====================>
				for(x=1;x<=12;x++){//Escrevendo o Combo com os Meses;
					if(x == 1){
						retorno += "<select id='"+ nomeCampo +"cbMes' onChange=\"document.getElementById('"+ nomeCampo +"').value = document.getElementById('"+ nomeCampo +"cbDia').value +'/'+ document.getElementById('"+ nomeCampo +"cbMes').value +'/'+ document.getElementById('"+ nomeCampo +"cbAno').value;\" style='width:40px' "+ complemento +">";
					}
					if(x <= 9){
						y = "0"+ x;
					}
					else{
						y = x;
					}
					
						if(parseInt(sMes) == parseInt(y)){
							marcar = " selected";
						}
						else{
							marcar = "";
						}
					retorno += "<option value='"+ y +"'"+ marcar +">"+ y +"</option>";
					if(x == 12){
						retorno += "</select> / ";
					}
				}
			//==================== ANO ====================>
			for(x=anoInicial;x<=anosMais;x++){
				if(x == anoInicial){
					retorno += "<select id='"+ nomeCampo +"cbAno' onChange=\"document.getElementById('"+ nomeCampo +"').value = document.getElementById('"+ nomeCampo +"cbDia').value +'/'+ document.getElementById('"+ nomeCampo +"cbMes').value +'/'+ document.getElementById('"+ nomeCampo +"cbAno').value;\" style='width:60px' "+ complemento +">";
				}

					if(sAno == x){
						marcar = " selected";
						edicao = true;
					}
					else{
						if(x == anoAtual && edicao == false){
							marcar = " selected";
						}
						else{
							marcar = "";
						}
					}

				retorno += "<option value='"+ x +"'"+ marcar +">"+ x +"</option>";
				if(x == anosMais){
					retorno += "</select>";
				}				
			}
		//================== HIDDEN COM  O VALOR DA DATA ======================>
		retorno += " <input type='hidden' name='"+ nomeCampo +"' id='"+ nomeCampo +"' value='"+ sDia +"/"+ sMes +"/"+ sAno +"'>";
		
		return(retorno);
}

//FUNÇÃO QUE APENAS DEIXA DIGITAR NÚMEROS PONTOS E VÍRGULAS
function somenteNumeros() // PARA EVENTO OnKeyDown
{
	var Tecla = window.event.keyCode;
if (!(	(Tecla > 95 && Tecla < 106) || 
	(Tecla > 44 && Tecla < 58) 		|| 
		(Tecla > 32 && Tecla < 41)  ||
			(
			Tecla == 17  ||
			Tecla == 16  ||
			Tecla == 8   || 
			Tecla == 9   || 
			Tecla == 13  ||
			Tecla == 144 ||
			Tecla == 188 ||
			Tecla == 190 ||
			Tecla == 110 ||
			Tecla == 194 
			)
		)
	)
{window.event.returnValue = false;}
}

function somenteNumeros2() // PARA EVENTO OnKeyDown
{
	var Tecla = window.event.keyCode;
if (!(	(Tecla > 95 && Tecla < 106) || 
	(Tecla > 44 && Tecla < 58) 		|| 
		(Tecla > 32 && Tecla < 41)  ||
			(
			Tecla == 17  ||
			Tecla == 16  ||
			Tecla == 8   || 
			Tecla == 9   || 
			Tecla == 13  ||
			Tecla == 144
			)
		)
	)
{window.event.returnValue = false;}
}

function MascaraCPF(Obj,Opcao)
{var KeyCod = window.event.keyCode;
 //PARA EVENTO ONBLUR / ONKEYUP
 if(Opcao == 0 && ((!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)) && ((KeyCod > 47 && KeyCod < 58) || (KeyCod > 95 && KeyCod < 106))) || (KeyCod == 0)) || (RetornaNumeros(Obj.value).length == 11 && (!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)))))
	{
	var NovoTexto = '';
	 var TextoAntigo = RetornaNumeros(Obj.value)
	 if(TextoAntigo.length > 11)
		{TextoAntigo = TextoAntigo.substr(0,11)}
	 for(Pos=0; Pos<TextoAntigo.length; Pos++)
		{NovoTexto+= TextoAntigo.substr(Pos,1)
		 if(NovoTexto.length == 3 || NovoTexto.length == 7)
			{NovoTexto+= '.'}
		 if(NovoTexto.length == 11) 
			{NovoTexto+= '-'}
		}
	 Obj.value = NovoTexto
	}
}

function MascaraCEP(Obj,Opcao)
{var KeyCod = window.event.keyCode;
 //PARA EVENTO ONBLUR / ONKEYUP	
 if(Opcao == 0 && ((!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)) && ((KeyCod > 47 && KeyCod < 58) || (KeyCod > 95 && KeyCod < 106))) || (KeyCod == 0)) || (RetornaNumeros(Obj.value).length == 8 && (!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)))))
	{var NovoTexto = '';
	 var TextoAntigo = RetornaNumeros(Obj.value)
	 if(TextoAntigo.length > 8)
		{TextoAntigo = TextoAntigo.substr(0,8)}
	 for(Pos=0; Pos<TextoAntigo.length; Pos++)
		{NovoTexto+= TextoAntigo.substr(Pos,1)
		 if(NovoTexto.length == 5)
			{NovoTexto+= '-'}
		}
	 Obj.value = NovoTexto
	}
}

function RetornaNumeros(Texto){
var CharPego = new RegExp("[^0-9]","gi")
var NovoTexto= Texto.replace(CharPego,'')
	return NovoTexto
}
/*
function modulo11(valor)
{
	var dc = 0, Res = 0;
	for(dc=0; dc<=(valor.length-1); dc++) Res +=(valor.substr(dc, 1) * (dc));
	Res%=11;
	return (Res==10)?0:Res;
}
*/
function isCPF(CPF){
	CPF = CPF.replace(/[^0-9]/g,"");
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
        //alert('Correto');
	return true;
	/*
	if(isNaN(CPF)) return false;
	if(CPF=='') return false;
	if(CPF.length!=11) return false;
	cCPF = CPF.substr(0, 10);
	cCPF += modulo11(cCPF);
	return (cCPF==CPF);
	*/
}

function isSenha(){
	if(document.form.senha.value != document.form.csenha.value){
		alert('Senha e confirma senha não conferem !');
		return(false);
	}else{
		return(true);
	}
}

function validaCNPJ() {
	CNPJ = document.form.cnpj.value;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\nEx: 00.000.000/0000-00\n\n"; 
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\nEx: 00.000.000/0000-00\n\n";
	}
	//substituir os caracteres que não são números
	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 += "A verificação de CNPJ suporta apenas números! \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 FormataCNPJ(Campo, teclapres){

	var tecla = teclapres.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);
		if (tam >= 6 && tam < 9)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		if (tam >= 9 && tam < 13)
			Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		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);
		}
}