/* ############################# VALIDAO DO FORMULRIO ####################################### 
acao_submit = Se objetivo for o submit defina como TRUE, ou FALSE caso contrario.
ver_especial = true, false;
ver_campo = campo1###campo2###campo3;
ver_tipo = tipo1###tipo2###tipo3;
tipos validos: 
	mac = validao de mac address
	ip = validao de endereo ip
	numerico = numerico;
	cpf
	cnpj
#####*/

/**
* ER�s
*/
var __erEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var __erNumerico = /^[0-9]*$/;


function validaNumero(string) {
	var strValidos = "0123456789";
	
	if (strValidos.indexOf(string) == -1 ) {
		 return false;
	}
	return true;	
}

function validaFloat(string) {
	var strValidos = "0123456789.,";
	
	if (strValidos.indexOf(string) == -1 ) {
		 return false;
	}
	return true;	
}

	
function mascaraMoeda(campo, event, tammax) {

	var e = event;
	var tecla= e.keyCode || e.which;
	var key = String.fromCharCode(tecla);	
	var vr = $F(campo);
	
	if (!validaNumero(key)) {
		if (tecla != 9 &&  tecla != 13 && tecla != 8) {
			Event.stop(event);
			return vr;
		}
	}
	
	tammax = tammax || 10;
	
	valorFinal = vr;
	
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( "/", "" );
	vr = vr.toString().replace( ",", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	vr = vr.toString().replace( ".", "" );
	tam = vr.length;
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1; }
	
	if (tecla == 8 ){ tam = tam - 1; }
	
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
			valorFinal = vr; }
			
		if ( (tam > 2) && (tam <= 5) ) {
		valorFinal = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); }
		
		if ( (tam >= 6) && (tam <= 8) ){
		valorFinal = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
		
		if ( (tam >= 9) && (tam <= 11) ){
		valorFinal = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
		
		if ( (tam >= 12) && (tam <= 14) ){
		valorFinal = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); }
		
		if ( (tam >= 15) && (tam <= 17) ){
		valorFinal = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );}
		
	}
	
	return valorFinal;
}

