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 (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



/******************************************/
/* recebe um campo e verifica se o conte?-*/
/* do dele nao esta vazio                 */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validateIsNotEmpty(field){
  //verifica se campo e valor existem
  if(field == null || field.value == null){
    return false;
  }  
  //verifica se o objeto do campo e do valro existem
  //sen?o existir o valor n?o ? campo texto....
  if(field == 'nothing' || field.value == 'nothing'){
    return false;
  }
  //verifica o valor
  var value = field.value;
  if(value.length == 0){
    return false;
  }
  return true;
}
/******************************************/
/* recebe uma string e valida se todos os */
/* membros dela s?o n?meros               */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validate_is_integer(str){
  if(str.length == 0){
    return false;
  }
  var ret = true;
  var tam = str.length;
  for(i=0;i<tam;i++){
    var code = str.charCodeAt(i);
    if(code < 48 || code > 57){
      ret = false;
    }   
  }
  return ret;
}
/******************************************/
/* recebe uma string e valida se ? um     */
/* email v?lido                           */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validate_is_email(str){
  if(str.length == 0){
    return false;
  }
  var pos = str.indexOf("@");
  if(pos == -1){
    return false;
  }
  pos = str.indexOf(".");
  if(pos == -1){
    return false;
  }
  return true;
}
/******************************************/
/* recebe um campo e verifica se o conte?-*/
/* do dele ? um email v?lido              */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validateField_email(field){
  //verifica se campo e valor existem
  if(field == null || field.value == null){
    return false;
  }  
  //verifica se o objeto do campo e do valro existem
  //sen?o existir o valor n?o ? campo texto....
  if(field == 'nothing' || field.value == 'nothing'){
    return false;
  }
  //verifica o valor
  var value = field.value;
  if(value.length == 0){
    return false;
  }
  return validate_is_email(value);  
}
/******************************************/
/* recebe um campo e verifica se o conte?-*/
/* do dele ? num?rico, se est? null e se  */
/* est? vazio                             */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validateField_integer(field){
  //verifica se campo e valor existem
  if(field == null || field.value == null){
    return false;
  }
  //verifica se o objeto do campo e do valro existem
  //sen?o existir o valor n?o ? campo texto....
  if(field == 'nothing' || field.value == 'nothing'){
    return false;
  }
  //verifica o valor
  var value = field.value;
  if(value.length == 0){
    return false;
  }
  return validate_is_integer(value); 
}
/******************************************/
/* recebe um campo e verifica se o conte?-*/
/* do dele ? um telefone no formato:      */
/* DD99999999                             */
/* Retornos:                              */
/*           true / false                 */
/******************************************/
function validateField_telefone_9999999999(field){
  //verifica se campo e valor existem
  if(field == null || field.value == null){
    return false;
  }
  //verifica se o objeto do campo e do valro existem
  //sen?o existir o valor n?o ? campo texto....
  if(field == 'nothing' || field.value == 'nothing'){
    return false;
  }
  //verifica o valor
  var value = field.value;
  if(value.length != 10){
    return false;
  }
  return validate_is_integer(value); 
}

/******************************************/
/* responsavel por formatar o tamanho da  */
/* janela pra 800x600 pixels              */
/******************************************/
function resize()
{
	window.moveTo(0,0);
	window.resizeTo(800,600);  
}
/******************************************/
/* responsavel por fechar a janela        */
/******************************************/
function closeWindow()
{
	window.close();	
}

function validarConteudo(evento, tipo, campo){
	var entrada;
	var navegador = navigator.appName;
	if (navegador.indexOf("Netscape") != -1){
		entrada = String.fromCharCode(evento.which);
	}else{
		entrada = String.fromCharCode(evento.keyCode);
	}
	
	if ((navegador.indexOf("Netscape") != -1) && ((evento.which == 8) || (evento.which == 0))){
		return true;
	}

	if(tipo == "numero"){
		return (validarNumero(entrada));
	}else{
		if( tipo == "float" ){
			if( entrada == "," && campo != null ){
				var indexVirgula =  campo.value.indexOf(",");
				if( indexVirgula != -1 ) {
					return false;
				}
			}else{
				return (validarFloat(entrada));
			}
		}		
		if (tipo == "texto"){
			return (validarTexto(entrada));
		}else{			
			if (tipo == "textoNumerico"){
				return (validarTextoNumerico(entrada));
			}
		}
	}
}

function validarNumero(conteudo){
	var validos = "0123456789";
	var valor = new String(conteudo);
	for (var i = 0; i < valor.length; i++){
		if (validos.indexOf(valor.charAt(i)) == -1)
			return false;
	}
	return true;
}

function validarTexto(conteudo){
	return validarTextoNumero(conteudo, false);
}

function validarTextoNumerico(conteudo){
	return validarTextoNumero(conteudo, true);
}

function validarTextoNumero(conteudo, textoNumerico){
	var valor = String(conteudo);
	var acentosMinusculos = new String("????????????");
	var acentosMaiusculos = new String("????????????");
	var outrosCaracteres = new String("/().,");
	var numerico = new RegExp("[0-9]");
	var texto = new RegExp("[A-Za-z]");
	for (var i = 0; i < valor.length; i++){
		var letra = new String(valor.charAt(i));
		if (letra != " " && !texto.test(letra)){
			if ((acentosMinusculos.indexOf(letra) == -1) && (acentosMaiusculos.indexOf(letra) == -1) && (outrosCaracteres.indexOf(letra) == -1)){
				if (textoNumerico){
					if (!numerico.test(letra)) 
						return false;
				}else 
					return false;                                
			}
		}
	}
	return true;
}

function isAlfaNro(){ 
	var caract = new RegExp(/^[a-z 0-9]+$/i); 
	var caract = caract.test(String.fromCharCode(event.keyCode));

	if(!caract){
    	event.returnValue = false;
	    return true;
	}else{
    	event.returnValue = true;
    	return true;
	}
}

function validaEmail(email) {
	emailRE = new RegExp("^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");
	if (emailRE.test(email)) {
		return true;
	}
	return false;
}

function checkEmail(str)
{
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if ( (str.indexOf(at)==-1) || (str.indexOf(at)==0) || ( (str.indexOf(at)+1)==lstr) ){
		   return false
		}

		if ( (str.indexOf(dot)==-1) || (str.indexOf(dot)==0) || ( (str.indexOf(dot)+1)==lstr) ){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if ( (str.substring(lat-1,lat)==dot) || (str.substring(lat+1,lat+2)==dot) ){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }
		 
		 return true;
				
	}

function formatarData(componente){

	if (componente.value.length == 2) 
	{
		if (!testarDia(componente.value)) 
		{
			componente.value = "";
			componente.focus();
		} 
		else 
		{
			componente.value += '/';
		}
	}
	
	if (componente.value.length == 5) 
	{
		if (!testarMes(componente.value.substring(3,5), componente.value.substring(0,2))) 
		{ 
			componente.value = componente.value.substring(0,3);
			componente.focus();
		} 
		else 
		{
			componente.value += '/';
		}
	}

	if (componente.value.length == 10) 
	{
		if (!testarAno(componente.value.substring(6,10), componente.value.substring(3,5), componente.value.substring(0,2))) 
		{
			componente.value = componente.value.substring(0,5);
			componente.focus();
		}
	}
}

 
function formatarMesAno(componente)
{
	if (componente.value.length == 2) 
	{
		if (!testarMes(componente.value,"01")) 
		{ 
			componente.value = "";
			componente.focus();
		} 
		else 
		{
			componente.value += '/';
		}
	}

	if (componente.value.length == 7) 
	{
		if ( !testarAno(componente.value.substring(3,7), componente.value.substring(0,2),"01") ) 
		{
			componente.value = componente.value.substring(0,3);
			componente.focus();
		}
	}
}


function formatarHorario(componente, componenteFoco)
{
	if (componente.value.length == 2) 
	{
		componente.value += ':';
	}
	else if (componente.value.length == 5) {
			if( componenteFoco != null ) {
				componenteFoco.focus();
			}
		}           

}

function testarDia(dia) 
{
	if (dia <= 0 || dia >= 32) 
	{
		alert("Dia n?o pode ter valor inferior a 01 e superir a 31 !");
		return false;
	}
	return true;
}



function testarMes(mes, dia) 
{
	if (mes < 1 || mes > 12) 
	{
		alert("M?s inv?lido.");
		return false;
	}
	if ((mes == 4 || mes == 6 || mes == 9 || mes == 11 ) && dia > 30) 
	{
		alert("Dia inv?lido para este m?s !");
		return false;
	}
	if ((mes == 2) && dia > 29) 
	{
		alert("Dia inv?lido para este m?s !");
		return false;
	}
	return true;
}

 

function testarAno(ano, mes, dia) 
{
	if (mes == 2) 
	{
		if (dia ==29) 
		{
			if ((ano % 100) == 0)
			{
				if ((ano % 400) != 0) 
				{ 
					alert("O m?s de fevereiro n?o possui dia 29 para este ano !");
					return false;
				}
			}
			else
			{
				if ((ano % 4) != 0) 
				{ 
					alert("O m?s de fevereiro n?o possui dia 29 para este ano !");
					return false;
				}
			}
		}
	}
	return true;
}

function CheckEmail(str){
    if (str == ""){        
        return true
    }
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || (str.indexOf(at)+1)==lstr){
	   return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || (str.indexOf(dot)+1)==lstr){
		return false
	}
	if (str.indexOf(at,(lat+1))!=-1){
		return false
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	}
	if (str.indexOf(dot,(lat+2))==-1){
		return false
	}		
	if (str.indexOf(" ")!=-1){
		return false
	}
	return true					
}
