/* ############################# 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
#####*/

/**
* ERs
*/
var __erEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var __erNumerico = /^[0-9]*$/;
var __erIp = /\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/;


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 inválido");
									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 inválido");
										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 inválido");
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'cpf') {
								if (!isCpf(frm[i].value)) {
									alert("CPF inválido");
									frm[i].focus();
									return false;
								}
							} else if (ver_tipo_arr[i2] == 'cnpj') {
								if (!isCnpj(frm[i].value)) {
									alert("CNPJ inválido");
									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 Mrcio dvila
 * @version 1.02, 2004-2007
 * http://www.mhavila.com.br/topicos/web/cpf_cnpj.html
 *
 * Licenciado sob os termos da licena Creative Commons,
 * Atribuio - Compartilhamento pela mesma licena 2.5:
 * http://creativecommons.org/licenses/by-sa/2.5/br/
 *
 * PROTTIPOS:
 * mtodo String.lpad(int pSize, char pCharPad)
 * mtodo 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 mtodo 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 mtodo trim()  classe String.
 * Elimina brancos no incio e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formatao e zeros  esquerda da string
 * de nmero fornecida.
 * @param String pNum
 *      String de nmero fornecida para ser desformatada.
 * @return String de nmero 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 necessrio 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 contrrio,  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 dgitos verificadores para o nmero-efetivo pEfetivo de
 * CNPJ (12 dgitos) ou CPF (9 dgitos) fornecido. pIsCnpj  booleano e
 * informa se o nmero-efetivo fornecido  CNPJ (default = false).
 * @param String pEfetivo
 *      String do nmero-efetivo (SEM dgitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida  de um CNPJ.
 *      Caso contrrio,  CPF. Default = false (CPF).
 * @return String com os dois dgitos 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 vlido.
 * Qualquer formatao que no seja algarismos  desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF vlido.
 */
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 dgitos verificadores
	if (numero != base + digitos) return false;

	/* No sero considerados vlidos 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 vlido.
 * Qualquer formatao que no seja algarismos  desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ vlido.
 */
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 dgitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* No sero considerados vlidos os CNPJ com os seguintes nmeros BSICOS:
	 * 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;

	/* No ser considerado vlido CNPJ com nmero de ORDEM igual a 0000.
	 * No ser considerado vlido CNPJ com nmero de ORDEM maior do que 0300
	 * e com as trs primeiras posies do nmero BSICO com 000 (zeros).
	 * Esta crtica no ser feita quando o no BSICO 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 vlido.
 * Se a String tiver uma quantidade de dgitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatao que no seja algarismos  desconsiderada.
 * @param String pCpfCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ vlido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj
