// P O R T A L D L L  J A V A S C R I P T  'U T I L S'

////////////////////////////////////// FUNCOES APROVE INICIO

function janelaTelaCheia(nomejanela, endereco)
{
	var leftdist = 0;
	var topdist = 0;
	var winwidth = window.screen.availWidth - leftdist;
	var winheight = window.screen.availHeight - topdist;
	var janela = window.open("", nomejanela, "left="+leftdist+",top="+topdist+",width=1,height=1,toolbar=no,status=yes,resizable=yes");
	janela.resizeTo(winwidth, winheight);
	janela.location = endereco;
}

//************************************** Funções de aviso "onBlur" e "onChange"
function limitaTextarea(txtarea, tamanho)
{
	if (txtarea.value.length > tamanho){
		txtarea.value = txtarea.value.substr(0, tamanho);
		alert("Tamanho máximo de "+tamanho+" caracteres.");
	}
}

function checa_data(campo_id)
{
	var campo = document.getElementById(campo_id);
	if ((campo.value != "") && !(validaData(campo.value))) {
			alert("Data inválida!");
			campo.value = "";
	} else {
			if (parseInt(campo.value.substr(6)) > hoje.getFullYear()) {
				alert("Data inválida!");
				campo.value = "";
			} else if (parseInt(campo.value.substr(6)) < 1900) {
				alert("Data inválida!");
				campo.value = "";
			}
	}
}

function checa_data_com_limite(campo, no_anos)
{
	if ((campo.value != "") && !(validaData(campo.value))) {
			alert("Data inválida!");
			campo.value = "";
	} else {
			var docampo = Date.parse(campo.value);
               var dehoje = Date.UTC(hoje.getFullYear(), hoje.getMonth(), hoje.getDate());
               if ((docampo - dehoje) > Date.parse("January 2, " + (1970+no_anos))) {
				alert("Data inválida!");
				campo.value = "";
			} else if (parseInt(campo.value.substr(6)) < 1900) {
				alert("Data inválida!");
				campo.value = "";
			}
	}
}

function checa_ano(campo)
{
	if (campo.value != "") {
		if ((campo.value < 1900) || (campo.value > hoje.getFullYear())) {
			alert("Ano inválido!");
			campo.value = ""; 
		}
	}
}

function checa_ano_modelo(campo)
{
	if (campo.value != "") {
		if ((campo.value < 1900) || (campo.value > hoje.getFullYear()+1)) {
			alert("Ano inválido!");
			campo.value = ""; 
		}
	}
}

function checa_ano_cultura(campo)
{
	if (campo.value != "") {
		if ((campo.value < 1900) || (campo.value > (hoje.getFullYear() + 50))) {
			alert("Ano inválido!");
			campo.value = ""; 
		}
	}
}

function checa_mes(campo)
{
	if (campo.value != "") {
		if ((campo.value < 1) || (campo.value > 12)) {
			alert("Mês inválido!");
			campo.value = "";
		}
	}
}

function checa_mes_ano_arrendamento(campo)
{
	var mestemp = parseFloat(campo.value.substr(0,2));
	var anotemp = parseFloat(campo.value.substr(3));
	if ((mestemp < 1) || (mestemp > 12)) {
		alert("Mês inválido!");
		campo.value = "";
	}
	else if (anotemp > (parseInt(hoje.getFullYear()) + 50)) {
		alert("Ano inválido!");
		campo.value = "";
	}
	else if (anotemp < 1900) {
		alert("Ano inválido!");
		campo.value = "";
	}
}

function checa_cnpj(campo)
{
		if (!(isCnpj(campo.value))) {
			alert("CNPJ inválido!");
			campo.value = "";
		}
}

function checa_cpf(campo)
{
		if (!(isCpf(campo.value))) {
			alert("CPF inválido!");
			campo.value = "";
		}
}

function checa_cpf_cnpj(campo)
{
		if (!(isCnpj(campo.value))) {
			if (!(isCpf(campo.value))) {
				alert("CPF/CNPJ inválido!");
				campo.value = "";
			}
		}
}

function checa_porcentagem(camponome)
{	
	var campo = document.getElementById(camponome);
	var completadecimal = "";
	
	for(i=0; i < campo.getAttribute("casasdecimais"); i++)
		completadecimal += "0";
	
	var temp = campo.value.replace(",",".");
	if (parseInt(temp) > 100) {
		campo.value = "100," + completadecimal;
	}
}
//**********************************************************************

function formataDeRealParaJs(val)
{ 
	return val.replace(/\./g,"").replace(/,/g,"."); 
}

function ServerURLDecode(str)
{
	return unescape(str.replace(/\+/g, " "));
}

//************************************************ ALGUMAS FUNCOES DE BUSCA
function excluiOptionDeSelect(campoId, valor)
{
	var valarray = new Array();
	valarray.push(valor);
	var indice = buscaEmSelect(campoId, valarray);
	if (indice != null) {
		var combo = document.getElementById(campoId);
		combo.options[indice] = null;
	}
}

function buscaEmSelect(campoId, valores)
{
	var combo = document.getElementById(campoId);
	var indice = null;
	
	for (i = 0; i < combo.length; i++) {
		if (isInArray(combo.options[i].value, valores)) {
			indice = i;
			break;
		}
	}
	
	return indice;
}

function buscaEmInputsDinamicos(nomeCampo, nroCampos, valores)
{
	var campo;
	var indice = null;
	var contaIndice = 1;
	var contaCamposValidos = 0;
		
	while ((contaCamposValidos < nroCampos) && (contaIndice < 100))
	{
		campo = document.getElementById(nomeCampo + "." + contaIndice);
		if (campo != null)
		{
			if (isInArray(campo.value, valores))
			{
				indice = contaIndice;
				break;
			}
			contaCamposValidos++;
		}
		contaIndice++;
	}
	
	return indice;
}

//************************************** Antigo "cpf_cnpj.js"
/**
 * @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)
 */


NUM_DIGITOS_CPF  = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;
NUM_DIGITOS_INSCRICAOESTADUAL = 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 Inscricao Estadual, adicionando zeros
 * à esquerda se necessário e caracteres separadores, conforme solicitado.
 * @param String pInscricaoEstadual
 * 	String fornecida para ser formatada.
 * @param boolean pUseSepar
 * 	Indica se devem ser usados caracteres separadores (. - /).
 * @return String de InscricaoEstadual devidamente formatada.
 */
function formatInscricaoEstadual(pInscricaoEstadual, pUseSepar)
{
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = NUM_DIGITOS_INSCRICAOESTADUAL
	var numero = unformatNumber(pInscricaoEstadual);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	reInscricaoEstadual = /(\d{2})(\d{3})(\d{2})(\d{1})$/;
	numero = numero.replace(reInscricaoEstadual, "$1.$2.$3-$4");
	
	return numero;
} //formatInscricaoEstadual


/**
 * 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

/**
 * 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 dvInscricaoEstadual(pEfetivo)
{
	var result = 0;
	var soma = 0;
	var resto = 0;
	
	soma = pEfetivo.charAt(0) * 2;			
	soma += pEfetivo.charAt(1) * 7;			
	soma += pEfetivo.charAt(2) * 6;			
	soma += pEfetivo.charAt(3) * 5;			
	soma += pEfetivo.charAt(4) * 4;			       
	soma += pEfetivo.charAt(5) * 3;			
	soma += pEfetivo.charAt(6) * 2;					
	
	resto = soma % 11;					
	if (resto <= 1){				
		result = 0;
	}else{				
		result = 11-resto;
	}		

	return result;
} //dvInscricaoEstadual


/**
 * 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


/**
 * APENAS PARA O ESTADO DO RIO DE JANEIRO
 * Testa se a String pInscricaoEstadual fornecida é um IE válido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pInscricaoEstadual
 * 	String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um IE válido.
 */
function isInscricaoEstadual(pInscricaoEstadual)
{
	var numero = formatInscricaoEstadual(pInscricaoEstadual, false);
	var base = numero.substring(0, numero.length - 1);
	var digito = dvInscricaoEstadual(base);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digito) return false;

	/* Não serão considerados válidos os seguintes CPF:
	 * 00.000.000-0, 11.111.111-1, 22.222.222-2, 33.333.333-3, 44.444.444-4,
	 * 55.555.555-5, 66.666.666-6, 77.777.777-7, 88.888.888-8, 99.999.999-9.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_INSCRICAOESTADUAL; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isInscricaoEstadual
//*******************************************************************

//************************************** Antigo "mascaras.js"
Mascaras = {
IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
AZ: /[A-Z]/i,
Acentos: /[À-ÿ]/i,
Num: /[0-9]/,
carregar: function(parte){
 var Tags = ['input','textarea'];
 if (typeof parte == "undefined") parte = document;
 for(var z=0;z<Tags.length;z++){
  Inputs=parte.getElementsByTagName(Tags[z]);
  for(var i=0;i<Inputs.length;i++)
   if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
    this.aplicar(Inputs[i]);
 }
},
aplicar: function(campo){
 tipo = campo.getAttribute('tipo');
 if (!tipo || campo.type == "select-one") return;
 orientacao = campo.getAttribute('orientacao');
 mascara = campo.getAttribute('mascara');
 jsexec = campo.getAttribute('jsexec');
 if (tipo.toLowerCase() == "decimal"){
  orientacao = "esquerda";
  casasdecimais = campo.getAttribute('casasdecimais');
  tamanho = campo.getAttribute('maxLength');
  if (!tamanho || tamanho > 50) tamanho = 10;
  if (!casasdecimais) casasdecimais = 2;
  campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
  campo.setAttribute("tipo", "numerico");
  campo.setAttribute("orientacao", orientacao);
  campo.setAttribute("jsexec", jsexec);
  campo.onblur = function(e){ Mascaras.onblur(e?e:event, campo) };
  campo.onfocus = function(e){ Mascaras.guardaValor(campo) };
 }
 if (orientacao && orientacao.toLowerCase() == "esquerda") 
 {
    campo.style.textAlign = "right";
    campo.style.paddingRight = "1px";
 }
 if (mascara) campo.setAttribute("maxLength", mascara.length);
 if (tipo){
  campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
  campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
 }
 campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
 
 this.aplicarMascara(campo, campo.value);
},
onkeypress: function(e){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 campo =  this.IsIE ? event.srcElement : e.target;
 readonly = campo.getAttribute('readonly');
 if (readonly) return;
 maxlength = campo.getAttribute('maxlength');
 pt = campo.getAttribute('pt');
 selecao = this.selecao(campo);
 if (selecao.length > 0 && KeyCode != 0){
  campo.value = ""; 
  Char = String.fromCharCode(KeyCode);
  tipo = campo.getAttribute('tipo').toLowerCase();
  if (tipo == "numerico" && Char.search(this.Num) == -1) {
  	return false;
  }
  else {
  	return true;
  }
 }
 if (KeyCode == 0) return true;
 Char = String.fromCharCode(KeyCode);
 valor = campo.value;
 mascara = campo.getAttribute('mascara');
 if (KeyCode != 8){
  tipo = campo.getAttribute('tipo').toLowerCase();
  negativo = campo.getAttribute('negativo');
  if(negativo && KeyCode == 45){
   snegativo = campo.getAttribute('snegativo');
   snegativo = (snegativo == "s" ? "n" : "s");
   campo.setAttribute("snegativo", snegativo);
  }else{
   valor += Char
   if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
   if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
  }
 }
 if (mascara){
  this.aplicarMascara(campo, valor);
  return false;
 }
 return true;
},
onkeyup: function(e, campo){
 KeyCode = this.IsIE ? event.keyCode : e.which;
 if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
  valor = campo.value;
  if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
  this.aplicarMascara(campo, valor);
 }
},
onblur: function(e, campo){
 var retorno = "";
 var i = 0;
 var decimais = campo.getAttribute("casasdecimais");
 if ((campo.value.length > 0) && (campo.value.length <= decimais)) {
   for (i=campo.value.length; i < decimais; i++){
     retorno += "0";
   }
   retorno = "0," + retorno + campo.value;
   campo.value = retorno;
 }
 this.executarEspecial(campo);
 return true;
},
aplicarMascara: function(campo, valor){
 //alert(campo.name);
 mascara = campo.getAttribute('mascara');
 if (!mascara) return;
 negativo = campo.getAttribute('negativo');
 snegativo = campo.getAttribute('snegativo');
 if (negativo && valor.substr(0,1) == "-") 
  valor = valor.substr(1,valor.length-1);
 orientacao = campo.getAttribute('orientacao');
 var i = 0;
 for(i=0;i<mascara.length;i++){
  caracter = mascara.substr(i,1);
  if (caracter != "#") valor = valor.replace(caracter, "");
 }
 retorno = "";
 if (orientacao != "esquerda"){
  contador = 0;
  for(i=0;i<mascara.length;i++){
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno += valor.substr(contador,1);
    contador++;
   }else
    retorno += caracter;
   if(contador >= valor.length) break;
  }
 }else{
  contador = valor.length-1;
  for(i=mascara.length-1;i>=0;i--){
   if(contador < 0) break;
   caracter = mascara.substr(i,1);
   if (caracter == "#"){
    retorno = valor.substr(contador,1) + retorno;
    contador--;
   }else
    retorno = caracter + retorno;
  }
 }
 if (negativo && snegativo == "s")
  retorno = "-" + retorno;
 campo.value = retorno;
},
geraMascaraDecimal: function(tam, decimais){
 var retorno = ""; var contador = 0; var i = 0;
 decimais = parseInt(decimais);
 for (i=0;i<(tam-(decimais+1));i++){
  retorno = "#" + retorno;
  contador++;
  if (contador == 3){
   retorno = "." + retorno;
   contador=0;
  }
 }
 retorno = retorno + ",";
 for (i=0;i<decimais;i++) retorno += "#";
 return retorno;
},
selecao: function(campo){
 if (this.IsIE)
  return document.selection.createRange().text;
 else
  return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
},
formataValor: function (valor, decimais){
 valor = valor.split('.');
 if (valor.length == 1) valor[1] = "";
 for(var i=valor[1].length;i<decimais;i++)
  valor[1] += "0"; 
 valor[1] = valor[1].substr(0,2);
 return (valor[0] + "." + valor[1]);
},
executarEspecial: function (campo){
	funcao = campo.getAttribute('jsexec');
	if (funcao) {
		valorguardado = campo.getAttribute('valorguardado');
		if (campo.value != valorguardado) eval(funcao);
	}
},
guardaValor: function (campo){
	campo.setAttribute('valorguardado', campo.value);
}
};
//*************************************************************

//************************************** Antigo "validacao.js"
function checkField(object,array)
{
  if(isInArray(object.name, array))
	{
	  if (object.value == "")
		{
			object.className="notNull";
		}
		else
		{
			object.className = "null";
		}		
	}
	else
	{
		object.className= "null";
	}
}

function isInArray(value,array)
{  
  var notNull = false;
  var k = value.lastIndexOf(".");
  var value2 = "";
  if (k != -1)
  {
    value2 = value.substring(0, k);
    //alert (value);
  }
  for(j=0; j<array.length; j++)
  {
    if (array[j] == value || array[j] == value2)
    {
        notNull = true; 
        //alert (value);
        break;
    }  
  }  
  return notNull;
}

function checkForm(theForm, notNullFields)
{
	var prefixosMultiplos = new Array(
	"financiado","garantia","participacao","bemImovel","instalacaoAgricola","bemMovel",
	"arrendamento","cultura","semovente","divida","garantido","controle","administracao","referencia");
	var camposInvalidos = new Array();
	var item;
	var prefixo;
	var ehMultiplo;
	var countCampo;
	var i;
	var validade = true;
	
	for(item in notNullFields)
	{
		ehMultiplo = false;
		for(prefixo in prefixosMultiplos)
		{
			if (notNullFields[item].indexOf(prefixosMultiplos[prefixo]) != -1)
			{
				ehMultiplo = true;
				break;
			}
		}
		
		if (ehMultiplo)
		{
			eval("countCampo = " + prefixosMultiplos[prefixo] + "Count;");
			if (countCampo > 0)
			{
				for(i = 1; i <= countCampo; i++)
				{
					if ( !validaFormCampo(theForm.elements[notNullFields[item] + "." + i]) )
					{
						validade = false;
						camposInvalidos.push(notNullFields[item] + "." + i);
					}
				}
			}
		}
		else
		{
			if ( !validaFormCampo(theForm.elements[notNullFields[item]]) )
			{
				validade = false;
				camposInvalidos.push(notNullFields[item]);
			}
		}
	}
	
	var pendentes = document.getElementById("camposPendentes");
	if (pendentes != null) pendentes.value = camposInvalidos.join();
	
	return validade;
}

function validaFormCampo(campo)
{
	var valid = true;
	var empty = true;
	
	if (campo == null)
		return valid;
	
	if (campo.type == "text" || campo.type == "password" || campo.type == "textarea")
	{
		if (campo.value == "")
		{
			campo.className = "notNull";
			valid = false;
		}
		else campo.className = "";
	}
	else if (campo.type == "select-one")
	{
		if (campo.options.length == 0 ||campo.selectedIndex == 0) 
		{
			campo.className = "selectNotNull";
			valid = false;
		}
		else campo.className = "";
	}
	else if (campo.type == "select-multiple")
	{
		if (campo.options.length == 0) 
		{
			campo.className = "selectNotNull";
			valid = false;
		}
		else campo.className = "";
	}
	else if (campo.type == "radio" || campo.type == "checkbox")
	{
		if (campo.checked)
			empty = false;
		
		if (empty)
		{
			campo.className = "notNull";
			valid = false;
		}
		else campo.className = campo.type;
	}
	else
	{
		var itemLength = campo.length;
		if ( (itemLength != undefined) && ((campo[0].type == "radio") || (campo[0].type == "checkbox")) )
		{
			for (j = 0; (j < itemLength) && empty; j++)
			{
				if (campo[j].checked)
					empty = false;
			}
			
			if (empty)
			{
				for (j = 0; j < itemLength; j++)
					campo[j].className = "notNull";
				
				valid = false;
			}
			else
			{
				for (j = 0; j < itemLength; j++)
					campo[j].className = campo[j].type;
			}
		}
	}

	return valid;
}

/*
// OLD CHECKFORM

function checkForm(theForm, notNullFields)
{
  valid = true;
  var invalidFields = new Array();
  for(i=0; i<theForm.elements.length; i++)
  {
    if (isInArray(theForm.elements[i].name,notNullFields))
    {    
      //alert(theForm.elements[i].name);
      //alert(theForm.elements[i].type);
      if (theForm.elements[i].type == "text" || theForm.elements[i].type == "password" || theForm.elements[i].type == "textarea")
      {
        if (theForm.elements[i].value == "")
        {
          theForm.elements[i].className = "notNull";  
          //alert("NV="+theForm.elements[i].name);
          valid = false;
		  invalidFields.push(theForm.elements[i].name);
        }
        else
        {      
            theForm.elements[i].className = "";  
        }
      }
      else if (theForm.elements[i].type == "select-one")
      {

        if (theForm.elements[i].options.length == 0 ||theForm.elements[i].selectedIndex == 0) 
        {
		  //alert("entrou");
          theForm.elements[i].className = "selectNotNull";  
		  //alert("NV="+theForm.elements[i].name);
          valid = false;
		  invalidFields.push(theForm.elements[i].name);
        }
        else
        {
          theForm.elements[i].className = "";  
        }
      }
	  
      else if (theForm.elements[i].type == "select-multiple")
      {

        if (theForm.elements[i].options.length == 0) 
        {
		  //alert("entrou");
          theForm.elements[i].className = "selectNotNull";  
		  //alert("NV="+theForm.elements[i].name);
          valid = false;
		  invalidFields.push(theForm.elements[i].name);
        }
        else
        {
          theForm.elements[i].className = "";  
        }
      }
      
      else if (theForm.elements[i].type == "radio" || theForm.elements[i].type == "checkbox")
      {
        //radioId = theForm.elements[i].				
        radioGroupName = theForm.elements[i].name;
        //alert(radioGroupName);
        radioGroup = theForm.elements[radioGroupName];
        //alert(radioGroup.name);
        empty = true;
        
        if (radioGroup.length)
        {
          for (j = 0; j < radioGroup.length && empty; j++)
          {
            //alert(radioGroup[j].value);
            if (radioGroup[j].checked == true)
            {
              empty = false;
            }
          } //for
        }
        
        else if (radioGroup.checked == true)
        {
          empty = false;
        }
        
        if (empty)
        {
          for (j = 0; j < radioGroup.length && empty; j++)
          {
            radioGroup[j].className == "notNull";
          } //for
          //alert("NV="+theForm.elements[i].name);
          valid = false;
		  invalidFields.push(theForm.elements[i].name);
        }
        
        else
        {
          for (j = 0; j < radioGroup.length && empty; j++)
          {
            radioGroup[j].className == radioGroup[j].type;
          } //for
        }
        
      } //else if
      
    }       
  }
  var pendentes = document.getElementById("camposPendentes");
  if (pendentes != "") pendentes.value = invalidFields.join();
  return valid;
}
*/
//********************************************************************

//------------------------------------- Antigo "NumberFormat154.js"
// mredkj.com
function NumberFormat(num, inputDecimal)
{
this.VERSION = 'Number Format v1.5.4';
this.COMMA = ',';
this.PERIOD = '.';
this.DASH = '-'; 
this.LEFT_PAREN = '('; 
this.RIGHT_PAREN = ')'; 
this.LEFT_OUTSIDE = 0; 
this.LEFT_INSIDE = 1;  
this.RIGHT_INSIDE = 2;  
this.RIGHT_OUTSIDE = 3;  
this.LEFT_DASH = 0; 
this.RIGHT_DASH = 1; 
this.PARENTHESIS = 2; 
this.NO_ROUNDING = -1 
this.num;
this.numOriginal;
this.hasSeparators = false;  
this.separatorValue;  
this.inputDecimalValue; 
this.decimalValue;  
this.negativeFormat; 
this.negativeRed; 
this.hasCurrency;  
this.currencyPosition;  
this.currencyValue;  
this.places;
this.roundToPlaces; 
this.truncate; 
this.setNumber = setNumberNF;
this.toUnformatted = toUnformattedNF;
this.setInputDecimal = setInputDecimalNF; 
this.setSeparators = setSeparatorsNF; 
this.setCommas = setCommasNF;
this.setNegativeFormat = setNegativeFormatNF; 
this.setNegativeRed = setNegativeRedNF; 
this.setCurrency = setCurrencyNF;
this.setCurrencyPrefix = setCurrencyPrefixNF;
this.setCurrencyValue = setCurrencyValueNF; 
this.setCurrencyPosition = setCurrencyPositionNF; 
this.setPlaces = setPlacesNF;
this.toFormatted = toFormattedNF;
this.toPercentage = toPercentageNF;
this.getOriginal = getOriginalNF;
this.moveDecimalRight = moveDecimalRightNF;
this.moveDecimalLeft = moveDecimalLeftNF;
this.getRounded = getRoundedNF;
this.preserveZeros = preserveZerosNF;
this.justNumber = justNumberNF;
this.expandExponential = expandExponentialNF;
this.getZeros = getZerosNF;
this.moveDecimalAsString = moveDecimalAsStringNF;
this.moveDecimal = moveDecimalNF;
this.addSeparators = addSeparatorsNF;
if (inputDecimal == null) {
this.setNumber(num, this.PERIOD);
} else {
this.setNumber(num, inputDecimal); 
}
this.setCommas(true);
this.setNegativeFormat(this.LEFT_DASH); 
this.setNegativeRed(false); 
this.setCurrency(false); 
this.setCurrencyPrefix('$');
this.setPlaces(2);
}
function setInputDecimalNF(val)
{
this.inputDecimalValue = val;
}
function setNumberNF(num, inputDecimal)
{
if (inputDecimal != null) {
this.setInputDecimal(inputDecimal); 
}
this.numOriginal = num;
this.num = this.justNumber(num);
}
function toUnformattedNF()
{
return (this.num);
}
function getOriginalNF()
{
return (this.numOriginal);
}
function setNegativeFormatNF(format)
{
this.negativeFormat = format;
}
function setNegativeRedNF(isRed)
{
this.negativeRed = isRed;
}
function setSeparatorsNF(isC, separator, decimal)
{
this.hasSeparators = isC;
if (separator == null) separator = this.COMMA;
if (decimal == null) decimal = this.PERIOD;
if (separator == decimal) {
this.decimalValue = (decimal == this.PERIOD) ? this.COMMA : this.PERIOD;
} else {
this.decimalValue = decimal;
}
this.separatorValue = separator;
}
function setCommasNF(isC)
{
this.setSeparators(isC, this.COMMA, this.PERIOD);
}
function setCurrencyNF(isC)
{
this.hasCurrency = isC;
}
function setCurrencyValueNF(val)
{
this.currencyValue = val;
}
function setCurrencyPrefixNF(cp)
{
this.setCurrencyValue(cp);
this.setCurrencyPosition(this.LEFT_OUTSIDE);
}
function setCurrencyPositionNF(cp)
{
this.currencyPosition = cp
}
function setPlacesNF(p, tr)
{
this.roundToPlaces = !(p == this.NO_ROUNDING); 
this.truncate = (tr != null && tr); 
this.places = (p < 0) ? 0 : p; 
}
function addSeparatorsNF(nStr, inD, outD, sep)
{
nStr += '';
var dpos = nStr.indexOf(inD);
var nStrEnd = '';
if (dpos != -1) {
nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
nStr = nStr.substring(0, dpos);
}
var rgx = /(\d+)(\d{3})/;
while (rgx.test(nStr)) {
nStr = nStr.replace(rgx, '$1' + sep + '$2');
}
return nStr + nStrEnd;
}
function toFormattedNF()
{	
var pos;
var nNum = this.num; 
var nStr;            
var splitString = new Array(2);   
if (this.roundToPlaces) {
nNum = this.getRounded(nNum);
nStr = this.preserveZeros(Math.abs(nNum)); 
} else {
nStr = this.expandExponential(Math.abs(nNum)); 
}
if (this.hasSeparators) {
nStr = this.addSeparators(nStr, this.PERIOD, this.decimalValue, this.separatorValue);
} else {
nStr = nStr.replace(new RegExp('\\' + this.PERIOD), this.decimalValue); 
}
var c0 = '';
var n0 = '';
var c1 = '';
var n1 = '';
var n2 = '';
var c2 = '';
var n3 = '';
var c3 = '';
var negSignL = (this.negativeFormat == this.PARENTHESIS) ? this.LEFT_PAREN : this.DASH;
var negSignR = (this.negativeFormat == this.PARENTHESIS) ? this.RIGHT_PAREN : this.DASH;
if (this.currencyPosition == this.LEFT_OUTSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
}
if (this.hasCurrency) c0 = this.currencyValue;
} else if (this.currencyPosition == this.LEFT_INSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
}
if (this.hasCurrency) c1 = this.currencyValue;
}
else if (this.currencyPosition == this.RIGHT_INSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n0 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n3 = negSignR;
}
if (this.hasCurrency) c2 = this.currencyValue;
}
else if (this.currencyPosition == this.RIGHT_OUTSIDE) {
if (nNum < 0) {
if (this.negativeFormat == this.LEFT_DASH || this.negativeFormat == this.PARENTHESIS) n1 = negSignL;
if (this.negativeFormat == this.RIGHT_DASH || this.negativeFormat == this.PARENTHESIS) n2 = negSignR;
}
if (this.hasCurrency) c3 = this.currencyValue;
}
nStr = c0 + n0 + c1 + n1 + nStr + n2 + c2 + n3 + c3;
if (this.negativeRed && nNum < 0) {
nStr = '<font color="red">' + nStr + '</font>';
}
return (nStr);
}
function toPercentageNF()
{
nNum = this.num * 100;
nNum = this.getRounded(nNum);
return nNum + '%';
}
function getZerosNF(places)
{
var extraZ = '';
var i;
for (i=0; i<places; i++) {
extraZ += '0';
}
return extraZ;
}
function expandExponentialNF(origVal)
{
if (isNaN(origVal)) return origVal;
var newVal = parseFloat(origVal) + ''; 
var eLoc = newVal.toLowerCase().indexOf('e');
if (eLoc != -1) {
var plusLoc = newVal.toLowerCase().indexOf('+');
var negLoc = newVal.toLowerCase().indexOf('-', eLoc); 
var justNumber = newVal.substring(0, eLoc);
if (negLoc != -1) {
var places = newVal.substring(negLoc + 1, newVal.length);
justNumber = this.moveDecimalAsString(justNumber, true, parseInt(places));
} else {
if (plusLoc == -1) plusLoc = eLoc;
var places = newVal.substring(plusLoc + 1, newVal.length);
justNumber = this.moveDecimalAsString(justNumber, false, parseInt(places));
}
newVal = justNumber;
}
return newVal;
} 
function moveDecimalRightNF(val, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimal(val, false);
} else {
newVal = this.moveDecimal(val, false, places);
}
return newVal;
}
function moveDecimalLeftNF(val, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimal(val, true);
} else {
newVal = this.moveDecimal(val, true, places);
}
return newVal;
}
function moveDecimalAsStringNF(val, left, places)
{
var spaces = (arguments.length < 3) ? this.places : places;
if (spaces <= 0) return val; 
var newVal = val + '';
var extraZ = this.getZeros(spaces);
var re1 = new RegExp('([0-9.]+)');
if (left) {
newVal = newVal.replace(re1, extraZ + '$1');
var re2 = new RegExp('(-?)([0-9]*)([0-9]{' + spaces + '})(\\.?)');		
newVal = newVal.replace(re2, '$1$2.$3');
} else {
var reArray = re1.exec(newVal); 
if (reArray != null) {
newVal = newVal.substring(0,reArray.index) + reArray[1] + extraZ + newVal.substring(reArray.index + reArray[0].length); 
}
var re2 = new RegExp('(-?)([0-9]*)(\\.?)([0-9]{' + spaces + '})');
newVal = newVal.replace(re2, '$1$2$4.');
}
newVal = newVal.replace(/\.$/, ''); 
return newVal;
}
function moveDecimalNF(val, left, places)
{
var newVal = '';
if (places == null) {
newVal = this.moveDecimalAsString(val, left);
} else {
newVal = this.moveDecimalAsString(val, left, places);
}
return parseFloat(newVal);
}
function getRoundedNF(val)
{
val = this.moveDecimalRight(val);
if (this.truncate) {
val = val >= 0 ? Math.floor(val) : Math.ceil(val); 
} else {
val = Math.round(val);
}
val = this.moveDecimalLeft(val);
return val;
}
function preserveZerosNF(val)
{
var i;
val = this.expandExponential(val);
if (this.places <= 0) return val; 
var decimalPos = val.indexOf('.');
if (decimalPos == -1) {
val += '.';
for (i=0; i<this.places; i++) {
val += '0';
}
} else {
var actualDecimals = (val.length - 1) - decimalPos;
var difference = this.places - actualDecimals;
for (i=0; i<difference; i++) {
val += '0';
}
}
return val;
}
function justNumberNF(val)
{
newVal = val + '';
var isPercentage = false;
if (newVal.indexOf('%') != -1) {
newVal = newVal.replace(/\%/g, '');
isPercentage = true; 
}
var re = new RegExp('[^\\' + this.inputDecimalValue + '\\d\\-\\+\\(\\)eE]', 'g');	
newVal = newVal.replace(re, '');
var tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');
var treArray = tempRe.exec(newVal); 
if (treArray != null) {
var tempRight = newVal.substring(treArray.index + treArray[0].length); 
newVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); 
}
if (newVal.charAt(newVal.length - 1) == this.DASH ) {
newVal = newVal.substring(0, newVal.length - 1);
newVal = '-' + newVal;
}
else if (newVal.charAt(0) == this.LEFT_PAREN
&& newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) {
newVal = newVal.substring(1, newVal.length - 1);
newVal = '-' + newVal;
}
newVal = parseFloat(newVal);
if (!isFinite(newVal)) {
newVal = 0;
}
if (isPercentage) {
newVal = this.moveDecimalLeft(newVal, 2);
}
return newVal;
}
//------------------------------------------------------------------------------------

var wd
  function parseelement(thisone)
  {    
   wd="w"
   var tempnum=thisone.value
   for (i=0;i<tempnum.length;i++)
   {
    if (tempnum.charAt(i)==",")
    {
     wd="d"
     break
    }
   }
   if (wd=="w")
    thisone.value=tempnum+",00"
   else
   {
    if (tempnum.charAt(tempnum.length-2)==",")
    {
     thisone.value=tempnum+"0"
    }
    else if (tempnum.charAt(tempnum.length-1)==",")
    {
     thisone.value=tempnum+"00"
    }
   }
  }

// abre tela do gerenciador
var newwindow;
function poptastic(url)
{
	newwindow=window.open(url,'name','height=700,width=800');
	if (window.focus) {newwindow.focus()}
}

// abre tela do Login
var newwindow;
function poptasticLogin(url)
{
	newwindow=window.open(url,'name','height=250,width=700');
	if (window.focus) {newwindow.focus()}
}


function Limpar(valor, validos) {
// retira caracteres invalidos da string
var result = "";
var aux;
for (var i=0; i < valor.length; i++) {
aux = validos.indexOf(valor.substring(i, i+1));
if (aux>=0) {
result += aux;
}
}
return result;
}

function FormataValor(campo,tammax,teclapres) {
  var tecla = teclapres.keyCode;
  vr = Limpar(campo.value,"0123456789");
  tam = vr.length;
  if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

  if (tecla == 8 ){ tam = tam - 1 ; }

  if (tecla == null || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
    if ( tam <= 2 ){ 
      campo.value = vr ; 
    }
    if ( (tam > 2) && (tam <= 5) ){ campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - 2, tam ) ; }
    if ( (tam >= 6) && (tam <= 8) ){ campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ; }
    if ( (tam >= 9) && (tam <= 11) ){ campo.value = 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) ){ campo.value = 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) ){ campo.value = 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 ) ;}
  } 

}

function FormataData(campo)
{
  return formatar(campo, '##/##/####');
}


function Mascara(formato, keypress, objeto) 
{ 
campo = eval (objeto); 
if (formato=='DATA') 
{ 
caracteres = '01234567890'; 
separacoes = 1; 
separacao1 = '/'; 
conjuntos = 3; 
conjunto1 = 2; 
conjunto2 = 5; 
if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
(conjunto1 + conjunto2 + 1)) 
{ 
if (campo.value.length == conjunto1) 
campo.value = campo.value + separacao1; 
if (campo.value.length == conjunto2) 
campo.value = campo.value + separacao1; 

} 
else 
campo.value = campo.value; 
} 

if (formato=='MESANO') 
{ 
caracteres = '01234567890'; 
separacoes = 1; 
separacao1 = '/'; 
conjuntos = 2; 
conjunto1 = 2; 
conjunto2 = 4; 
if ((caracteres.search(String.fromCharCode (keypress))!=-1) && campo.value.length < 
(conjunto1 + conjunto2 + 1)) 
{ 
if (campo.value.length == conjunto1) 
campo.value = campo.value + separacao1; 
} 
else 
event.returnValue = false; 
} 
}


/* Formatação para qualquer mascara */

function formatar(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida) 
  {
	src.value += texto.substring(0,1);
  }
}



function uncheck(form, field)
{
	for (i=0; i<document.forms[form].elements[field].length; i++)
		document.forms[form].elements[field][i].checked = false;
}

function check_cpf (numcpf)
{
x = 0;
soma = 0;
dig1 = 0;
dig2 = 0;
texto = "";
numcpf1="";
len = numcpf.length; x = len -1;
// var numcpf = "12345678909";
for (var i=0; i <= len - 3; i++) {
y = numcpf.substring(i,i+1);
if ((y != "-") || (y != ".")) {
	soma = soma + ( y * x);
	x = x - 1;
	texto = texto + y;
	}
}
dig1 = 11 - (soma % 11);
if (dig1 == 10) dig1=0 ;
if (dig1 == 11) dig1=0 ;
numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
x = 11; soma=0;
for (var i=0; i <= len - 2; i++) {
soma = soma + (numcpf1.substring(i,i+1) * x);
x = x - 1;
}
dig2= 11 - (soma % 11);
if (dig2 == 10) dig2=0;
if (dig2 == 11) dig2=0;
//alert ("Digito Verificador : " + dig1 + "" + dig2);
if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
return true;
}
return false;
}

function valida_email(email) {

  if ((email.indexOf('@') == email.lastIndexOf('@')) &&
      (email.indexOf('@') > 0) &&
      (email.lastIndexOf('.') > (email.indexOf('@') + 1)) &&
      (email.lastIndexOf('.') + 1 != email.length)) return true
  else return false
}

function consisteEmail(email) {
  //O pattern abaixo reflete as seguintes regras:
  //- no máximo 25 caracteres (alfanumérico, hífen, ponto) possíveis antes da @, sendo q o último
  //  deve ser um caracter alfanumérico
  //- cada parte do domínio pode ter no máximo 30 caracteres (alfanumérico, hífen), último não 
  //  pode ser hífen
  //- domínio pode ter até 4 partes separadas por ponto, sendo que a ultima tem entre 2 e 3
  //  caracteres (alfanumérico), geralmente com, net, br, etc
  pattern  = /(^[a-z0-9.-]{1,24}[a-z0-9]@([a-z0-9-]{1,29}[a-z0-9].){1,3}[a-z0-9]{2,3}$)/;
  
  return pattern.test(email);

}

function formataData(campo){
//Formata o campo de data de acordo com a tecla pressionada
  
  var pos = 2;
  var pos1 = 4;
  var tecla = event.keyCode;
  var tam = 0;
  var vrout = "";

  vr = ""
  for (i=0 ;i <= campo.value.length; i++) {
    c = campo.value.substr(i,1);
  if (c >= "0" && c <= "9") {
    vr += c;
  }
  }
  tam = vr.length ;

  if (tecla == 8 ){ 
  tam = tam - 1 ; 
  }
  
  if ( tecla == 9 || tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105){

  vrout = "" ;
  for (i=0 ;i <= tam ; i++) {
  
  c = vr.substr(i,1);

  switch (i){  
    case pos : 
    case pos1 :      
      vrout += "/";      
      break;  
    } // switch
  vrout += c;
  } // for
  
  campo.value = vrout;
  }
    
  else {
    return(false);
  }

  return(true);
  
}


//----------------------------------------------------






//testa se caractere é numérico
function isNum(caractere)
{
  var strValidos = "0123456789,"
  if ( strValidos.indexOf( caractere ) == -1 )
    return false;
  return true;
}
function isNum2(caractere)
{
  var strValidos = "0123456789"
  if ( strValidos.indexOf( caractere ) == -1 )
    return false;
  return true;
}
  
//retorna verdadeiro se tecla em event é númerica ou backspace
//retorna falso caso contrário
function validaTeclaNumerica(event)
{
  var BACKSPACE=  8;
  var TAB= 9;
  var key;
  var tecla;

  if(navigator.appName.indexOf("Netscape")!= -1)  
    tecla= event.which;    
  else
    tecla= event.keyCode;

  key = String.fromCharCode( tecla);

  if ( tecla == 13 )
    return false;
  if ( tecla == BACKSPACE || tecla == TAB )
    return true;
  return ( isNum(key));

} 
function validaTeclaNumerica2(event)
{
  var BACKSPACE=  8;
  var key;
  var tecla;

  if(navigator.appName.indexOf("Netscape")!= -1)  
    tecla= event.which;    
  else
    tecla= event.keyCode;

  key = String.fromCharCode( tecla);

  if ( tecla == 13 )
    return false;
  if ( tecla == BACKSPACE )
    return true;
  return ( isNum2(key));

} 

function validaData ( data ) {
//Verifica se a data é válida (data em português) 
//no formato DD/MM/YY ou DD/MM/YYYY

  if (data == "" ) {
    return (false) ;
  }  
  else {
  
    var datePat = /^(\d{1,2})(\/|-)(\d{2})\2(\d{4})$/i;

    var matchArray = data.match(datePat); //verifica o formato
    if (matchArray == null) {
      return (false);
    }
  
    day = matchArray[1]; // divide a data em variáveis
    month = matchArray[3];
    year = matchArray[4];

    if (month < 1 || month > 12) { // verifica o intervalo de meses
      return (false);
    }
    if (day < 1 || day > 31) {
      return (false);
    }
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
      return (false);
    }
    if (month == 2) { //verifica data de 29 de fevereiro
      var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) {
      return (false);
    }
    }  
  }
  return (true);  // data válida
  
}

function validaTecla(event, compare)
{
  var BACKSPACE=  8;
  var key;
  var tecla;

  if (event.which)  
    tecla = event.which;    
  else
    tecla = event.keyCode;

  key = String.fromCharCode( tecla);

  if ( tecla == 13 )
    return false;
  if ( tecla == BACKSPACE )
    return true;
  return ( compare.indexOf(key)!=-1);
}

// Open a pop up window
function openPopup(winurl, winname, winWidth, winHeight, posX, posY, scroll)
{
  // Position
  var x = null;
  var y = null;
  if (posX == null)
  {
  	x = (window.screen.width - winWidth)/ 2;
  }
  if (posY == null)
  {
  	y = (window.screen.height - winHeight)/2;
  }
  var scr;
  if (scroll == 1) {
  	scr = "scrollbars=yes";
  } else {
  	scr = "scrollbars=no";
  }
  // Object window
  var win = null;
  params = "width="+winWidth+", height="+winHeight+", top="+y+",left="+x+", "+scr+", resizable=yes, toolbar=no, menubar=no, location=no, directories=no";
  win = window.open(winurl, winname, params);
  win.moveTo(x, y);
  win.focus();
}

// Open a pop up window
function openPopup2(winurl, winname, winWidth, winHeight, posX, posY) 
{
  // Position
  var x = null;
  var y = null;
  if (posX == null)
  {
  	x = (window.screen.width - winWidth)/ 2;
  }
  if (posY == null)
  {
  	y = (window.screen.height - winHeight)/2;
  }
  
  // Object window
  var win = null;
  params = "width="+winWidth+", height="+winHeight+", top="+y+",left="+x+", scrollBars=no, resizable=no, " +
           "toolbar=no, menubar=no, location=no, directories=no";
  win = window.open(winurl, winname, params);
  win.moveTo(x, y);
  win.focus();
}

function populateUF(comboId, value)
{
	var combo = document.getElementById(comboId);
	
	if (combo == null) return;

	combo.length = 0;
	combo.options[combo.length] = new Option("", "");
	combo.options[combo.length] = new Option("AC", "AC");
	combo.options[combo.length] = new Option("AL", "AL");
	combo.options[combo.length] = new Option("AM", "AM");
	combo.options[combo.length] = new Option("AP", "AP");
	combo.options[combo.length] = new Option("BA", "BA");
	combo.options[combo.length] = new Option("CE", "CE");
	combo.options[combo.length] = new Option("DF", "DF");
	combo.options[combo.length] = new Option("ES", "ES");
	combo.options[combo.length] = new Option("GO", "GO");
	combo.options[combo.length] = new Option("MA", "MA");
	combo.options[combo.length] = new Option("MG", "MG");
	combo.options[combo.length] = new Option("MS", "MS");
	combo.options[combo.length] = new Option("MT", "MT");
	combo.options[combo.length] = new Option("PA", "PA");
	combo.options[combo.length] = new Option("PB", "PB");
	combo.options[combo.length] = new Option("PE", "PE");
	combo.options[combo.length] = new Option("PI", "PI");
	combo.options[combo.length] = new Option("PR", "PR");
	combo.options[combo.length] = new Option("RJ", "RJ");
	combo.options[combo.length] = new Option("RN", "RN");
	combo.options[combo.length] = new Option("RO", "RO");
	combo.options[combo.length] = new Option("RR", "RR");
	combo.options[combo.length] = new Option("RS", "RS");
	combo.options[combo.length] = new Option("SC", "SC");
	combo.options[combo.length] = new Option("SE", "SE");
	combo.options[combo.length] = new Option("SP", "SP");
	combo.options[combo.length] = new Option("TO", "TO");
	if (value != "") combo.value = value;
}

function populateMunicipio(combo, uf, value)
{    
	municipio.location.href = "../publico/action/PopulateMunicipio.asp?uf="+uf+"&combo="+combo+"&value="+value;	
}

// abre popup modal
function openModalPopup(winurl, winname, winWidth, winHeight, posX, posY, scroll)
{
  var x = null;
  var y = null;
  if (posX == null) x = (window.screen.width - winWidth) / 2;
  if (posY == null)	y = (window.screen.height - winHeight) / 2;
  
  var params = "";
  var win = null;
  if (window.showModalDialog)
  {
  		params = "dialogWidth:"+winWidth+"px; dialogHeight:"+winHeight+"px; "+(scroll ? "scroll:yes" : "scroll:no")+"; resizable:no; status:no; unadorned:yes;";
	  	win = window.showModalDialog(winurl, '', params);
  }
  else
  {
		params = "width="+winWidth+", height="+winHeight+", top="+y+",left="+x + (scroll ? "scrollbars=yes" : "scrollbars=no")+", resizable=yes, toolbar=no, menubar=no, location=no, directories=no";
	  	win = window.open(winurl, winname, params + ", modal=yes");
		win.moveTo(x, y);
  }
}


function deleteEntity(entityName, entityUID, label)
{
  if (confirm("Você tem certeza que deseja excluir "+label+"?"))
  {
    //alert ("Controller?ent="+entityName+"&act=delete&"+entityName.charAt(0).toLowerCase()+entityName.substring(1, entityName.length)+".uid="+entityUID);
    document.location.href = "controller.jsp?c=delete"+entityName+"&"+entityName.charAt(0).toLowerCase()+entityName.substring(1, entityName.length)+".uid="+entityUID;
    
  }
}

function orderBy(orderBy, orderType)
{
  document.forms["list"].elements["orderBy"].value = orderBy;
  document.forms["list"].elements["orderType"].value = orderType;
  doSubmit(); 
}

function viewPage(viewPage)
{
  document.forms["list"].elements["viewPage"].value = viewPage;
  doSubmit(); 
}

function doPostCep(formUF, formLocalidade, formLogradouro)
{
  var logradouro = formLogradouro.value;
  logradouro = logradouro.toUpperCase().replace('.', '');  
  logradouro = logradouro.toUpperCase().replace('AVENIDA', '');  
  logradouro = logradouro.toUpperCase().replace('AV', '');  
  logradouro = logradouro.toUpperCase().replace('RUA', '');  
  logradouro = logradouro.toUpperCase().replace('TRAVESSA', '');  
  logradouro = logradouro.toUpperCase().replace('TRAV', '');  
  document.forms['cep_form'].elements['UF'].value = formUF.options[formUF.selectedIndex].value;
  document.forms['cep_form'].elements['Localidade'].value = formLocalidade.value;  
  document.forms['cep_form'].elements['Logradouro'].value = logradouro;
  document.forms['cep_form'].submit();
}

function fileExplorer()
{

  var winWidth = 700;
  var winHeight = 500;
  // Position
  var x = (window.screen.width - winWidth)/ 2;
  var y = (window.screen.height - winHeight)/2;
  // Object window
  var win = null;
  
  params = "width="+winWidth+", height="+winHeight+", top="+y+",left="+x+", scrollBars=yes, resizable=no, " +
           "toolbar=no, menubar=no, location=no, directories=no";
  win = window.open("controller.jsp?c=listImageLibrary2", "fileExplorer", params);
  //win.moveTo(x, y);
  //win.focus();
  //win=window.showModalDialog("controller.jsp?c=viewFileExplorer",window,params);

  //return win;  
  
  //openPopup("controller.jsp?c=viewFileExplorer", "fileExplorer", 600, 400);
}

function pickColor()
{
  //alert ("entrou");
  var winWidth = 218;
  var winHeight = 187;
  // Position
  var x = (window.screen.width - winWidth)/ 2;
  var y = (window.screen.height - winHeight)/2;
  // Object window
  var win = null;
  
  params = "width="+winWidth+", height="+winHeight+", top="+y+",left="+x+", scrollBars=no, resizable=no, " +
           "toolbar=no, menubar=no, location=no, directories=no, status=no";
  //win = window.open("include/color_table.html", "fileExplorer", params);
  //win.moveTo(x, y);
  //win.focus();
  win=window.showModalDialog('include/color_table.html',window,params);
  return win;  
}

function pageNavigator(page, frameName, formName)
{
  if (formName == 'null') {
    formName = "listForm";
  }	
  if (frameName == 'null') {
  	document.forms[formName].elements["pageIndex"].value = page;
  	document.forms[formName].submit();
  } else {
	window.frames[frameName].document.forms[formName].elements["pageIndex"].value = page;
    window.frames[frameName].document.forms[formName].submit();
  } 
}

function pageOrder(column, direction, frameName, formName)
{	
  if (formName == 'null') {
    formName = "listForm";
  }	
  if (frameName == 'null') {
  	document.forms[formName].elements["orderDirection"].value = direction;
	document.forms[formName].elements["orderColumn"].value = column;
  	document.forms[formName].submit();
  } else {
	window.frames[frameName].document.forms[formName].elements["orderDirection"].value = direction;
	window.frames[frameName].document.forms[formName].elements["orderColumn"].value = column;
    window.frames[frameName].document.forms[formName].submit();
  } 
}


function removeFromArray(pArray, pElement)
{
  var outArray = new Array();

  for (var i=0; i<pArray.length; i++)
    if (pArray[i] != pElement)
      outArray.push(pArray[i]);

  pArray = outArray;
}

function addToArray(pArray, pElement)
{
  var add = true;

  for (var i=0; i<pArray.length && add; i++)
    if (pArray[i] == pElement)
      add = false;

  if (add)
    pArray.push(pElement);
}

function mOvr(src,clrOver) 
    {
        if (!src.contains(event.fromElement)) 
            {
                src.style.cursor = 'hand';
                src.bgColor = clrOver;
            }
    }
    
function mOut(src,clrIn) 
    {
        if (!src.contains(event.toElement)) 
            {
                src.style.cursor = 'default';
                src.bgColor = clrIn;
            }
    }


