/**
*	Biblioteca de funções JavaScript responsáveis 
*	por fazer validações de:
*	- Formato de data : isDate
*	- Formato de hora : isTime
*	- Formato de moeda: isMoeda
*	- Dígitos válidos : isDigit
*	- Decimal válido  : isDecimal
*	- E-mail válido   : isEmail
*	- validação de CPF: validaCPF
*	- validação de CNPJ: validaCNPJ
*	- Comparação de datas: dtaInicialMaiorQFinal
*	- Digitar apenas números: onlyNumbers
*	- Adicionar máscara: inputMask
*	- Remover espaços de string: trim
*	- Remover espaços do lado esquerdo da string : LTrim
*	- Remover espaços do lado direito da string : RTrim
*
*	@author dm@proxima.agr.br avs@proxima.agr.br omn@proxima.agr.br	
*	@version 1.0
*	06/06/2006 
*/

/**				inputMask
*	Função utilizada para colocar máscara
*	em um campo passado como par?metro
*	A máscara deve ser passada como par?metro
*	conforme mostra o exemplo abaixo.
*	Ex:
*	OnKeyPress="inputMask(this, '##/##/####')"
*
*	CEP : #####-###
*	CPF : ###.###.###-##
*	CNPJ: ##.###.###/####-## 
*	DATA: ##/##/####
*/
function inputMask(src, mask) {
	// alteração realizada em 29/01/2007 - limpar campo
	if ((src.value.length == mask.length) && (window.document.selection.createRange().text.length == mask.length)) {
		if (src.readOnly == false) {
			src.value = src.value.substr(src.value.length,1);
		}
	}
	//
	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);
	}
}

/**				LTrim
*	Função utilizada para retirar os espaços
*	em branco do lado esquerdo da string
*	Veja trim()
*/
function LTrim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");	
}

/**				RTrim
*	Função utilizada para retirar os espaços
*	em branco do lado direito da string
*	Veja trim()
*/
function RTrim( value ) {	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

/**				trim
*	Retorna o valor passado sem espaços
*	em branco à direita e à esquerda.
*	Ex:
*	if(trim(campo.value).length == 0)
*	alert('O campo está vazio');
*/
function trim( value ) {	
	return LTrim(RTrim(value));	
}

/**				isDigits
*	Função utilizada para validar se 
*	no campo passado como argumento,
*	tem somente dígitos. (Números naturais)
*	Ex:
*	onblur="isDigits(this)";
*/
var reDigits = /^\d+$/;
function isDigits( pStr ) {
	if ((pStr != null) && (pStr.value.length > 0)) {
		if (reDigits.test(pStr.value)) {
			return true;
		} else {
			geraMessageBox("Informe apenas números.", "2");
			pStr.value = "";
			setFocus(pStr);
			return false;
		}
	}
	
	return false;
}

/**				isInteger
*	Função utilizada para validar se 
*	no campo passado como argumento,
*	tem um número inteiro. 
*	Ex:
*	onblur="isInteger(this)";
*/
function isInteger( pStr ) {
	var x = pStr.value
	var y = parseInt(x);
	var isInt;
	
	if (isNaN(y)) {
		isInt = false;
	} else if (x==y && x.toString()==y.toString()) {
		isInt = true;
	} else {
		isInt = false;
	}
		
	if (!isInt) {
		geraMessageBox(termosGerais.APENAS_NUMEROS, "2");
		pStr.value = "";
		setFocus(pStr);
	}
		
	return isInt;
}

/**					isDecimal
*	Função utilizada para validar se o valor
*	passado como argumento para a Função, tem
*	números decimais válidos.
*	O segundo argumento da Função é o separador
*	Os valores válidos são ponto(.) e vírgula(,)
*	Passar o valor En significa que o separador ser é ponto(.)
*	Passar o valor Pt significa que o separador ser é vírgula(,)
*	Ex:
*	onblur="isDecimal(this, 'Pt')";
*/
var reDecimalPt = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
var reDecimalEn = /^[+-]?((\d+|\d{1,3}(\,\d{3})+)(\.\d*)?|\.\d+)$/;
var reDecimal = reDecimalPt;
function isDecimal( pStr, pLang ) {
	
	pStr.value = pStr.value.replace(".",",");		
	charDec = ",";
	eval("reDecimal = reDecimal" + pLang);
	if (reDecimal.test(pStr.value)) {
		//pos = pStr.indexOf(charDec);
		//decs = pos == -1? 0: pStr.length - pos - 1;
		//alert(pStr + " é um float válido (" + pLang + ") com " + decs + " decimais.");
	} else if (pStr.value != null && pStr.value != "") {
		geraMessageBox("Formato decimal inválido!", "2");
		pStr.value = "";
		pStr.focus();
	}
}

/**	validDecimal
*	Função utilizada para validar se o valor
*	passado como argumento para a Função, tem
*	números decimais válidos.
*	Ex:
*	onblur="validDecimal(this, 3, 2)";
*/
var reDecimal = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
function validDecimal( pStr, integer, decimal ) {	
	pStr.value = pStr.value.replace(".",",");		
	charDec = ",";
	if (reDecimal.test(pStr.value)) {
		var pos = pStr.value.indexOf(charDec);
		if (pos == -1) {
			pos = pStr.value.length;
			decs = 0;
		} else {
			decs = pStr.value.length - pos - 1;
		}
		if (pos > integer || decs > decimal) {
			geraMessageBox("O campo deve ser formado por " + integer + " inteiros e " + decimal + " decimais!", "2");
			pStr.focus();
			return false;
		}
	} else if (pStr.value != null && pStr.value != "") {
		geraMessageBox("Formato decimal inválido!", "2");
		pStr.value = "";
		pStr.focus();
		return false;
	}
	return true;
}

/**	isPositive
*/
function isPositive( pStr ) {
	if (pStr.value != null && pStr.value != "") {
		var value = pStr.value.replace(",",".");
		if (value < 0) {
			geraMessageBox("O valor deve ser positivo.", "2");
			pStr.value = "";
			pStr.focus();
		}
	}
}

/**					isMoeda
*	Função utilizada para validar valores financeiros
*	Ex:
*	onblur="isMoeda(this)";
*/
var reMoeda = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
function isMoeda( pStr ) {
	if (reMoeda.test(pStr.value)) {
		//alert(pStr + " é um valor financeiro válido.");
	} else if (pStr.value != null && pStr.value != "") {
		geraMessageBox("Formato financeiro inválido", "2");
		pStr.focus();
	}
}

/**					isDate
*	Função que valida se o valor passado como argumento
*	é uma data válida.
	1	--> Simples
  	2	--> Média
    3	--> Avançada
    4	--> Completa
    5	--> dd/mm/aaaa
*	Ex:
*	onblur="isDate(this, '5')";
*/
var reDate1 = /^\d{1,2}\/\d{1,2}\/\d{1,4}$/;
var reDate2 = /^[0-3]?\d\/[01]?\d\/(\d{2}|\d{4})$/;
var reDate3 = /^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[0-2])\/(19|20)?\d{2}$/;
var reDate4 = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
var reDate5 = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
var reDate = reDate4;
function isDate( pStr, pFmt ) {
	pStr.value = completarAno(pStr.value);
	if ((pStr != null) && (pStr.value.length > 0)) {
		eval("reDate = reDate" + pFmt);
		
		if (reDate.test(pStr.value)) {
			return true;
		} else {
			geraMessageBox("Formato inválido de data!", "2");
			pStr.value = "";
			pStr.focus();
			return false;
		}
	}
	
	return false;
} 

/** completarAno(string)
 * 
 *  Função que recebe uma data no formato dd/mm/aa
 *  e retorna a mesma data no formato dd/mm/aaaa.
 * 
 */
function completarAno(pStr) {
	if(pStr.length == 8){
       var ano = pStr.substr(6,8);
       if(ano < 24){
          ano = '20' + ano;
       }else{
          ano = '19' + ano
       }
       pStr = pStr.substr(0,6) + ano;
	}
	return pStr;
}

/**					isTime
*	Função que valida se o valor passado como argumento
*	é um tempo válido.
    1	-->	Horário HH:MM simples
    2	-->	Horário HH:MM 24h
    3	-->	Horário HH:MM 12h
    4	-->	Tempo horas:MM:SS
    5	-->	Tempo horas:MM:SS.mili
*	Ex:
*	onblur="isTime( this, '4' )";
*/
var reTime1 = /^\d{2}:\d{2}$/;
var reTime2 = /^([0-1]\d|2[0-3]):[0-5]\d$/;
var reTime3 = /^(0[1-9]|1[0-2]):[0-5]\d$/;
var reTime4 = /^\d+:[0-5]\d:[0-5]\d$/;
var reTime5 = /^\d+:[0-5]\d:[0-5]\.\d{3}\d$/;
function isTime( pStr, pFmt ) {
	eval("reTime = reTime" + pFmt);
	if (reTime.test(pStr.value)) {
		return true;
	} else if (pStr.value != null && pStr.value != "") {
		geraMessageBox("Formato inválido de hora!", "2");
		pStr.value = "";
		pStr.focus();
		return false;
	}
	
	return false;
} 

/*
 *  afterToday:
 *  Não permite ao usuário inserir no campo 
 *  uma data posterior ao dia corrente.
 */
function afterToday(elementoDT) {
	if (elementoDT.value.length > 0) {
		var dataHora = elementoDT.value + " 00:00";
		var agora = dateTimeNow();
		if (subDateTime(agora, dataHora) > 0) {
			geraMessageBox("Não é possível incluir data posterior ao dia de hoje.", "2");
			elementoDT.value = "";
			elementoDT.focus();
		} 
	}
}

/*
 *  beforeToday:
 *  Não permite ao usuário inserir no campo 
 *  uma data posterior ao dia corrente.
 */
function beforeToday(elementoDT) {
	if (elementoDT.value.length > 0) {
		var dataHora = elementoDT.value + " 00:00";
		var agora = dateTimeNow();
		if (subDateTime(dataHora, agora) > 0) {
			geraMessageBox("Não é possível incluir data anterior ao dia de hoje.", "2");
			elementoDT.value = "";
			elementoDT.focus();
		} 
	}
}

/*
 * Desenvolvida por: Alberto Vieira de Sá Biason
 * subTime : calcula a diferença entre 2 horas (no formato HH:MM)
 */
function subTime(timeStartValue, timeEndValue) {
	if ((timeStartValue.length == 5) && (timeEndValue.length == 5)) {
		var h = 0;
		var m = 0;
		
		h = Number(timeStartValue.substring(0, 2));
		m = Number(timeStartValue.substring(3, 5));
		var timeStart = new Date(1980, 3, 20, h, m, 0, 0);
		
		h = Number(timeEndValue.substring(0, 2));
		m = Number(timeEndValue.substring(3, 5));
		var timeEnd = new Date(1980, 3, 20, h, m, 0, 0);
		
		var t  = timeEnd - timeStart;
		var ss = t / 1000;
		var mm = ss / 60;
		var hh = mm / 60;
		
		return hh;
	} else {
		return 0;
	}
}

/*
 * Desenvolvida por: Alberto Vieira de Sá Biason
 * compareTime : compara 2 horas (no formato HH:MM)
 */
function compareTime(timeStartField, timeEndField) {
	if ((timeStartField.length == 5) && (timeEndField.length == 5)) {
		var h1 = Number(timeStartField.substring(0, 2));
		var m1 = Number(timeStartField.substring(3, 5));
		var timeStart = new Date(1980, 3, 20, h1, m1, 0, 0);
		
		var h2 = Number(timeEndField.substring(0, 2));
		var m2 = Number(timeEndField.substring(3, 5));
		var timeEnd = new Date(1980, 3, 20, h2, m2, 0, 0);
		
		if (timeStart < timeEnd) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function isLesserOrEqualThatTheCurrentTime( varStrTime ) {
	if ( varStrTime.length > 5 ) {
		var day    = Number( varStrTime.substring( 0, 2 ) );
		var month  = Number( varStrTime.substring( 3, 5 ) ) - 1;
		var year   = Number( varStrTime.substring( 6, 10 ) );
		var hour   = Number( varStrTime.substring( 11, 13 ) );
		var minute = Number( varStrTime.substring( 14, 16 ) );
		
		var varTime     = new Date( year, month, day, hour, minute );
		var currentTime = new Date();
		
		if ( varTime <= currentTime ) {
			return true;
		} else {
			return false;
		}
	} else if ( varStrTime.length == 5 ) {
		var h = Number( varStrTime.substring( 0, 2 ) );
		var m = Number( varStrTime.substring( 3, 5 ) );
		
		var varTime = new Date();
		varTime.setHours( h, m, Number( 0 ) );
		
		var currentTime = new Date();
		
		if ( varTime <= currentTime ) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function calcDate(varData, varQtdDias, varOpcao) {
	var dataResultMs = 0;
	var dataResultDt = null;
	
	var UM_DIA = 86400000 * varQtdDias;
	
	var dia = Number(varData.substring(0, 2));
	var mes = Number(varData.substring(3, 5)) - 1;
	var ano = Number(varData.substring(6, 10));
	
	var dataCorrente = new Date(ano, mes, dia);
	var dataQtdeDias = new Date(UM_DIA);
	
	if (varOpcao == "+") {
		dataResultMs = dataCorrente + dataQtdeDias;
		dataResultDt = new Date(dataResultMs);
	} else if (varOpcao == "-") {
		dataResultMs = dataCorrente - dataQtdeDias;
		dataResultDt = new Date(dataResultMs);
	}
	
	return dataResultDt;
}

function calculateDate(varData, varQtdDias, varOpcao) {
	var dataResultMs = 0;
	var dataResultDt = null;

	var mili = 86400000 * varQtdDias;

	var dia = Number(varData.substring(0, 2));
	var mes = Number(varData.substring(3, 5)) - 1;
	var ano = Number(varData.substring(6, 10));

	var dataEntrada = new Date(ano, mes, dia);

	if (varOpcao == "+") {
		dataResultMs = dataEntrada.getTime() + mili;
	} else if (varOpcao == "-") {
		dataResultMs = dataEntrada.getTime() - mili;
	}

	dataResultDt = new Date();
	dataResultDt.setTime(dataResultMs);
	
	return dataResultDt;
}

function getStringFromDate(varData) {
	var res = "";
	
	var dia = varData.getDate();
	var mes = varData.getMonth() + 1;
	var ano = varData.getFullYear();
	
	res += (dia < 10 ? "0" + dia : dia);
	res += "/";
	res += (mes < 10 ? "0" + mes : mes);
	res += "/";
	res += ano;
	
	return res;
}

function getHRStringFromDate(varData) {
	var res = "";
	
	var hr = varData.getHours();
	var mms = varData.getMinutes();
	
	res += (hr < 10 ? "0" + hr : hr);
	res += ":";
	res += (mms < 10 ? "0" + mms : mms);
	
	return res;
}

/**
 *      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
 * Ex.: 1 7 / 0 1 / 2 0 0 7    1  7  :  5  5
 *
 * strDateTimeStart  = "17/01/2007 17:55";
 * strDateTimeEnd    = "19/01/2007 13:42";
 * strDateTimeResult = calcDateTime( strDateTimeStart, strDateTimeEnd );
 */
function subDateTime( strDateTimeStart, strDateTimeEnd ) {
	var day           = Number( strDateTimeStart.substring( 0, 2 ) );
	var month         = Number( strDateTimeStart.substring( 3, 5 ) ) - 1;
	var year          = Number( strDateTimeStart.substring( 6, 10 ) );
	var hour          = Number( strDateTimeStart.substring( 11, 13 ) );
	var minute        = Number( strDateTimeStart.substring( 14, 16 ) );
	
	var dateTimeStart = new Date( year, month, day, hour, minute, 0, 0 );
	
	var day           = Number( strDateTimeEnd.substring( 0, 2 ) );
	var month         = Number( strDateTimeEnd.substring( 3, 5 ) ) - 1;
	var year          = Number( strDateTimeEnd.substring( 6, 10 ) );
	var hour          = Number( strDateTimeEnd.substring( 11, 13 ) );
	var minute        = Number( strDateTimeEnd.substring( 14, 16 ) );
	
	var dateTimeEnd   = new Date( year, month, day, hour, minute, 0, 0 );
	
	var dateTimeCurr  = dateTimeEnd - dateTimeStart;
	
	var ss = dateTimeCurr / 1000;
	var mm = ss / 60;
	var hh = mm / 60;
	
	return hh;
}
/** toClipBoard
 * 
 * Manda um valor String para
 * a Área de Transferência
 * 
 */
function toClipBoard(str) {
	var textBox=document.createElement("<INPUT TYPE='TEXT' NAME='CLIPBOARD' VALUE='' style='position:absolute;top:0;left:0;'>");
    document.body.insertBefore(textBox);

	textBox.value=str;
	textBox.select();
	therange=textBox.createTextRange();
	therange.execCommand('Copy');

	textBox.removeNode(true);
}

/** dateTimeNow
 * 
 * Retorna uma string contendo
 * a data e hora atuais no 
 * formato 'dd/mm/aaaa hh:mm'.
 * 
 */
function dateTimeNow() {
	var objDate = new Date();
	var res     = "";
	var day     = String(objDate.getDate());
	var month   = String(objDate.getMonth() + 1);
	var year    = String(objDate.getFullYear());
	var hour    = String(objDate.getHours());
	var minute  = String(objDate.getMinutes());
	
	if (day.length < 2)    { day    = "0" + day; }
	if (month.length < 2)  { month  = "0" + month; }
	if (hour.length < 2)   { hour   = "0" + hour; }
	if (minute.length < 2) { minute = "0" + minute; }
	
	res = day + "/" + month + "/" + year + " " + hour + ":" + minute;

	return res;
}

/** dateTimeNow
 * 
 * Retorna uma string contendo
 * a data e hora atuais no 
 * formato 'dd/mm/aaaa'.
 * 
 */
function dateNow() {
	var objDate = new Date();
	var res     = "";
	var day     = String(objDate.getDate());
	var month   = String(objDate.getMonth() + 1);
	var year    = String(objDate.getFullYear());
	
	if (day.length < 2)    { day    = "0" + day; }
	if (month.length < 2)  { month  = "0" + month; }
	
	res = day + "/" + month + "/" + year;

	return res;
}

/**					isEmail
*	Função que valida se o valor passado como argumento
*	é um e-mail válido.
	1	--> Livre
  	2	--> Compacto
  	3	--> Restrito
*	Ex:
*	onblur="isEmail( this, '3' )";
*/
var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;
function isEmail( pStr, pFmt ) {
	eval("reEmail = reEmail" + pFmt);
	if (reEmail.test(pStr.value)) {
		//alert(pStr + " é um endereço de e-mail válido.");
	} else if (pStr.value != null && pStr.value != "") {
		geraMessageBox("Formato de e-mail inválido!", "2");
		pStr.focus();
	}
}

/**				dtaInicialMaiorQFinal
*	Função que valida se o argumento dtInicial
*	é menor que dtFinal. Caso seja maior
*	é lançada uma mensagem informando que a
*	data inicial deve ser menor que a data final
*	Ex:
*	onblur="dtaInicialMaiorQFinal( dataInicial, dataFinal )"
*/
function parseDate(date) {
	var pos   = null;
	var day   = null;
	var month = null;
	var d     = null;
	
	// Day
	pos   = date.indexOf('/');
	day   = date.substr(0,pos);
	date  = date.substr(pos + 1, date.length - pos - 1);
	
	// Month
	pos   = date.indexOf('/');
	month = date.substr(0,pos);
	date  = date.substr(pos + 1, date.length - pos - 1);
	
	// Year
	d     = new Date(date, month-1, day);
	
	return d;
}

function newParseDate( varStrDate ) {
	var day   = Number( varStrDate.substring( 0, 2 ) );
	var month = Number( varStrDate.substring( 3, 5 ) ) - 1;
	var year  = Number( varStrDate.substring( 6, 10 ) );
	
	var resultDate = new Date( year, month, day );
	
	return resultDate;
}

function verificarPeriodo( dataInicial, dataFinal ) {
	if ( dataInicial == dataFinal ) {
		return true;
	} else {
		var dtInicial = newParseDate( dataInicial );
		var dtFinal   = newParseDate( dataFinal );
		
		if (dtInicial < dtFinal) {
			return true;
		}
		else {
			return false;
		}
	}
} 

function dtaInicialMaiorQFinal(dtInicial, dtFinal) {
	if (! dtInicial || ! dtFinal ) {
		return false;
	}	
	
	var data1 = dtInicial.value;
	var data2 = dtFinal.value;
	
	if ( data1.length == 0 || data2.length == 0 ) {
		return false;
	}

	if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) >= parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) )
	{
	  return false;
	}
	else
	{
	  return true;
	}
}

function dtaInicialMaiorQFinal2(dtInicial, dtFinal) {
	var data1 = dtInicial.value;
	var data2 = dtFinal.value;

	if ( parseInt( data2.split( "/" )[2].toString() + data2.split( "/" )[1].toString() + data2.split( "/" )[0].toString() ) > parseInt( data1.split( "/" )[2].toString() + data1.split( "/" )[1].toString() + data1.split( "/" )[0].toString() ) )
	{
	  return false;
	}
	else
	{
	  return true;
	}
}

function validaPeriodo( dataCorrente, dataInicial, dataFinal ) {
	var result = false;
	
	var dtC = dataCorrente ? newParseDate( dataCorrente ) : new Date();
	var dtI = newParseDate( dataInicial );
	var dtF = newParseDate( dataFinal );
	
	if ( ( dtC >= dtI ) && ( dtC <= dtF ) ) {
		result = true;
	}
	
	return result;
}

/**					onlyNumbers
*	Função que permite apenas a digitação de números,
*	para o campo que a habilita.
*	Note no exemplo que o parâmetro passado deve ser event.
*	Ex:
*	OnKeyPress="return onlyNumbers(event)"
*/
function onlyNumbers(evnt){
 	if (navigator.appName.indexOf('Microsoft') != -1){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
}

/**
*	Função que valida o CNPJ
*	A Função recebe o campo a ser validado
*	e retorna falso caso tenha algum erro,
*	juntamente com a mensagem do erro causado.
*	Caso seja um CNPJ válido, é retornado verdadeiro
*	Ex:
*	onblur="validaCNPJ( this )"
*/
function validaCNPJ(campo) {
	CNPJ = campo.value;
	
	if (trim(CNPJ).length == 0) {
		return false;
	}
	
    erro = new String;
	if (CNPJ.length < 18) erro += "O número do CNPJ é inválido. Não foram informados todos os dígitos! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	if (erro.length == 0) erro += "O número do CNPJ é inválido. Formato incorreto! \n\n";
	}
	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x;
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "O número do CNPJ é inválido. Informe apenas números! \n\n";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		for (i=0; i<12; i++){
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
			b = 0;
			for (y=0; y<13; y++) {
				b += (a[y] * c[y]);
			}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
			erro +="O número do CNPJ é inválido. Problemas com o dígito verificador!";
		}
		if (erro.length > 0){
			alert(erro);
			campo.focus();
			campo.select();
			return false;
		}
		return true;
}

/**
*	Função utilizada para validar cpf
*	Recebe como argumento um valor de cpf
*	e retorna true ou false, lançando 
*	mensagens de detalhe do erro caso 
*	o cpf seja inválido	
*	Ex:
*	onblur="validaCPF( this )"
*/
function validaCPF(campo) {
	cpf = campo.value;
	
	if (trim(cpf).length == 0) {
		return false;
	}
	
	var cont;
	var aux = "";
	var nonNumbers = /\D/;
	//Retira a máscara caso ela exista
	for(cont=0; cont<cpf.length; cont++) {
		if(! nonNumbers.test(cpf.charAt(cont)) )
			aux+=cpf.charAt(cont);
	}
	cpf = aux;
	erro = new String;
	if (cpf.length < 11) erro += "Número de CPF inválido. São necessários 11 dígitos para verificacão do CPF! \n\n";

	if (nonNumbers.test(cpf)) erro += "A verificação de CPF suporta apenas números! \n\n";
	if (cpf == "00000000000" || cpf == "11111111111" ||	cpf == "22222222222" || cpf == "33333333333" || 
		cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || 
		cpf == "88888888888" || cpf == "99999999999") {
		erro += "Número de CPF inválido!";
	}
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		erro +="Número de CPF inválido. Dígito verificador com problema!";
	}
	if (erro.length > 0){
		alert(erro);
		campo.focus();
		campo.select();
		return false;
	}
	return true;
}

/**
*	Função utilizada para exibir uma Caixa de Mensagem
*	Função....: geraMessageBox(mensagem, opcao)
*	messagem..: texto a ser exibido
*	opcao.....: { 1 | 2 | 3 } -> 1 - OK, 2 - Aviso, 3 - Erro
*	Exemplo...: mensagbox.innerHTML = geraMessageBox("Testando...", 3);
*/
var msg_resp = false;

function geraMessageBox(msg, opcao, params) {
	var op, img, msg, jsp;
	
	if (msg == undefined) {
		msg = "ERRO - Termo não cadastrado.";
	}
	
	if (params != undefined) {
		if (typeof(params) == "string") {
			msg = msg.replace("{0}", params);
		} else {
			for (var i = 0; i < params.length; i++) {
				var str = "{" + i + "}";
				msg = msg.replace(str, params[i]);
			}
		}
	}

	msg = msg.replace(/\&#39;/g, '\'');
	msg = msg.replace(/\&#58;/g, ':');
	msg = msg.replace(/\&#61;/g, '=');
	
	if (msg.length > 0) {
		img = STATIC_WEB_MODULE_NAME+"newimage/";
		jsp = DINAMIC_WEB_MODULE_NAME +"/util/msgbox.jsp";
		op  = parseInt(opcao);
		
		switch (op) {
			case 1:  img += "msgBoxInfo.png";     msg_resp = false; jsp = DINAMIC_WEB_MODULE_NAME +"/util/askmsgbox.jsp"; break;
			case 2:  img += "msgBoxWarning.png";  msg_resp = true; break;
			case 3:  img += "msgBoxCritical.png"; msg_resp = true; break;
			default: img += "msgBoxWarning.png";  msg_resp = true;
		}
		
		var destino = jsp + "?msg=" + msg + "&img=" + img;
		window.showModalDialog(destino, window, "help:no;status:no;scroll:no;dialogWidth:480px;dialogHeight:200px");
	}
	
	return msg_resp;
}

//goTo (X) : Vai para URL desejada
function goTo(url) {
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}	
	document.location = url;
}

//Janela Popup -- Início --------------------------------------------

var windowWhoCall;
var windowModal;

function popup( popupURL, popupWidth, popupHeight ) {
    if ( popupWidth == undefined || popupWidth == null ) {
	    popupWidth = 425;
   	}
	
	if ( popupHeight == undefined || popupHeight == null ) {
		popupHeight = 320;
	}
	
	var rand = new Date().getTime();
	if ( popupURL && popupURL.indexOf('?') ) {
		popupURL += "&rnd="+ rand;
	} else {
		popupURL += "?rnd="+ rand;
	}

	windowModal = window.showModelessDialog( popupURL, 
											 document, 
											 "scroll:no;help:no;status:no;dialogWidth:" + 
											 popupWidth + 
											 "px;dialogHeight:" + 
											 popupHeight + 
											 "px" 
											);
}

//abrirNovaJanela : Abre uma janela pop-up
function abrirNovaJanela(url, width, height) {
	if ( document.getElementById("STATE").value != "BROWSE" ) { 
    	var comprimento = 425;
    	var altura      = 320;
 
	    if (width != null && height != null) {
		    comprimento = width;
	    	altura      = height;
    	}
		
		var rand = new Date().getTime();
		if ( url && url.indexOf('?') > 0 ) {
			url += "&rnd="+ rand;
		} else {
			url += "?rnd="+ rand;
		}
		
    	windowModal = window.showModelessDialog(url, document, "help:no;status:no;scroll:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
		//windowModal = window.showModalDialog(url, document, "help:no;status:no;scrollbars:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
	}
	endProgress();
}

//abrirNovaJanela2 : Abre uma janela pop-up
function abrirNovaJanela2(url, width, height) {
   	var comprimento = 425;
   	var altura      = 320;
	
	if ( width && height ) {
	    comprimento = width;
	   	altura      = height;
    }
	
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}
	
    windowModal = window.showModelessDialog(url, document, "help:no;status:no;scroll:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
	endProgress();	
}

//abrirNovaJanela3 : Abre uma janela pop-up
function abrirNovaJanela3(url, width, height, arg) {
   	var comprimento = 425;
   	var altura      = 320;
	
	if (width != null && height != null) {
	    comprimento = width;
	   	altura      = height;
    }

	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}
	
    windowModal = window.showModelessDialog(url, arg, "help:no;status:no;scroll:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
	//windowModal = window.showModalDialog(url, arg, "help:no;status:no;scrollbars:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
	
	endProgress();	
}

//abrirNovaJanela4 : Abre uma janela pop-up
function abrirNovaJanela4(url, width, height, arg) {
   	var comprimento = 425;
   	var altura      = 320;
	
	if (width != null && height != null) {
	    comprimento = width;
	   	altura      = height;
    }
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}
    windowModal = window.showModalDialog(url, arg, "help:no;status:no;scroll:no;dialogWidth:" + comprimento + "px;dialogHeight:" + altura + "px");
	
	endProgress();	
}

// showPopup: Exibe uma janela pop-up de uma determinada URL
// Exemplo..: showPopup( DINAMIC_WEB_MODULE_NAME+'modulo/orcamento/popup/matrizPadraoPopupFiltro.jsp', '?campo=FILTRO_MATRIZ_CD', 640, 380 );
function showPopup( url, callbackField, windowPrefWidth, windowPrefHeight ) {
   	var windowWidth  = 425;
   	var windowHeight = 320;
	
	if ( ( windowPrefWidth != undefined ) && ( windowPrefWidth != null ) ) {
	    windowWidth  = windowPrefWidth;
    }
	
	if ( ( windowPrefHeight != undefined ) && ( windowPrefHeight != null ) ) {
		windowHeight = windowPrefHeight;
	}
	
	var windowTop  = ( 1024 - windowWidth ) / 2;
	var windowLeft = ( 768 - windowHeight ) / 2;
	
	var props = "'resize=0,toolbar=0,scrollbars=0,top="+windowTop+",left="+windowLeft+",width="+windowWidth+",height="+windowHeight+"'";
	
	url += callbackField;
	
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}	
	window.open( url, "Popup", props, true );
	
	endProgress();
}

function telaCheia( url, titulo ) {
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}	
	window.open( url, '', 'fullscreen=yes, scrollbars=auto' );
	endProgress();	
}

//abrirNovaRelatorio : Abre uma janela pop-up
function abrirJanelaRelatorio( url, valWidth, valHeight ) {
   	var comprimento = 425;
   	var altura      = 320;
	
	if ( valWidth != null && valWidth != comprimento ) {
	    comprimento = valWidth;
    }
	
	if ( valHeight != null && valHeight != altura ) {
		altura = valHeight;
	}
	
	var valTop  = ( 1024 - comprimento ) / 2;
	var valLeft = ( 768 - altura ) / 2;
	
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}
	window.open( url, "_blank", "'resize=1,toolbar=0,scrollbars=0,top=" + valTop + ",left=" + valLeft + ",width=" + comprimento + ",height=" + altura+ "'", true );
	
	endProgress();	
}

//abrirNovaRelatorio : Abre uma janela pop-up
function abrirJanelaRelatorio2(url, width, height) {
   	var comprimento = 1016;
   	var altura      = 711;
	
	if (width && height) {
	    comprimento = width;
	   	altura      = height;
    }
	
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}
	
	var options = "'resize=1,toolbar=0,scrollbars=1,top=1,left=0,width=" + comprimento + ",height=" + altura+"'";
	window.open(url, "_blank", options, true);
	
	
		
	endProgress();	
}

function abrirJanelaRelatorio3(url, width, height) {
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}	
	abrirNovaJanela3(url, width, height, document);
}

function openWindow( url, widthWindow, heightWindow ) {
	var rand = new Date().getTime();
	if ( url && url.indexOf('?') > 0 ) {
		url += "&rnd="+ rand;
	} else {
		url += "?rnd="+ rand;
	}	
	if ( widthWindow == null || widthWindow == undefined ) {
	    widthWindow  = 425;
	}
	
	if ( heightWindow == null || heightWindow == undefined ) {
	    heightWindow  = 320;
	}
	
    window.showModelessDialog( url, document, "help:no;status:no;scrollbars:no;dialogWidth:" + widthWindow + "px;dialogHeight:" + heightWindow + "px" );
}

//repassaValor : Repassa valor de determinado campo para a janela de chamada
function repassaValor(wwc, campo, valor){
	window.close();
	
	var field = wwc.getElementById(campo);
	
	field.changeOnFocus = "true";
	field.value = valor;
	field.onkeydown();
	field.focus();
	field.changeOnFocus = "false";
}

//fecharNovaJanela : Fecha uma janela pop-up
function fecharNovaJanela() {
	if (windowModal != null) {
		windowModal.close();
		windowModal = null;
	}
}

//Janela Popup -- Fim -----------------------------------------------

//checkField : verifica se o campo é nulo
function checkField(field) {
	if (field != null && field.text != "0" && field.text != "null") {
		return field.text;
	} else {
		return "";
	}
}

//checkField2 : verifica se o campo é nulo
function checkField2(field) {
	if (field != null) {
		return field.nodeValue;
	} else {
		return "";
	}
}

//checkFieldValue : verifica se o campo é nulo
function checkFieldValue(value) {
	if (value != "null") {
		return value;
	} else {
		return "";
	}
}

//Controla de abas na interface
function stAba(menu, conteudo) {
	this.menu = menu;
	this.conteudo = conteudo;
}

var arAbas = new Array();

function AlternarAbas(menu, conteudo) {

	for (i=0; i < arAbas.length; i++) {
		m = document.getElementById(arAbas[i].menu);
		m.className = 'menu';
		
		c = document.getElementById(arAbas[i].conteudo);
		c.style.display = 'none';
	}
	
	m = document.getElementById(menu);
	m.className = 'menu-sel';
	
	c = document.getElementById(conteudo);
	c.style.display = '';
}

//Controla de abas na interface
function stAba2(menu, conteudo) {
	this.menu = menu;
	this.conteudo = conteudo;
}

var arAbas2 = new Array();

function AlternarAbas2(menu, conteudo) {
	
	for (i=0; i < arAbas2.length; i++) {
		m = document.getElementById(arAbas2[i].menu);
		m.className = 'menu';
		
		c = document.getElementById(arAbas2[i].conteudo);
		c.style.display = 'none';
	}
	
	m = document.getElementById(menu);
	m.className = 'menu-sel';
	
	c = document.getElementById(conteudo);
	c.style.display = '';
}

function truncaDecimais( valor, casas, separador, separador2 ) {
	var result = "";
	
	var temp   = trim( valor );
	var tam    = temp.length;
	var sep    = temp.indexOf( ( separador2 == undefined ? '.' : separador2 ) );
	var dec    = ( tam - sep ) - 1;
	
	if ( dec < casas ) {
		result = retornaCasasDecimais( temp, casas, separador );
	} else {
		var parte1 = temp.substring( 0, sep );
		var parte2 = temp.substring( ( sep + 1 ), ( sep + casas + 1 ) );
		if ( casas > 0) {
			result = parte1 + separador + parte2;
		} else {
			result = parte1;
		}
	}
	
	return result;	
}

function displayCurrency( valor, casas, separador, separador2 ) {
	return truncaDecimais( floatTocurrency( parseFloat( truncaDecimais( valor, casas, separador ) ) ), casas, separador2, separador2 );
}

//completa casas decimais e troca separador decimal
function retornaCasasDecimais(valor, casas, separador) {
	var temp   = trim(valor);
	var tam    = temp.length;
	var result = "";
	var sep    = temp.indexOf('.');
	var temp2  = "";
	
	if (sep == -1) {
		sep = temp.indexOf(',');
		
		if (sep == -1) {
			result = temp + separador;
			
			for (count = 0; count < casas; count++) {
				result = result + "0";
			}
			
			return result;
		}
	}
	
	temp2  = temp.substring(0, sep) + separador;
	sep    = sep + 1;
	temp2  = temp2 + temp.substring(sep);
	temp   = temp2;
	result = temp.substring(0, sep);
	
	for (count = 0; count < casas; count++) {
		if (sep < tam) {
			result = result + temp.charAt(sep);
			sep++;
		} else {
			result = result + "0";
		}
	}
	
	return result;
}

//validaCampo
function validaCampo(campo, casas, separador) {
	if (trim(campo.value).length > 0) {
		if ((campo.value.indexOf(separador) == -1) && ((campo.maxLength - (casas + 1)) < campo.value.length)) {
			geraMessageBox("O valor informado excedeu o tamanho permitido.", "2");
			campo.value = "";
			setFocus(campo);
		} else {
			if (casas > 0) {
				if ((campo.value.indexOf('.') == 0) || (campo.value.indexOf(',') == 0)) {
					campo.value = "0" + campo.value;
				}
				
				campo.value = retornaCasasDecimais(campo.value, casas, ".");
				
				if (!isNaN(campo.value)) {
					campo.value = retornaCasasDecimais(campo.value, casas, separador);
				} else {
					geraMessageBox("O valor informado é inválido.", "2");
					campo.value = "";
					setFocus(campo);
				}
			} else {
				if (isNaN(campo.value)) {
					geraMessageBox("O valor informado é inválido.", "2");
					campo.value = "";
					setFocus(campo);
				}
			}
		}
	}
}

var LEFT_SIDE_col;
var RIGHT_SIDE_col;
var MIN_MAX_btn;

var LEFT_SIDE_FILTER_col;
var LEFT_SIDE_FILTER_inner;

function onResizeWindow() {
	var DIV_LEFT_SIDE = document.getElementById("LEFT_SIDE_FILTER");
	var DIV_FILTER    = document.getElementById("FILTER_DIV");
	var DIV_MAIN_BODY = document.getElementById("MAIN_BODY_DIV");
	var DIV_BUTTONS   = document.getElementById("formButtons");

	var newHeightFilter = document.body.clientHeight - 327;
	var newHeightBody   = null;
	
	if (DIV_BUTTONS.style.display != 'none')
		newHeightBody = document.body.clientHeight - 132;
	else
		newHeightBody = document.body.clientHeight - 109;
	
	if (DIV_LEFT_SIDE != null) 
		DIV_FILTER.style.height = (newHeightFilter > 80 ? newHeightFilter : 80);

	DIV_MAIN_BODY.style.height = (newHeightBody > 275 ? newHeightBody : 275);
}

function initMinMax() {

	var DIV_LEFT_SIDE = document.getElementById("LEFT_SIDE_FILTER");
	var DIV_FILTER    = document.getElementById("FILTER_DIV");
	var DIV_MAIN_BODY = document.getElementById("MAIN_BODY_DIV");
	
	if (DIV_LEFT_SIDE == null) 
		DIV_FILTER.style.height = "64px";

	document.body.style.overflowY = 'hidden';
	
	onResizeWindow();
	window.onresize = onResizeWindow;
	
	// exibe o menu
	/*
	document.getElementById("container").style.display = "inline";
	
	LEFT_SIDE_col  = document.getElementById("LEFT_SIDE");
	RIGHT_SIDE_col = document.getElementById("RIGHT_SIDE");
	MIN_MAX_btn    = document.getElementById("MIN_MAX");
	
	LEFT_SIDE_FILTER_col   = document.getElementById("LEFT_SIDE_FILTER");
	LEFT_SIDE_FILTER_inner = (LEFT_SIDE_FILTER_col != null ? LEFT_SIDE_FILTER_col.innerHTML : "&nbsp;");
	
	MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_esq.gif";
	LEFT_SIDE_col.width  = "185";
	RIGHT_SIDE_col.width = "100%";
	*/
}

function minMax() {
	if (LEFT_SIDE_col.width == "185") {
		MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_direita.gif";
		LEFT_SIDE_col.width  = "30";
		RIGHT_SIDE_col.width = "100%";
		
		if (LEFT_SIDE_FILTER_col != null) {
			LEFT_SIDE_FILTER_col.style.display = 'none';
		}
	} else {
		MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_esq.gif";
		LEFT_SIDE_col.width  = "185";
		RIGHT_SIDE_col.width = "100%";
		
		if (LEFT_SIDE_FILTER_col != null) {
			LEFT_SIDE_FILTER_col.style.display = '';
		}
	}
}

function initMinMax2() {
	
	// exibe o menu
	document.getElementById("container").style.display = "inline";
	
	LEFT_SIDE_col  = document.getElementById("LEFT_SIDE");
	RIGHT_SIDE_col = document.getElementById("RIGHT_SIDE");
	MIN_MAX_btn    = document.getElementById("MIN_MAX");
	
	LEFT_SIDE_FILTER_col   = document.getElementById("LEFT_SIDE_FILTER");
	LEFT_SIDE_FILTER_inner = (LEFT_SIDE_FILTER_col != null ? LEFT_SIDE_FILTER_col.innerHTML : "&nbsp;");
	
	MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_esq.gif";
	LEFT_SIDE_col.width  = "207";
	RIGHT_SIDE_col.width = "817";
}

function minMax2() {
	if (LEFT_SIDE_col.width == "207") {
		MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_direita.gif";
		LEFT_SIDE_col.width  = "30";
		RIGHT_SIDE_col.width = "889";
		
		if (LEFT_SIDE_FILTER_col != null) {
			LEFT_SIDE_FILTER_col.style.display = 'none';
		}
	} else {
		MIN_MAX_btn.src      = STATIC_WEB_MODULE_NAME+"image/seta_esq.gif";
		LEFT_SIDE_col.width  = "207";
		RIGHT_SIDE_col.width = "817";
		
		if (LEFT_SIDE_FILTER_col != null) {
			LEFT_SIDE_FILTER_col.style.display = '';
		}
	}
}

function encodeField(field) {
    if ( field != null ) {
          field = field.replace(/\+/g, '!!PLUS!!');
    }
    return field;
}

function decodeField(field) {
    if ( field != null ) {
          field = field.replace(/!!PLUS!!/g, '+');
    }
    return field;
}



function desHabilite(document, status){
	var fields = document.getElementsByTagName("input");
	
	for (i = 0; i < fields.length; i++) {
		if (fields[i].type != 'button') {
			if ( fields[i].name != "RECORD_COUNT" 
					&& fields[i].name.indexOf("FLT") < 0 && fields[i].name.indexOf("DESCRICAO_") < 0
					&& fields[i].name.indexOf("FILTRO") < 0 && fields[i].name.indexOf("DE_") < 0
					&& fields[i].name.indexOf("TOTAL") < 0 && fields[i].name.indexOf("PERC") < 0 
					&& fields[i].name.indexOf("DA_") < 0 && fields[i].name.indexOf("PESO") < 0  ) {
				
				fields[i].disabled = status;
				if (status)
					fields[i].style.backgroundColor = "#f5f5f5";
				else 
					fields[i].style.backgroundColor = "#ffffff";
				
				if( (fields[i].id == "CODIGO") && (!status) ) {
					setFocus(fields[i]);
				}
			} else if ( fields[i].name.indexOf("CD_") >= 0 || fields[i].id.indexOf("CD_") >= 0) {
				fields[i].disabled = status;
				if (status)
					fields[i].style.backgroundColor = "#f5f5f5";
				else 
					fields[i].style.backgroundColor = "#ffffff";
			}
		}
	}
	
	var fields2 = document.getElementsByTagName("select");
	
	if (fields2 != null) {
		for (i = 0; i < fields2.length; i++) {
			if ( fields2[i].id != 'UNIADM' && fields2[i].id != 'DOMAIN' && fields2[i].id != 'GROUP' && fields2[i].id != 'UNIT') {
				fields2[i].disabled = status;
			}
		}
	}
}

function clearFields(document){
	var fields = document.getElementsByTagName("input");
	
	for (i = 0; i < fields.length; i++) {
		if ((fields[i].type == "text") || (fields[i].type == "hidden")) {
			if (fields[i].id != "STATE") {
				if (fields[i].name != "RECORD_COUNT") {
					fields[i].value = "";
				}
			}
		}
	}
}


function nextFocus(doc, field){
	var fields = doc.getElementsByTagName("input");
	var encontrou = false;
	var firstEnableField = "-1";
	for (i = 0; i < fields.length; i++) {
		if ((fields[i].type != 'button') && (fields[i].type != 'hidden')) {
			if (fields[i].name == "RECORD_COUNT")
				continue;
			if((firstEnableField == "-1") && (! fields[i].disable)) //Esse é o primeiro campo habilitado.
				firstEnableField = fields[i].id;
				
			if(fields[i].id == field) { //Caso seja o field passado como argumento
				i = i + 3;
				for(; i < fields.length; i++) {
					if ((fields[i].type != 'button') && (fields[i].type != 'hidden')) {
						if (fields[i].name == "RECORD_COUNT")
							continue;
						if(! fields[i].disable) {
							encontrou = true;
							fields[i].focus();
							break;
						}
					}		
				}
				break;
			}
		}
	}
	if((!encontrou) && (firstEnableField != "-1")) {
		if(! doc.getElementById(firstEnableField).disable)
			doc.getElementById(firstEnableField).focus();
	}
}

function novoClick() {
	if (arAbas.length > 0) {
		AlternarAbas('td_cadastro','div_cadastro');
	}

	document.getElementById("STATE").value = "INSERT";
	desHabilite(document, false); 
	clearFields(document);
	editMode(true);
	document.getElementById("RECORD_COUNT").value = "*";
	doNovo();
}

function alterarClick() {
	if (arAbas.length > 0) {
		AlternarAbas('td_cadastro','div_cadastro');
	}
	
	document.getElementById("STATE").value = "UPDATE";
	desHabilite(document, false); 
	editMode(true);
}

function salvarClick() {
	if (document.getElementById("STATE").value == "INSERT") {
		doSalvar(); 
	} else {
		if (document.getElementById("STATE").value == "UPDATE") {
			doAlterar();
		}
	}
	editMode(false);
}

function pesquisarClick() {
	clearFields(document);
	
	document.getElementById("STATE").value = "SEARCH";
	document.getElementById("RECORD_COUNT").value = "?";
	
	desHabilite(document, false);
	
	document.getElementById("FIRST").disabled    = true;
	document.getElementById("PREVIOUS").disabled = true;
	document.getElementById("NEXT").disabled     = true;
	document.getElementById("LAST").disabled     = true;
	document.getElementById("SEARCH").disabled   = true;
	document.getElementById("NEW").disabled      = true;
	document.getElementById("UPDATE").disabled   = true;
	document.getElementById("DELETE").disabled   = true;							
	document.getElementById("PRINT").disabled    = true;							
	document.getElementById("SAVE").disabled     = true;									
	document.getElementById("CANCEL").disabled   = false;
	document.getElementById("REFRESH").disabled  = true;
	
	if (document.getElementById("QUERY") != null) {
		document.getElementById("QUERY").disabled = false;
	}
	
	if (document.getElementById("QUERY2") != null) {
		document.getElementById("QUERY2").disabled = false;
	}
	
	if (document.getElementById("QUERY3") != null) {
		document.getElementById("QUERY3").disabled = false;
	}
	editMode(true);
}	

function cancelarClick() {
	document.getElementById("STATE").value = "BROWSE";
	desHabilite(document, true);
	editMode(false);
	doCancelar(); 
}

function refreshClick() {
    doConsultarTodos();
    doDesenharGrid();
	editMode(false);
}

function editMode(status) {
	
	if (!status) document.getElementById("STATE").value = "BROWSE";
	
	var btnFirstRecord    = document.getElementById("FIRST");
	var btnPreviousRecord = document.getElementById("PREVIOUS");
	var btnNextRecord     = document.getElementById("NEXT");
	var btnLastRecord     = document.getElementById("LAST");
	var btnSearch		  = document.getElementById("SEARCH")
	var btnNew            = document.getElementById("NEW")
	var btnEdit           = document.getElementById("UPDATE")
	var btnSave           = document.getElementById("SAVE")
	var btnDelete         = document.getElementById("DELETE");
	var btnCancel         = document.getElementById("CANCEL");
	var btnRefresh        = document.getElementById("REFRESH");
	var btnPrint          = document.getElementById("PRINT");

	btnSearch.style.backgroundColor = "#f5f5fa";
	
	switch ( document.getElementById("STATE").value ) {
	case "BROWSE":
		btnFirstRecord.disabled    = false;
		btnPreviousRecord.disabled = false;
		btnNextRecord.disabled     = false;
		btnLastRecord.disabled     = false;
		btnSearch.disabled 		   = false;
		btnNew.disabled            = false;
		btnEdit.disabled           = false;
		btnSave.disabled           = true;
		btnDelete.disabled         = false;
		btnCancel.disabled         = true;
		btnRefresh.disabled        = false;
		btnPrint.disabled          = false;
		break;
	case "SEARCH":
		btnFirstRecord.disabled    = true;
		btnPreviousRecord.disabled = true;
		btnNextRecord.disabled     = true;
		btnLastRecord.disabled     = true;
		btnSearch.disabled         = true;
		btnNew.disabled            = true;
		btnEdit.disabled           = true;
		btnSave.disabled           = true;
		btnDelete.disabled         = true;
		btnCancel.disabled         = false;
		btnRefresh.disabled        = true;
		btnPrint.disabled          = true;
		break;
	case "INSERT":
	case "UPDATE":
		btnFirstRecord.disabled    = true;
		btnPreviousRecord.disabled = true;
		btnNextRecord.disabled     = true;
		btnLastRecord.disabled     = true;
		btnSearch.disabled 		   = true;
		btnNew.disabled            = true;
		btnEdit.disabled           = true;
		btnSave.disabled           = false;
		btnDelete.disabled         = true;
		btnCancel.disabled         = false;
		btnRefresh.disabled        = true;
		btnPrint.disabled          = true;
		break;
	default:
		btnFirstRecord.disabled    = false;
		btnPreviousRecord.disabled = false;
		btnNextRecord.disabled     = false;
		btnLastRecord.disabled     = false;
		btnSearch.disabled         = false;
		btnNew.disabled            = false;
		btnEdit.disabled           = false;
		btnSave.disabled           = true;
		btnDelete.disabled         = false;
		btnCancel.disabled         = true;
		btnRefresh.disabled        = false;
		btnPrint.disabled          = false;
	}
	
	if (document.getElementById("QUERY") != null) 
		document.getElementById("QUERY").disabled = !status;
	
	if (document.getElementById("QUERY2") != null) 
		document.getElementById("QUERY2").disabled = !status;
	
	if (document.getElementById("QUERY3") != null) 
		document.getElementById("QUERY3").disabled = !status;

	// set buttons opacity 
	if(btnFirstRecord.disabled)	   btnFirstRecord.style.filter="gray , alpha(opacity=30)";
	else 						   btnFirstRecord.style.filter="";
	if(btnPreviousRecord.disabled) btnPreviousRecord.style.filter="gray , alpha(opacity=30)";
	else 						   btnPreviousRecord.style.filter="";
	if(btnNextRecord.disabled)     btnNextRecord.style.filter="gray , alpha(opacity=30)";
	else 						   btnNextRecord.style.filter="";
	if(btnLastRecord.disabled)     btnLastRecord.style.filter="gray , alpha(opacity=30)";
	else 						   btnLastRecord.style.filter="";
	if(btnSearch.disabled)     	   btnSearch.style.filter="gray , alpha(opacity=30)";
	else 					   	   btnSearch.style.filter="";

	if(btnNew.disabled)  	btnNew.style.filter="gray , alpha(opacity=30)";
	else 					btnNew.style.filter="";
	if(btnEdit.disabled)  	btnEdit.style.filter="gray , alpha(opacity=30)";
	else 					btnEdit.style.filter="";
	if(btnSave.disabled)  	btnSave.style.filter="gray , alpha(opacity=30)";
	else 					btnSave.style.filter="";
	if(btnDelete.disabled)  btnDelete.style.filter="gray , alpha(opacity=17)";
	else 					btnDelete.style.filter="";
	if(btnCancel.disabled)  btnCancel.style.filter="gray , alpha(opacity=22)";
	else 					btnCancel.style.filter="";
	if(btnRefresh.disabled) btnRefresh.style.filter="gray , alpha(opacity=22)";
	else 					btnRefresh.style.filter="";
	if(btnPrint.disabled)  	btnPrint.style.filter="gray , alpha(opacity=30)";
	else 					btnPrint.style.filter="";
}

//createShowField
//Ex.: <script>createShowField("DA_CLASSE_FERTILIDADE");</script>
//<input name="DA_CLASSE_FERTILIDADE" type="text" class="textfield" id="DA_CLASSE_FERTILIDADE" size="35" maxlength="30" disabled>
function createShowField(name) {
	var src = "";
	
	src += "<table height=\"16\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">";
	src += "<tr>";
	src += "<td class=\"readonly_field\">";
	src += "<div id=\"" + name + "\">&nbsp;</div>";
	src += "</td>";
	src += "</tr>";
	src += "</table>";
	
	document.write(src);
}

//trocaSeparador : Troca determinado caracter por outro de uma string
function trocaSeparador(valor, separador1, separador2) {
	var result = valor;
		
	if ( valor.indexOf(separador1) > - 1) {
		result = valor.split(separador1);
		result = result.join(separador2);
	}
		
	return result;
}

//doDoubleToTime : transforma um Double em um Time
function doDoubleToTime( doubleValue, decimalSeparator ) {
	decimalSeparator = ( decimalSeparator == undefined ? "." : decimalSeparator );
	
	var sep  = doubleValue.indexOf( decimalSeparator );
	var temp = doubleValue.substring( 0, sep );
	var cont = temp.length;
	
	var result = null;
	
	if ( cont < 2 ) {
		result = "0" + doubleValue.substring( 0, 1 ) + ":" + doubleValue.substring( 2, 4 );
	} else {
		result = doubleValue.substring( 0, 2 ) + ":" + doubleValue.substring( 3, 5 );
	}
	
	return result;
}

//Funções criadas pelo Dreamweaver para a troca de imagens
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function changeStyle(component, styleClass) {
	component.className = styleClass;
}

var teclaPressionada = false;

function ativar(ev, status) {
	if(window.event) {
		if(ev.keyCode == 17) {
			teclaPressionada = status;
		}
	}
}

function changeStyle(component, styleCSS) {
	component.className = styleCSS
}

//initRequest : inicia requisicao XML
function initRequest() {
	runProgress();
	
   	if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}

//DAYS_FROM_MONTHS : qtde de Dias dos Meses
var DAYS_FROM_MONTHS = new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

//isAnoBissexto : verifica se o ano é Bissexto
function isAnoBissexto( ano ) {
	var result     = false;
	var anoInicial = 1968;
	
	if ( anoInicial < ano ) {
		while ( anoInicial < ano ) {
			anoInicial = anoInicial + 4;
		}
		
		if ( anoInicial == ano ) {
			result = true;
		} 
	}
	
	return result;
}

function showUploadForm( recordName, processAction, objectName ) {
	//toClipBoard(DINAMIC_WEB_MODULE_NAME+"util/attachment-frame.jsp?recordName="+recordName+"&objectName="+objectName+"&processAction="+DINAMIC_WEB_MODULE_NAME+processAction);
	abrirNovaJanela2(DINAMIC_WEB_MODULE_NAME+"util/attachment-frame.jsp?recordName="+recordName+"&objectName="+objectName+"&processAction="+DINAMIC_WEB_MODULE_NAME+processAction,768,480);
}


function doUpload() {
	var name = document.attachment.myFile.value;
	runProgress();	
	document.attachment.submit();
	endProgress();	
	geraMessageBox('Arquivo '+name+' carregado com sucesso','2');
}

function hide( component ) {
	var comp = document.getElementById( component );
	if ( comp != null ) {
		comp.style.display = 'none';
	}
}

function show( component ) {
	var comp = document.getElementById( component );
	if ( comp != null ) {
		comp.style.display = 'inline';
	}
}

var STARTING_YEAR = 2000;
function generateYearCombo( comboName ) {
	var today = new Date();
	var year  = today.getFullYear();
	var total = ( ( year - STARTING_YEAR ) > 0 ? ( year - STARTING_YEAR ) + 1 : STARTING_YEAR );
	
	var combo = document.getElementById( comboName );
	combo.length = ( total + 5 );
	
	var i = 0;
	var count = STARTING_YEAR;
	
	while ( count <= ( year + 5 ) ) {
		combo.options[i].value = count + "";
		combo.options[i].text  = count + "";
		
		i++;
		count++;
	}
	
	combo.value = year;
	
	return combo;
}

function checkChars( fieldId ) {
	var field = document.getElementById( fieldId );
	if ( field != null ) {
		var valor = field.value;
		if ( valor.indexOf("-") > 0  || valor.indexOf(";") >0  ) {
			field.value = valor.substring(0, valor.length -1 );
			field.focus();
			return false;
		} else {
			return true;
		}
	} else {
		return true;
	}
}

function getIdUnidadeAdm( field ) {
	var UNIDADE_field;
	var idUnidadeAdm = "";
	if ( field == null ) {
		UNIDADE_field = document.getElementById("UNIADM");
	} else {
		UNIDADE_field = document.getElementById( field );
	}
	var options = UNIDADE_field.options;
	idUnidadeAdm = options[0].value;	
	return idUnidadeAdm;
}

/**
		 * Função para construir a tabela de detalhes sem registro algum,
		 * apenas para desenhar o layout dela
		 */
function tableWithoutData( crudObject ) {
	var nullXML = crudObject.getXML( null );
	crudObject.xmlDataSource = createXMLDOMV2( null, false );
	crudObject.xmlDataSource.loadXML( nullXML );
	crudObject.doDesenharGrid();
} 


/** 
 * 
 * Função parse string
 */
function splitString ( paramString, separador ) {
		
	var result = paramString.split( separador );
	
	return result;
}

/*
 * floatTocurrency( floatValue ) : 
 * A partir de um valor float retorna o valor formatado com separador de milhar e vírgula nos centavos.
 */
function floatTocurrency( floatValue ) {
	x = 0;
	
	if ( floatValue < 0 ) {
		floatValue = Math.abs( floatValue );
		x = 1;
	}
	
	if ( isNaN( floatValue ) ) floatValue = "0";
	
	cents = Math.floor( ( floatValue * 100 + 0.5 ) % 100 );
	
	floatValue = Math.floor( ( floatValue * 100 + 0.5 ) / 100 ).toString();
	
	if ( cents < 10 ) cents = "0" + cents;
	
	for ( var i = 0; i < Math.floor( ( floatValue.length - ( 1 + i ) ) / 3 ); i++ )
		floatValue = floatValue.substring( 0, floatValue.length - ( 4 * i + 3 ) ) + '.' + floatValue.substring( floatValue.length - ( 4 * i + 3 ) );
	
	ret = floatValue + ',' + cents;
	
	if ( x == 1 ) ret = ' - ' + ret;
	
	return ret;
}

/*
 * currencyTofloat( currencyValue ):
 * Pega um valor formatado com virgula e separador de milha e o transforma em float.
 */
function currencyTofloat( currencyValue ) {
	while ( currencyValue.indexOf( "." ) > -1 ) {
		currencyValue = currencyValue.replace( ".", "" );
	}
	
	currencyValue = currencyValue.replace( ",", "." );
	
	return parseFloat( currencyValue );
}

/*
 * roundNumber( rnum ):
 * arredonda valores em um certo número de casas decimais.
 */
function roundNumber( rnum ) {
	return Math.round( rnum * Math.pow( 10,2 ) ) / Math.pow( 10,2 );
}


/**
 * Retorna dias do mes
 * @param {Object} month
 * @param {Object} year
 */
function daysInMonth(month,year) {
	var dd = new Date(year, month, 0);
	return dd.getDate();
}

function limite(campo, countcampo, maxlimit)
{
if (campo.value.length > maxlimit){
	geraMessageBox("Você atingiu o limite máximo de " + maxlimit + " caracteres.", "2");	
  campo.value = campo.value.substring(0, maxlimit);
  }
else
  countcampo.value = maxlimit - campo.value.length;
}

function showRendimento(idNivel, btn) { 
	var elements = getElementsByName_iefix('tr', idNivel ); 
	for ( var i =0; i<elements.length; i++) { 
		var element = elements[i]; 
		if ( element && element.style.display == 'none' ) { 
			element.style.display = 'inline'; 
		} else if ( element && element.style.display == 'inline' ) { 
			element.style.display = 'none'; 
		} 
	}
	if ( btn && btn.value == '+') {
		btn.value = '-';
	} else if ( btn && btn.value == '-') {
		btn.value = '+';
	}
}

function getElementsByName_iefix(tag, name) {
    
    var elem = document.getElementsByTagName(tag);
    var arr = new Array();
    for(i = 0,iarr = 0; i < elem.length; i++) {
         att = elem[i].getAttribute("name");
         if(att == name) {
              arr[iarr] = elem[i];
              iarr++;
         }
    }
    return arr;
}

function converterHoraRelogioDecimal (time) {
	var hora = time.split(':')[0];
	var minuto = time.split(':')[1];
	return ( parseFloat(hora) +  ( parseFloat(minuto) / 60) );
}

function converterDecimalHoraRelogio(valor) {
	var entrada = valor +"";
	entrada = entrada.replace(",",".");
	if ( entrada.indexOf(".") == -1) {
		entrada += ".00";
	} else {
		entrada += "0";
	}
	var hora = entrada.split('.')[0];
	if ( parseInt( hora ) < 10 ) {
		hora = "0"+hora;
	}
	var min = entrada.split('.')[1];
	if ( min && min.length > 2 ) {
		min = min.substring(0,2);
	} 
	var minutos = Math.round( (min * 60) / 100 );
	minutos = parseInt( minutos )+"";
	if ( parseInt( minutos ) < 10) {
		minutos = "0"+minutos;
	}
	var relogio = hora +":"+minutos;
	return relogio;
}


function clearCombo(comboBox) {
	if ( comboBox && comboBox.options ) {
		while (comboBox.options.length > 0) {
			comboBox.options[0] = null;
		}
		comboBox.options.length = 0;
	}
}

function createOption (text, value, id, title) {
	var option = new Option( text, value );
	if ( id ) {
		option.id = id;
	}
	if ( title ) {
		option.title = title;
	}
	return option;
}

/**
 * arrayToString - Transformar o conteúdo de um Array em um String formatado ("X, X, e X") sem repetição.
 * @param pArray - O array alvo
 */
function arrayToString(pArray) {
	var strReturn = "";

	pArray.sort();
	
	if (pArray.length) {
		var newArray = new Array();
		newArray.push(pArray[0]);
		for(i = 1; i < pArray.length; i++) {
			if (pArray[i] != pArray[i-1]) {
				newArray.push(pArray[i]);
			}
		}
		
		var strReturn = "";
		strReturn += newArray[0];
		
		for(i = 1; i < newArray.length; i++) {
			if (i < newArray.length - 1) strReturn += ", ";
			else					     strReturn += " e ";			
			strReturn += newArray[i];
		}
	}
	
	return strReturn;
}

/**
 * indexOf
 */
function indexOf(array, value)
{
    var len = array.length;

    for (var from = 0; from < len; from++)
    {
      if (from in array && array[from] === value)
        return from;
    }
    return -1;
};


/**
 * updateXMLRecord - Atualizar RecordData após Alteração
 * @param recordNode - O nó a ser atualizado
 * @param serviceName - O nome do serviço para fazer a consulta pelo Id
 * @param tagName - A tag do xml para para fazer a consulta pelo Id
 */
function updateXMLRecord(recordNode, serviceName, tagName, callback) {
	
	var id;   
	try {
		id = recordNode.getElementsByTagName("id")[0].firstChild.nodeValue;
	} catch(e) { return; }
	
	var url  = DINAMIC_WEB_MODULE_NAME + serviceName + ".do?method=selecionarPeloId";
	var data = "&xml=";
	data += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
	data += "<resultset>";
	data += "<" + tagName + " action=\"select\">"
	data += "<id>" + id + "</id>"
	data += "</" + tagName + ">"
	data += "</resultset>"
	
	req = getXMLHTTPRequest();
	    req.onreadystatechange = function() {
   	    if (req.readyState == 4) {
   	    	if (req.status == 200) {
   	    		parseUpdateXMLRecord(req, recordNode, tagName, callback);
	        } 
       	}
    };
	req.open("POST", url , false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");   	    
   	req.send(data);
}

function parseUpdateXMLRecord(response, recordNode, tagName, callback) {
	var responseXML = getXMLDOM(false);
	responseXML.loadXML(response.responseText);
	
	if ( responseXML.getElementsByTagName(tagName)[0] != null ) {
		var newNode = responseXML.getElementsByTagName(tagName)[0];
		
		var i = 0;
		for(; i < recordNode.childNodes.length; i++) 
		{
			var nodeName     = recordNode.childNodes[i].nodeName;
			var newNodeChild = null;

			if (newNode.getElementsByTagName(nodeName)[0] != null) {
				if (newNode.getElementsByTagName(nodeName)[0].hasChildNodes()) {
					newNodeChild = newNode.getElementsByTagName(nodeName)[0].firstChild.cloneNode(false);
				}
				
				if (recordNode.getElementsByTagName(nodeName)[0].hasChildNodes()) {
					if (newNodeChild != null) {
						recordNode.getElementsByTagName(nodeName)[0].firstChild.nodeValue = newNodeChild.nodeValue;			
					} else {
						recordNode.getElementsByTagName(nodeName)[0].firstChild.nodeValue = "";
					}
				} else {
					if (newNodeChild != null) recordNode.getElementsByTagName(nodeName)[0].appendChild(newNodeChild);
				}
			}
		}		
	} else {
		
	}
	
	if (callback != "undefined") eval(callback);
}

/**
 * updateXMLNodes - Atualizar xmlDestiny com os campos de xmlSource
 */
function updateXMLNodes(xmlSource, xmlDestiny) {
	var i = 0;
	for(; i < xmlSource.childNodes.length; i++) 
	{
		var name = xmlSource.childNodes[i].nodeName;
		try {
			xmlDestiny.getElementsByTagName(name)[0].firstChild.nodeValue = xmlSource.getElementsByTagName(name)[0].firstChild.nodeValue;
		} catch(e) {}
	}	
}

/**
 * selectPRXParameter - Selecionar valor de parametro da tabela PRXPARAMETER
 * @param pNome - Nome do Parâmetro
 * @param pContexto - Contexto do Parâmetro
 * @param pCampo - Campo de retorno
 */
function selectPRXParameter(pNome, pContexto, pCampo, pCallback) {
	var xml = "";
	xml += "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>";
	xml += "<resultset>";
	xml += "<parametro action=\"select\">";
	xml += "<nomeParametro>" + pNome + "</nomeParametro>";
	xml += "<contexto>" + pContexto + "</contexto>";
	xml += "</parametro>";
	xml += "</resultset>";
	
	runProgress();
   	var url   = DINAMIC_WEB_MODULE_NAME + "manterParametro.do?method=selecionarValorParametro";
	var param = "&xml=" + escape(xml);
	var data  = param;
	
	req = getXMLHTTPRequest();
	    req.onreadystatechange = function() {
		    if (req.readyState == 4) {
   		    if (req.status == 200) {
   		    	parsePRXParameter(req, pCampo, pCallback);
            } 
       	}
	};
    req.open("POST", url , false);
	req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	req.send(data);
	endProgress();
}

function parsePRXParameter(response, pCampo, pCallback) {
	var tmpDOM = getXMLDOM(false);
	tmpDOM.loadXML( response.responseText ); 

	if ( tmpDOM.getElementsByTagName("parametro")[0] != null ) {
		var xmlResponse = tmpDOM.getElementsByTagName("parametro");

		$(pCampo).value = xmlResponse[0].getElementsByTagName("valorParametro")[0].firstChild.nodeValue;
		if (pCallback != "undefined") eval(pCallback);
	} else {
		geraMessageBox( "Parâmetro não configurado para este caso." , "3" );
	}
}

/**
 * maxLength - Limitar os caracteres para tags TEXTAREA
 */
function maxLength(obj, limit) {
	if (obj.value.length >= limit) {
		obj.value = obj.value.substring(0, limit-1);
	}
}


/**
 * setEnterKeyToTab - Função responsável por substituir a função da tecla TAB pela tecla ENTER.
 */
function setEnterKeyToTab() {
	document.onkeydown = function () {
		if (event.keyCode == 13 && event.srcElement.name != 'pass' && event.srcElement.name != 'loginForm' ) 
		{
			if (event.srcElement.nodeName == 'A') 
			{
				event.srcElement.click();
				return null;
			}
			
			if ((event.srcElement.type!='textarea' && event.srcElement.type!='submit' && event.srcElement.type!='button') || (event.srcElement.className == "btn_search"))
			{
				event.keyCode = 9; 
				return event.keyCode;
			}
		}
	}	
}
setEnterKeyToTab();


/**
 * subMonths() - Retorna a quantidade de meses entre um intervalo de datas
 *    			 
 *    subMonths(strDateStart, strDateStart)
 *      0 1 2 3 4 5 6 7 8 9  
 * Ex.: 1 7 / 0 1 / 2 0 1 0 
 *
 * strDateStart  = "17/01/2010";
 * strDateEnd    = "19/01/2010";
 * monthsResult  = subMonths( strDateStart, strDateEnd );
 */
 
function subMonths(strDateStart, strDateEnd){
	var months;
	var monthStart;
	var yearStart;
	
	var monthEnd;
	var yearEnd;

	if( (strDateStart && strDateEnd) && (strDateStart.value.length > 0 && strDateEnd.value.length > 0 )){
		
		if ( strDateStart.value.length == 10 && strDateEnd.value.length == 10 ) {
			
			if ( !verificarPeriodo( strDateStart.value, strDateEnd.value ) ) {
				geraMessageBox( "A \"Data Final\" não pode ser menor que a \"Data Inicial\".", "2" );
				strDateEnd.value = "";
				strDateStart.focus();
				return false;
			} else {
				monthStart    = Number( strDateStart.value.substring( 3, 5 ) );
				yearStart     = Number( strDateStart.value.substring( 6, 10 ) );
				
				monthEnd      = Number( strDateEnd.value.substring( 3, 5 ) );
				yearEnd       = Number( strDateEnd.value.substring( 6, 10 ) );
				
				months = (((yearEnd*12)+ monthEnd ) - ((yearStart*12)+ monthStart )) + 1;
				 
				return months;	
			}
		} 
	} else {
		return;
	}
}

/**
 * setMessageStatusEAI - Função responsável por setar a mensagem em apontamentos com Finalizar
 */
function setMessageStatusEAI (statusField, messageField) {
	var status = statusField.value;
	switch (status) 
	{
		case '1':
			messageField.style.visibility = 'visible';
			messageField.value = 'Aguardando Integração. Não pode ser alterado!';
			break;
		case '2':
			messageField.style.visibility = 'visible';
			messageField.value = 'Enviado para integração! Aguardando processamento e valoração!';
			break;
		case '3':
			messageField.style.visibility = 'visible';
			messageField.value = 'Falha na integração!';
			break;
		case '4':
			messageField.style.visibility = 'visible';
			messageField.value = 'Integrado com sucesso!';			
			break;
		case '7':
			messageField.style.visibility = 'visible';
			messageField.value = 'Boletim liberado para alteração!';
			break;
		case '9':
			messageField.style.visibility = 'visible';
			messageField.value = 'Já integrado. Não pode ser alterado!';
			break;
		default:
			messageField.style.visibility = 'hidden';
			messageField.value = '';
			break;
	}
}

/**
 * setFocus - Função responsável por setar o foco em um campo.
 */
function setFocus(element) {
	if (isVisible(element) && !element.disabled) { 
		element.focus(); 
	}
}

/**
 * isVisible  - Retorna true se o elemento for visível.
 * @param obj - Elemento HTML
 */
function isVisible(obj)
{
    if (obj == document) return true;
    
    if (!obj) return false;
    if (!obj.parentNode) return false;

    if (obj.type == 'hidden') return false;
    
    if (obj.style) {
        if (obj.style.display == 'none') return false;
        if (obj.style.visibility == 'hidden') return false;
    }
    
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "");
        if (style.display == 'none') return false;
        if (style.visibility == 'hidden') return false;
    }
    
    var style = obj.currentStyle;
    if (style) {
        if (style['display'] == 'none') return false;
        if (style['visibility'] == 'hidden') return false;
    }
    
    return isVisible(obj.parentNode);
}

/**
 * doDisableFields  - Desabilita campos na tela.
 * @param obj - Array de campos a serem desabilitados.
 */

function doDisableFields(list, keep) {
	for(var i in list){
		list[i].disabled = true;
		list[i].style.backgroundColor = "#f5f5f5";
		if (keep == undefined)
			list[i].value = "";
	}
}

/**
 * doEnableFields  - Habilita campos na tela.
 * @param obj - Array de campos a serem habilitados.
 */

function doEnableFields(list, keep) {
	for(var i in list){
		list[i].disabled = false;
		list[i].style.backgroundColor = "#ffffff";
		if (keep == undefined)
			list[i].value = "";
	}
}

function doComparaCodigoInicialFinal(ccustoInicial, ccustoFinal){
	
	var codigoInicial = parseInt( $("CODIGO_" + ccustoInicial).value);
	var codigoFinal = parseInt ($("CODIGO_" + ccustoFinal).value);
	var labelInicial = window["label"+ccustoInicial];
	var labelFinal = window["label"+ccustoFinal];
	
	if(codigoInicial!= null && codigoFinal != null && codigoFinal < codigoInicial){
		geraMessageBox( termosEspecificos.O_X_MAIOR_QUE_Y, "2", [labelInicial, labelFinal]);
		$("ID_" + ccustoInicial).value        = "";
		$("CODIGO_" + ccustoInicial).value    = "";
		$("DESCRICAO_" + ccustoInicial).value = "";
		setFocus($("CODIGO_" + ccustoInicial));
		return false;
	}
}