function validar(form, acao_submit, ver_especial, ver_campo, ver_tipo, ver_senha, campo_senha1, campo_senha2) {
	var frm = form; //eval("document." + form);
	
	if (ver_senha) {
		senha1 = eval("frm." + campo_senha1);
		senha2 = eval("frm." + campo_senha2);
		if (senha1.value != senha2.value) {
			alert("Campos de senha estao diferentes");
			senha1.focus();
			return false;
		} else if (senha1.value.length < 6 && senha1.value != '') {
			alert("Senha deve ter no m�nimo 6 caracteres");
			senha1.focus();
			return false;
		}
	}
	
	if (ver_especial) {
		ver_campo_arr = new Array();
		ver_tipo_arr = new Array();
		
		ver_campo_arr = ver_campo.split("###");
		ver_tipo_arr = ver_tipo.split("###");
	}

	for (i = 0; i < frm.length ; i++) {
		if (!frm[i].disabled == true) {
			if (frm[i].type == 'text' || frm[i].type == 'password') {
				if (frm[i].value == '') {
					if (frm[i].title != 'NULL' && frm[i].alt != 'NULL') {
						alert("O preenchimento do campo: " + frm[i].title + " � obrigat�rio");
						frm[i].focus();
						return false;
					}
				} else if(ver_especial) {
					
					for (var i2 = 0 ; i2 <= ver_campo_arr.length ; i2++) {
						
						if (frm[i].name == ver_campo_arr[i2]) {
							if (ver_tipo_arr[i2] == 'mac') {
								seek = /([A-F0-9]{2}[-:]){5}[A-F0-9]{2}/
								if (!seek.exec(frm[i].value)) {
									alert("Endere�o de MAC invalido");
									frm[i].focus();
									return false;
								}
								//alert('mac verificacao');
							} else if (ver_tipo_arr[i2] == 'ip') {
								if (frm[i].value != '0/0') {
								seek = /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/
									//seek = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)([0-9/]{0,2})$/
									//seek = /^(([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5])\.([01]?\d?\d|2[0-4]\d|25[0-5]))([0-9/]){0,3}$/
									
									if (!seek.exec(frm[i].value)) {
										alert("Endere�o de IP invalido");
										frm[i].focus();
										return false;
									}
								}
							} else if (ver_tipo_arr[i2] == 'numerico') {
								seek = /^[0-9:]*$/
								if (!seek.exec(frm[i].value)) {
									alert("Por favor, digite um valor num�rico no campo: " + frm[i].name);
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'espaco') {
								seek = /^[a-zA-Z0-9._-]*$/
								if (!seek.exec(frm[i].value)) {
									alert("O campo " + frm[i].name + " n�o pode conter espa�os ");
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'email') {
								seek = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
								if (!seek.exec(frm[i].value)) {
									alert("Email invalido");
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'cpf') {
								if (!isCpf(frm[i].value)) {
									alert("CPF invalido");
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'cnpj') {
								if (!isCnpj(frm[i].value)) {
									alert("CNPJ invalido");
									frm[i].focus();
									return false;
								}
							}
						}
					}
				}
			} else if (frm[i].type == 'select-one') {
				if (frm[i].title != 'NULL' && frm[i].alt != 'NULL') {
					if (frm[i].value == '') {
						alert('Por favor, selecione um valor no campo: ' + frm[i].title);
						frm[i].focus();
						return false;
					}
				}
			}
		} // endif do disabled
	}
	
	if (!acao_submit) {
		retorno_validacao(form);
		return false;
	} else {
		return true;
	}
}

/* ##########################################################################################################################
#											FIM DA VALIDAO DE FORMULRIO 													#
###########################################################################################################################*/

/**
 * @author M�rcio d'�vila
 * @version 1.02, 2004-2007
 * http://www.mhavila.com.br/topicos/web/cpf_cnpj.html
 *
 * Licenciado sob os termos da licen�a Creative Commons,
 * Atribui��o - Compartilhamento pela mesma licen�a 2.5:
 * http://creativecommons.org/licenses/by-sa/2.5/br/
 *
 * PROT�TIPOS:
 * m�todo String.lpad(int pSize, char pCharPad)
 * m�todo String.trim()
 *
 * String unformatNumber(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */


var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona m�todo lpad() � classe String.
 * Preenche a String � esquerda com o caractere fornecido,
 * at� que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona m�todo trim() � classe String.
 * Elimina brancos no in�cio e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formata��o e zeros � esquerda da string
 * de n�mero fornecida.
 * @param String pNum
 *      String de n�mero fornecida para ser desformatada.
 * @return String de n�mero desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * � esquerda se necess�rio e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 *      String fornecida para ser formatada.
 * @param boolean pUseSepar
 *      Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 *      Indica se a string fornecida � um CNPJ.
 *      Caso contr�rio, � CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 d�gitos verificadores para o n�mero-efetivo pEfetivo de
 * CNPJ (12 d�gitos) ou CPF (9 d�gitos) fornecido. pIsCnpj � booleano e
 * informa se o n�mero-efetivo fornecido � CNPJ (default = false).
 * @param String pEfetivo
 *      String do n�mero-efetivo (SEM d�gitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida � de um CNPJ.
 *      Caso contr�rio, � CPF. Default = false (CPF).
 * @return String com os dois d�gitos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (indice = calculado.length-1; indice >= 0; indice--)
		{
			soma += (calculado.charAt(indice) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida � um CPF v�lido.
 * Qualquer formata��o que n�o seja algarismos � desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF v�lido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida d�gitos verificadores
	if (numero != base + digitos) return false;

	/* N�o ser�o considerados v�lidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (indice=1; algUnico && indice<NUM_DIGITOS_CPF; indice++)
	{
		algUnico = (numero.charAt(indice-1) == numero.charAt(indice));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida � um CNPJ v�lido.
 * Qualquer formata��o que n�o seja algarismos � desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ v�lido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida d�gitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* N�o ser�o considerados v�lidos os CNPJ com os seguintes n�meros B�SICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (indice=1; algUnico && indice<NUM_DGT_CNPJ_BASE; indice++)
	{
		algUnico = (numero.charAt(indice-1) == numero.charAt(indice));
	}
	if (algUnico) return false;

	/* N�o ser� considerado v�lido CNPJ com n�mero de ORDEM igual a 0000.
	 * N�o ser� considerado v�lido CNPJ com n�mero de ORDEM maior do que 0300
	 * e com as tr�s primeiras posi��es do n�mero B�SICO com 000 (zeros).
	 * Esta cr�tica n�o ser� feita quando o no B�SICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000" || parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


/**
 * Testa se a String pCpfCnpj fornecida � um CPF ou CNPJ v�lido.
 * Se a String tiver uma quantidade de d�gitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formata��o que n�o seja algarismos � desconsiderada.
 * @param String pCpfCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ v�lido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj

