// Validações
//CPFCNPJ
/**
 * @author Márcio d'Ávila
 * @version 1.01, 2004
 *
 * 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+/, "");
	return pNum;
} //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 (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '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 (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	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 (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	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
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cartoes
function x_cc(v,m,b,p) {
	type = p;
	ccnum = document.getElementById(v).value;
   if (type == "VISA") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AMEX") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "DINERS") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)){
	alert(m.replace("/n" , "\n"));
	document.getElementById(v).focus();
	document.getElementById(v).style.backgroundColor='#FFFFCC';
	return true
   }
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0){
	   //return false
   }else{
		alert(m.replace("/n" , "\n"));
		document.getElementById(v).focus();
		document.getElementById(v).style.backgroundColor='#FFFFCC';
		return true
	   }
}
// branco
function x_blank(v,m){
	if(document.getElementById(v).value == ""){
	alert(m.replace("/n" , "\n"));
	document.getElementById(v).focus();
	document.getElementById(v).style.backgroundColor='#FFFFCC';
	return true
	}
}
// email
function x_email(v,m,b,f){
		var flag = false;
		el = eval("document."+f.name+"."+v);

	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    var address = el.value;
   if(reg.test(address) == false) {
      //alert('Invalid Email Address');
      flag= true;
   }	
   
   

		if(b == "bok" && el.value == ""){
		flag = false
		}
		if(flag == true){
				alert(m.replace("/n" , "\n"));
				el.focus();
				el.style.backgroundColor='#FFFFCC';
				//document.getElementById(v).focus();
				///document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
		}
		
		
		
		

		
		
		
		
		
		
		
		
		
	
}
// select
function x_select(v,m){
	if(document.getElementById(v).value == ""){
	alert(m.replace("/n" , "\n"));
	document.getElementById(v).focus();
	document.getElementById(v).style.backgroundColor='#FFFFCC';
	return true
	}
}
//CPF
function x_cpf(v,m,b){
	var flag = false;
	if(isCpf(document.getElementById(v).value) == false){
		flag = true;	
	}
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}
}
// so numeros
function x_numero(v,m,b,le){
   var sText = document.getElementById(v).value;
	var flag = false;

	var illegalChars = /\D/;
    if (illegalChars.test(sText) || sText == "" || sText.length < le ) {
       flag = true;
    } 
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}

}
// igual quem
function x_igual(v,m,b,q){
	if((document.getElementById(v).value != document.getElementById(q).value) || (document.getElementById(v).value == "")){
		alert(m.replace("/n" , "\n"));
		document.getElementById(v).focus();
		document.getElementById(v).style.backgroundColor='#FFFFCC';
		return true
	}
}
//data
function x_data(v,m,b){
	var flag = false;
	pattern		= /(((0[1-9]|[12][0-9]|3[01])([/])(0[13578]|10|12)([/])(\d{4}))|(([0][1-9]|[12][0-9]|30)([/])(0[469]|11)([/])(\d{4}))|((0[1-9]|1[0-9]|2[0-8])([/])(02)([/])(\d{4}))|((29)(\.|-|\/)(02)([/])([02468][048]00))|((29)([/])(02)([/])([13579][26]00))|((29)([/])(02)([/])([0-9][0-9][0][48]))|((29)([/])(02)([/])([0-9][0-9][2468][048]))|((29)([/])(02)([/])([0-9][0-9][13579][26])))/;
	var regex = new RegExp( pattern );
	if ( !regex.test( document.getElementById(v).value ) ){
		flag = true;
	}
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}
}
// Dinheiro
function x_dinheiro(v,m,b){
	var pattern	= "^(?:(?:[0-9]{1,3}\.)(?:[0-9]{3}\.)*[0-9]{3}|[0-9]{1,3})(,[0-9]{2})$";
	var regex = new RegExp( pattern );
	if ( !regex.test( document.getElementById(v).value ) ){
		alert(m.replace("/n" , "\n"));
		document.getElementById(v).focus();
		document.getElementById(v).style.backgroundColor='#FFFFCC';
		return true
	}
}
// Decimal
function x_decimal(v,m,b){
	var pattern	= /(^\d*\.\d{2}$)/;
	var regex = new RegExp( pattern );
	if ( !regex.test( document.getElementById(v).value ) ){
		alert(m.replace("/n" , "\n"));
		document.getElementById(v).focus();
		document.getElementById(v).style.backgroundColor='#FFFFCC';
		return true
	}
}
// Alfa
function x_alfa(v,m,b,le){
   var sText = document.getElementById(v).value;
	var flag = false;

	var illegalChars = /\W/;
    if (illegalChars.test(sText) || sText == "" || sText.length < le ) {
       flag = true;
    } 
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}

}
//CNPJ
function x_cnpj(v,m,b){
	var flag = false;
	if(isCnpj(document.getElementById(v).value) == false){
		flag = true;	
	}
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}
}
//CPFCNPJ
function x_cpfcnpj(v,m,b){
	var flag = false;
	if(isCpfCnpj(document.getElementById(v).value) == false){
		flag = true;	
	}
	if(b == "bok" && document.getElementById(v).value == ""){
		flag = false
	}
	if(flag == true){
				alert(m.replace("/n" , "\n"));
				document.getElementById(v).focus();
				document.getElementById(v).style.backgroundColor='#FFFFCC';
				return true
	}
}


function validateForm(f){
	var elem, i = 0
	while ( elem = f.elements[i++] ){ // le todos os elementos do formulario
	
	//alert(elem.name + "----" + elem.alt)

		if(elem.alt != ''  && elem.alt != 'undefined' && elem.alt != null){
				
				oalt = elem.alt;
				oquem = elem.id;
				prop = oalt.split("|");
				otipo = prop[0]; // tipo
				omensagem = prop[1]; // mensagem
				obok = prop[2]; // bok
				opar = prop[3]; // parametro

				document.getElementById(oquem).style.backgroundColor='';

// validando branco///////////////////////////////////////////////////////////
				if(otipo == "blank"){ 
					if(x_blank(oquem,omensagem)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando email////////////////////////////////////////////////////////////
// aceita bok
				if(otipo == "email"){ 
					if(x_email(oquem,omensagem,obok,f)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando select///////////////////////////////////////////////////////////
//				if(otipo == "selecione"){ 
//					if(x_select(oquem,omensagem)) return false; 
//				}
//////////////////////////////////////////////////////////////////////////////

// validando CPF /////////////////////////////////////////////////////////////
// aceita bok
				if(otipo == "cpf"){ 
					if(x_cpf(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Numero //////////////////////////////////////////////////////////
// aceita bok
// aceita tamanho
				if(otipo == "numero"){ 
					if(x_numero(oquem,omensagem,obok,opar)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Igual  //////////////////////////////////////////////////////////
				if(otipo == "igual"){ 
					if(x_igual(oquem,omensagem,obok,opar)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Data   //////////////////////////////////////////////////////////
// aceita bok
				if(otipo == "data"){ 
					if(x_data(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Dinheiro/////////////////////////////////////////////////////////
				if(otipo == "dinheiro"){ 
					if(x_dinheiro(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Decimal//////////////////////////////////////////////////////////
				if(otipo == "decimal"){ 
					if(x_decimal(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Alfa ////////////////////////////////////////////////////////////
// aceita bok
// acetita tamanho
				if(otipo == "alfa"){ 
					if(x_alfa(oquem,omensagem,obok,opar)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando CNPJ ////////////////////////////////////////////////////////////
// aceita bok
				if(otipo == "cnpj"){ 
					if(x_cnpj(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando CPFCNPJ /////////////////////////////////////////////////////////
// aceita bok
				if(otipo == "cpfcnpj"){ 
					if(x_cpfcnpj(oquem,omensagem,obok)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

// validando Cartão de Crédito ///////////////////////////////////////////////
// exemplo alt="cc|Número do cartão inválido||VISA"
				if(otipo == "cc"){ 
					if(x_cc(oquem,omensagem,obok,opar)) return false; 
				}
//////////////////////////////////////////////////////////////////////////////

				prop = "";
		}
	}


return true
//document.getElementById("form1").submit();

}