var pagStrErro='';
var pagStrBotao='';

function Submete( asPagina )
{
	document.forms[0].action = asPagina;
	document.forms[0].submit();
}

function Trim(sTrim)
{
	var String = sTrim;
	var Resultado = String;

	//Retira os espaços do inicio. Enquanto o primeiro caracter for igual à "Espaço" 1 caracter do inicio é removido.
	var i = 0;

	if (Resultado.charCodeAt(2-1) == '32'){
	}

	while (Resultado.charCodeAt(0) == '32'){
		Resultado = String.substring(i,String.length);
		i++;
	}

	//Pega a string já formatada e agora retira os espaços do final
	//mesmo esquema, enquanto o ultimo caracter for um espaço,
	//ele retira 1 caracter do final...

	while(Resultado.charCodeAt(Resultado.length-1) == '32'){
		Resultado = Resultado.substring(0,Resultado.length-1);
	}
	String = "";
	return Resultado;
}

function fnAbrePopup( asURL, asTarget, aiLargura, aiAltura, aiOpcoes, aiScroll, aiResize )
	{
	var oJanela;
	var sOpcoes;

	sOpcoes = "";
	if ( parseInt( navigator.appVersion ) < 4 )
		{
		sOpcoes	= "toolbar=no,location=no,address=no,directories=no,status=no,menubar=no,copyhistory=yes,maximized=yes"
					+ ",width=" + aiLargura + ",height=" + aiAltura;
		}
	else
		{
		var lX = screen.width	- aiLargura;		// Posição X da janela
		var lY = screen.height	- aiAltura;			// Posição y da janela

		if ( lX != 0 )
			{
			lX = Math.round( lX / 0.5 );
			lY = Math.round( lY / 0.5 );
			}
		sOpcoes = aiOpcoes;
		sOpcoes	+= ",width=" + aiLargura + ",height=" + aiAltura;

		}
	if ( aiScroll > 0 )
		sOpcoes += ",scrollbars=yes";
	else
		sOpcoes += ",scrollbars=no";

	if ( aiResize > 0 )
		sOpcoes += ",resizable=yes";
	else
		sOpcoes += ",resizable=no";

	//aoTelaPai.open( asURL, "pop", sOpcoes );
	window.open( asURL, asTarget, sOpcoes );
	}

//Rejeita caracteres especificados em lista, separados por · (ASCII alt + 250)
function fnEvnRejeitaChar(peStrCharList)
{
	var locBitRetorno = true;
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locVetCharRejeitado = peStrCharList.split('·');

	for (i=0; i<locVetCharRejeitado.length; i++)
	{
		if(peCharEntrada == locVetCharRejeitado[i])
		{
			locBitRetorno = false;
			break;
		}
	}

	if (locBitRetorno)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
//Controla a máscara para campos de valores do tipo moeda
function fnEvnEntradaMoedaMascara(peStrcampo, peStrMil, peStrDec, peMaxcampo)
{
	e = event;

	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = peStrcampo.value.length;
	for(i = 0; i < len; i++)
		if ((peStrcampo.value.charAt(i) != '0') && (peStrcampo.value.charAt(i) != peStrDec)) break;

	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(peStrcampo.value.charAt(i))!=-1) aux += peStrcampo.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) peStrcampo.value = '';
	if (len == 1) peStrcampo.value = '0'+ peStrDec + '0' + aux;
	if (len == 2) peStrcampo.value = '0'+ peStrDec + aux;
	if (len < peMaxcampo)
	{
		if (len > 2)
		{
			aux2 = '';
			for (j = 0, i = len - 3; i >= 0; i--)
			{
				if (j == 3)
				{
					aux2 += peStrMil;
					j = 0;
				}
				aux2 += aux.charAt(i);
				j++;
			}
			peStrcampo.value = '';
			len2 = aux2.length;
			for (i = len2 - 1; i >= 0; i--)
			peStrcampo.value += aux2.charAt(i);
			peStrcampo.value += peStrDec + aux.substr(len - 2, len);
		}
	}
	else
	{
		return false;
	}
	return false;
}
// Controla a entrada de dados para campos do tipo "NOME"
function fnEvnEntradaNome()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-záãèêíóõúçÇÁÃÉÊÍÓÔÕÚ .]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}

// Controla a entrada de dados para camnpos do tipo "CHAVE"
function fnEvnEntradaChave()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-z0-9]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}

// Controla a entrada de dados para camnpos do tipo "ENDERECO"
function fnEvnEntradaEndereco()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-z0-9áãèêíóõúçÇÁÃÉÊÍÔÓÕÚºª().\/\-, ]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
// Controla a entrada de dados para camnpos do tipo "ENDERECO"
function fnEvnEntradaPlicAspas()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /['"]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
// Controla a entrada de dados para camnpos do tipo "ENDERECO"
function fnEvnEntradaMoeda()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^0-9,.]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
// Controla a entrada de dados para campos do tipo "Email"
function fnEvnEntradaEmail()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-z0-9@().\/\-, ]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
// Controla a entrada de dados para campos do tipo "NUMERO"
function fnEvnEntradaNumeros()
{
	var peCharEntrada		= String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^0-9]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
// Controla a entrada de dados para campos do tipo "DATA"
function fnEvnEntradaData()
{
	var peCharEntrada		= String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^0-9/]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
//Controla a entrada de dados para camnpos do tipo "CHAVE" (Somente letras e números)
function fnEvnEntradaAlfa()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-z]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}

//Controla a entrada de dados para camnpos do tipo "CHAVE" (Somente letras e números)
function fnEvnEntradaChave()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[^A-Za-z0-9]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}

//Verificar os preenchimentos mínimo e máximo de um campo
function fnStrVerificaPreenchimento(peStrcampo, peStrDescricao, peIntMin, peIntMax, peStrMensagemOpcional)
{
	if ( (peStrcampo.value.length == 0) && (peIntMin != 0) ){
		pagStrErro += peStrMensagemOpcional + '.\n';
		return false;
	}
	if (peStrcampo.value.length < peIntMin)
	{
		//if (peStrMensagemOpcional == '')
		//{
			pagStrErro += '-O prenchimento mínimo para o campo [' + peStrDescricao + '] é de ' + peIntMin + ' caracter(es).\n';
		//}
		//else
		//{
		//	pagStrErro += peStrMensagemOpcional + '.\n';
		//}
		return false;
	}

	if (peStrcampo.value.length > peIntMax)
	{
		//if (peStrMensagemOpcional == '')
		//{
			pagStrErro += '-O prenchimento máximo para o campo [' + peStrDescricao + '] é de ' + peIntMax + ' caracter(es).\n';
		//}
		//else
		//{
		//	pagStrErro += peStrMensagemOpcional + '\n';
		//}
		return false;
	}
	return true;
}

function fnStrVerificaPreenchimentoLista(peStrcampo, peStrDescricao, peIntMin, peIntMax, peStrMensagemOpcional)
{
	if ( (peStrcampo.value.length == 0) && (peIntMin != 0) ){
		pagStrErro += '- Selecione ao menos um [' + peStrDescricao + '].\n';
		return false;
	}
	return true;
}

//Verificar os preenchimentos mínimo e máximo de um campo
function fnStrVerificaPreenchimentoFixo(peStrcampo, peStrDescricao, peIntMin, peIntMax, peStrMensagemOpcional)
{
	if ( (peStrcampo.value.length == 0) ){
			//pagStrErro += peStrMensagemOpcional + '.\n';
		return false;
	}
	if (peStrcampo.value.length < peIntMin)
	{
		//if (peStrMensagemOpcional == '')
		//{
			pagStrErro += '-O prenchimento mínimo para o campo [' + peStrDescricao + '] é de ' + peIntMin + ' caracter(es).\n';
		//}
		//else
		//{
		//	pagStrErro += peStrMensagemOpcional + '.\n';
		//}
		return false;
	}

	if (peStrcampo.value.length > peIntMax)
	{
		//if (peStrMensagemOpcional == '')
		//{
			pagStrErro += '-O prenchimento máximo para o campo [' + peStrDescricao + '] é de ' + peIntMax + ' caracter(es).\n';
		//}
		//else
		//{
		//	pagStrErro += peStrMensagemOpcional + '\n';
		//}
		return false;
	}
	return true;
}

// Verifica o conteúdo de campos do tipo "NOME"
function fnStrVerificaNome(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^A-Za-záãêèíóõúçÇÁÃÉÊÍÓÕÚ .$]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}

// Verifica o conteúdo de campos do tipo "CHAVE"
function fnStrVerificaAlfa(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^A-Za-z]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}

// Verifica o conteúdo de campos do tipo "CHAVE"
function fnStrVerificaChave(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^A-Za-z0-9]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}

// Verifica o conteúdo de campos do tipo "ENDERECO"
function fnStrVerificaEndereco(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^A-Za-z0-9áãêèíóõúçÇÀÁÃÉÊÍÓÕÚºª().\/\-, $]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-" + peStrDescricao + " [" + locRetorno + "] \n";
		return false;
	}
}

// Verifica o conteúdo de campos do tipo ' "
function fnStrVerificaPlicAspas(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /['"]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}
// Verifica o conteúdo de campos do tipo '
function fnStrVerificaPlic(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[']/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}
// Verifica o conteúdo de campos do tipo "NUMERO"
function fnStrVerificaNumeros(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^0-9$]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}

// Verifica o conteúdo de campos do tipo "EMAIL"
function fnStrVerificaEmail(peStrcampo, peStrDescricao)
{
	if (peStrcampo.value != '')
	{
		var peStrMail = peStrcampo.value;
		var locStrExpression	= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;


		if (locStrExpression.test(peStrMail))
		{
			return true;
		}
		else
		{
			pagStrErro += "-Endereço de email inválido!\n";
			return false;

		}
	}
}

// Verifica o conteúdo de campos do tipo "DATA"
function fnStrVerificaData(peStrcampo, peStrDescricao)
{
    var peStrData = peStrcampo.value;

    var dia = Number(peStrData.substring(0,2));
    var mes = Number(peStrData.substring(3,5));
    var ano = Number(peStrData.substring(6));
    var ultDiaMes = 0;

    if(peStrData == '')
    {
		return true;
    }

    if (ano < 1900)
    {
        pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
        return false;
	}

    if (mes == 2)
    {
        if (ano % 4 == 0)
        {
            ultDiaMes = 29;
		}
        else
        {
            ultDiaMes = 28;
		}
    }
    else if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12)
	{
        ultDiaMes = 31;
	}
    else if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
	{
        ultDiaMes = 30;
	}
    else
    {
   		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
        return false;
    }

    if (dia < 1 || dia > ultDiaMes)
    {
   		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
        return false;
    }
	return true;
}

// Verifica o conteúdo dos campos do tipo moeda (números, vírgula e ponto)
function fnStrVerificaMoeda(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /[^0-9,.$]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "Caracter inválido [" + locRetorno + "] no campo [" + peStrDescricao + "]\n";
		return false;
	}
}

// Verifica o conteúdo dos campos com respeito à mascara especificada.
function fnStrVerificaMascara(peStrcampo, peStrDescricao, peStrMascara)
{
	var locMascChar;
	var loccampoChar;
	var locNumeros='0123456789';
	var locLetras='abcdefghijklmnopqrstuvxzABCDEFGHIJKLMNOPQRSTUVXZáàâãÁÀÂÃéèêÉÈÊíìîÍÌÎÓÒÔÕóòôõÚÙÛúùûçÇñÑ ';
	var locValorcampo = peStrcampo.value;

	if(locValorcampo.length == 0)
	{
		return true;
	}

	if (locValorcampo.length != peStrMascara.length)
	{
		pagStrErro += "-O campo [" + peStrDescricao + "] não está devidamente preenchido.\n";
		return false;
	}

	for (locIntCount=0; locIntCount < peStrMascara.length; locIntCount++)
	{
		locMascChar = peStrMascara.substring(locIntCount, locIntCount + 1);
		loccampoChar = locValorcampo.substring(locIntCount, locIntCount + 1);

		switch (locMascChar)
		{
			case "#":
			{
				if (locNumeros.indexOf(loccampoChar) == -1)
				{
					pagStrErro += "-O preenchimento do campo '" + peStrDescricao + "' é inválido! [" + loccampoChar + "]\n";
					return false;
				}
				break;
			}
			case "A":
			{
				if (locLetras.indexOf(loccampoChar) == -1)
				{
					pagStrErro += "-O preenchimento do campo '" + peStrDescricao + "' é inválido! [" + loccampoChar + "]\n";
					return false;
				}
				break;
			}
			default:
			{
				if (loccampoChar != locMascChar)
				{
					pagStrErro += "-O preenchimento do campo '" + peStrDescricao + "' é inválido! [" + loccampoChar + "]\n";
					return false;
				}
			}
		}
	}
}

//Aplica máscara à um determinado valor
function fnStrMascValor(peStrValor, peStrMask)
{
	var psStrRetorno	='';
	var locStrCharMask  ='';
	var locStrCharValor ='';

	var j=0;

	for (i=0; i<peStrMask.length; i++)
	{
		locStrCharMask  = peStrMask.substring(j,j+1);
		locStrCharValor = peStrValor.substring(i,i+1);

		if((locStrCharMask != '#') && (locStrCharMask != 'A'))
		{
			psStrRetorno += locStrCharMask;
			j++;
		}
		j++;
		psStrRetorno += locStrCharValor;
	}

	return psStrRetorno;
}

// Cria dinâmicamente uma máscara especifica
function fnMascDinam(peStrcampo, peStrMask)
{
	var locObj		 = peStrcampo;

	var locStr		 = locObj.value;

	var locCharPos   = locStr.length;
	var locCharInput = String.fromCharCode(event.keyCode);
	
	var locCharMask  = peStrMask.substring(locCharPos, locCharPos + 1);
	var locCharProx	 = peStrMask.substring(locCharPos + 1, locCharPos + 2);
	var locStrNumeros= '0123456789';
	var locStrLetras = 'abcdefghijklmnopqrstuvxzABCDEFGHIJKLMNOPQRSTUVXZáàâãÁÀÂÃéèêÉÈÊíìîÍÌÎÓÒÔÕóòôõÚÙÛúùûçÇñÑ';

	// A - Alfanumérico (Letras, espaço e números)
	// # - Números apenas.

	if (locStr.length >= peStrMask.length)
	{
		locObj.value = locStr.substring(0,peStrMask.length);
		return false;
	}

	switch (locCharMask)
	{
		case "#":
		{
			if (locStrNumeros.indexOf(locCharInput) == -1)
			{
				return false;
			}
			break;
		}
		case "A":
		{
			if (locStrLetras.indexOf(locCharInput) == -1)
			{
				return false;
			}
			break;
		}
		default:
		{
			switch (locCharProx)
			{
				case "#":
				{
					if (locStrNumeros.indexOf(locCharInput) == -1)
					{
						return false;
					}
					break;
				}
				case "A":
				{
					if (locStrLetras.indexOf(locCharInput) == -1)
					{
						return false;
					}
					break;
				}
			}
		}
		locObj.value += locCharMask;
	}
}

//Verifica itens numa lista
function fnStrVerificaLista(peObjForm, peStrListaTiposObjeto, peStrMensagemOpcional)
{
	var locStrObj='';
	var locStrChar='';
	var locIntChecks=0;
	var ii=0;

	//Cria array baseado em lista de tipos de objeto especificada
	for (i=0; i < peStrListaTiposObjeto.length; i++)
	{
		locStrChar = peStrListaTiposObjeto.substring(i,i+1);
		if(locStrChar == ';')
		{
			eval('var locStrObj' + ii + '="' + locStrObj + '"');
			locStrObj = '';
			ii++;
		}
		else
		{
			locStrObj += locStrChar;
		}
	}

	//Para cada um dos tipos de objeto, corre array de elementos do formulário,
	//Verificando quais estão com "checked=true".
	for (j=0; j<ii; j++)
	{
		for (i=0; i< peObjForm.elements.length; i++)
		{
			if (peObjForm.elements[i].type == eval('locStrObj' + j))
			{
				if (peObjForm.elements[i].checked) locIntChecks++;
			}
		}
	}

	//Se o número de itens checados na lista for inferior ao mínimo, adiciona erro.
	if (locIntChecks < 1)
	{
		if (peStrMensagemOpcional == '')
		{
			pagStrErro += '- É necessário que pelo menos um item da lista seja selecionado para esta operação.\n';
		}
		else
		{
			pagStrErro += peStrMensagemOpcional + '\n';
		}
		return false;
	}
	return true;
}

function fnStrVerificaChar(peObjForm, peStrCharList, peStrcampo, peStrMensagemOpcional)
{
	var locVetCharRejeitado = peStrCharList.split('·');
	var locStrValor = peObjForm.value;

	for (i=0; i<locStrValor.length; i++)
	{
		for (j=0; j<locVetCharRejeitado.length; j++)
		{
			if(locStrValor.substring(i,i+1) == locVetCharRejeitado[j])
			{
				if (peStrMensagemOpcional == '')
				{
					pagStrErro += '- O caracter [' + locStrValor.substring(i,i+1) + '] é inválido para o campo [' + peStrcampo + '].\n';
				}
				else
				{
					pagStrErro += peStrMensagemOpcional + '\n';
				}
				return false;
			}
		}
	}
	return true;
}

function fnObjMarcaSomenteUmCheckBox(peObjLista)
{
	for (i=0; i < peObjLista.form.elements.length; i++)
	{
		if (peObjLista.form.elements[i].type == 'checkbox')
	    {
			peObjLista.form.elements[i].checked = false;
		}
	}
	peObjLista.checked = true;
}

function fnIntComparaDatas(peStrData1,peStrData2)
{
    var data1=peStrData1.substring(6)+peStrData1.substring(3,5)+peStrData1.substring(0,2);
    var data2=peStrData2.substring(6)+peStrData2.substring(3,5)+peStrData2.substring(0,2);

    if (Number(data1)>Number(data2))
	{
 		return 1;
	}
	if (Number(data1)==Number(data2))
	{
		return 0;
    }
    if (Number(data1)<Number(data2))
	{
		return -1;
	}
}

//Função para arredondar valores
function fnArredonda(paramValue,decimal){
	var str, str2, strDec, xx = new String();
	var x, i, a;
	var xDec, xValue;

	str = paramValue + "";
	x = str.indexOf(".");

	if(x > 0){
		str = paramValue + "00000";
	}

	strDec = "";

	strDec = str.substr(x+1, decimal+1);

	xValue = parseFloat(str);

	a = "";
	if(x > -1){
		xx = str.substr(x+1, decimal+1);

		strDec = str.substr(x+1, decimal+1);

		if(xx.length > decimal){

			a = parseInt(xx.substr(decimal,1));

			if(a >= 5){

				if(xValue < 0){
					xValue -= ((1/Math.pow(10,decimal))-(a/Math.pow(10,decimal+1)));
				}else{
					xValue += parseFloat((1/Math.pow(10,decimal))-(a/Math.pow(10,decimal+1)));
				}
			}
		}
		strDec = xValue;
		for(i = 0; i < decimal; i++){
			strDec += "0";
		}

		str2 = str.substring(0,x) + "." + strDec.substring(0,decimal);
		str2 = strDec.substring(0,x+decimal+1);

		return str2;
	}else{
		strDec = str + ".";
		for(i = 0; i < decimal; i++){
			strDec += "0";
		}

		return strDec;
	}

}//Fim Arredonda

function fnFormataValorBR(Valor,numDecs)
{
	var cRetu;
	var nPos;
	var inte2;
	var inte3;
	var zeros;
	var cValor = new String(Valor);
	var k, x, deci;

	nPos = cValor.indexOf(".");
	numDecs = parseInt(numDecs);

	if (nPos > 0){
	  inte1 = cValor.substr(0, nPos);
	}else{
	  inte1 = cValor;
	}

	inte2="";
	inte3="";
	x = 0;
	for (k=inte1.length-1;k>=0;k--){
		inte2 += inte1.substr(k,1);
		x++;
		if ((x == 3) && (k > 0)){
			inte2 += ".";
			x = 0;
		}
	}

	for (k=inte2.length-1; k >= 0;k--){
		inte3 += inte2.substr(k,1);
	}

	deci = "";
	zeros = "";
	zeros += Math.pow(10, numDecs);

	if (numDecs > 0){
		if (nPos > 0){
			deci = cValor.substr(nPos + 1, numDecs);
		}

		for(k=zeros.length-1; k >= 0; k--){
			deci += zeros.substr(k, 1);
		}
		//alert("deci = " + deci);
		cRetu = inte3 + "," + deci.substr(0, numDecs);
	}else{
		cRetu = inte2;
	}
	//alert("cRetu = " + cRetu);
	return cRetu;
}

// Resume as criticas de um formulário
function fnStrResumeCritica()
{
	if (pagStrErro == '')
	{
		return true;
	}
	else
	{
		alert(pagStrErro);
		pagStrErro = '';
		return false;
	}
}

/*=========================================================================================
	Nome:			ValidacampoData
	Descrição:	Função de Validação de campos data

	Utilização:	validacampoData( evento , ocampo )
	Recebe:
		evento
		ocampo		Objeto		Objeto Texto
	RETORNA:
		Mensagem do campo
===========================================================================================*/
function ValidacampoData( evento , ocampo )
{
	var sData = ocampo.value;
	var i;

//	alert( evento.keyCode );

	if( evento.keyCode == 37 || evento.keyCode == 38 || evento.keyCode == 39 || evento.keyCode == 40 )
	{
		return true;
	}

	if( ocampo.value != '' )
	{
		for( i = 0 ; i < sData.length ; i++ )
		{
			if( sData.charAt(i) == "/" )
			{
				sData = sData.substring( 0 , i ) + sData.substring( i + 1 , sData.length )
				i = i - 1;
			}
		}

		if( ValidacampoNumerico( sData ) )
		{
			if( evento.keyCode == 8 )
			{
				if( sData.length == 4 || sData.length == 3 )
				{
					sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , sData.length );
				}
				else
				{
					if( sData.length < 3 )
					{
						sData = sData.substring( 0 , sData.length );
					}
					else
					{
						sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , 4 ) + "/" + sData.substring( 4 , sData.length );
					}
				}
			}
			else
			{
				if( sData.length != 1 )
				{
					if( sData.length < 4 )
					{
						sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , sData.length );
					}
					else
					{
						if( sData.length == 4 )
						{
							sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , 4 ) + "/";
						}
						else
						{
							sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , 4 ) + "/" + sData.substring( 4 , sData.length );
						}
					}
				}
			}
			ocampo.value = sData.substr( 0 , 10 );
		}
		else
		{
			ocampo.value = '';
			alert( 'Preencha o campo apenas com números' );
		}
	}
	return true;
}

/*=========================================================================================
	Nome:			ValidacampoDataMesAno
	Descrição:		Função de Validação de campos data Mes/Ano

	Utilização:	validacampoDataMesAno( evento , ocampo )
	Recebe:
		evento
		ocampo		Objeto		Objeto Texto
	RETORNA:
		Mensagem do campo
===========================================================================================*/
function ValidacampoDataMesAno( evento , ocampo )
{
	var sData = ocampo.value;
	var i;

	if( evento.keyCode == 37 || evento.keyCode == 38 || evento.keyCode == 39 || evento.keyCode == 40 )
	{
		return false;
	}

	if( ocampo.value != '' )
	{
		for( i = 0 ; i < sData.length ; i++ )
		{
			if( sData.charAt(i) == "/" )
			{
				sData = sData.substring( 0 , i ) + sData.substring( i + 1 , sData.length )
				i = i - 1;
			}
		}

		if( ValidacampoNumerico( sData ) )
		{
			if( evento.keyCode == 8 )
			{
				if( sData.length == 4 || sData.length == 3 )
				{
					sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , sData.length );
				}
				else
				{
					if( sData.length < 3 )
					{
						sData = sData.substring( 0 , sData.length );
					}
					else
					{
						sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 4 , sData.length );
					}
				}
			}
			else
			{
				if( sData.length != 1 )
				{
					sData = sData.substring( 0 , 2 ) + "/" + sData.substring( 2 , sData.length );
				}
			}
			ocampo.value = sData.substr( 0 , 6 );
		}
		else
		{
			ocampo.value = '';
			alert( 'Preencha o campo apenas com números' );
		}
	}
	return true;
}

/*=========================================================================================
	Nome:			ValidacampoNumerico
	Descrição:	Função de Validação de campos texto mostrando
	            a mensagem de uma so vez

	Utilização:	ValidacampoTexto( String )
	Recebe:
		String		sTexto				Texto a ser tratado
	RETORNA:
		Mensagem do campo
===========================================================================================*/
function ValidacampoNumerico( sTexto )
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;

 	for ( i = 0 ; i < sTexto.length && IsNumber == true ; i++ )
	{
		Char = sTexto.charAt( i );
		if ( ValidChars.indexOf(Char) == -1 )
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

// Verifica se a data é válida no formato mm/aaaa
function fnStrVerificaDataMesAno( peStrcampo, peStrDescricao )
{
	var loccampoChar = peStrcampo.value;
	var mes = parseInt( peStrcampo.value.toString().substr( 0, 2 ), 10 );
	var ano = parseInt( peStrcampo.value.toString().substr( 3, 4 ), 10 );

	if( mes < 1 || mes > 12 )
	{
		pagStrErro += "-O preenchimento do campo '" + peStrDescricao + "' é inválido! [" + loccampoChar + "]\n";
		return false;
	}
	if( ano < 1900 )
	{
		pagStrErro += "-O campo preenchimento do campo '" + peStrDescricao + "' é inválido! [" + loccampoChar + "]\n";
		return false;
	}
	return true;
}

function fnStrVerificaRadio( peStrcampo, peStrDescricao )
{
	bMarcado = 0;
	for( var i=0; i < peStrcampo.length; i++ )
	{
		if( peStrcampo[i].checked == true )
			bMarcado = 1;
	}

	if( bMarcado == 0 )
	{
		pagStrErro += "O campo [" + peStrDescricao + "] é obrigatório.\n";
		return false;
	}

}

function fnAdicionaMensagem( peStrMensagem )
{
	pagStrErro += peStrMensagem + "\n";
}
function fnEvnEntradaAspas()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /["]/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
function fnEvnEntradaPlic()
{
	var peCharEntrada = String.fromCharCode(event.keyCode);

	var locStrExpression	= /[']/i;
	var locRetorno			= peCharEntrada.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		event.keyCode = 0;
		return false;
	}
}
function fnStrVerificaAspas(peStrcampo, peStrDescricao)
{
	var peStr = peStrcampo.value;

	var locStrExpression	= /["]/i;
	var locRetorno			= peStr.match(locStrExpression);

	if (locRetorno == null)
	{
		return true;
	}
	else
	{
		pagStrErro += "-" + peStrDescricao + " [" + locRetorno + "] \n";
		return false;
	}
}
function fnValidaData( peStrcampo, peStrDescricao ){
	
	var adtData = peStrcampo.value;
	
	if(adtData == ''){
		return true;
    }
	
	// Checando os seguintes formatos validos:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	var rgMascara = /^(\d{2})(\/|-)(\d{2})\2(\d{4})$/;

	//var rgMascara = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// Se quizermos considerar obrigatório 4 dígitos de ano,
	// é só descomentar esta linha
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	// Este formato está Ok?
	var vMatchArray = adtData.match( rgMascara ); 
	if ( vMatchArray == null ) 
		{
		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
		return false;
		}
	
	// Agora vou separar a data em variáveis mês, dia e ano.
	iMes = vMatchArray[ 3 ]; 
	iDia = vMatchArray[ 1 ];
	iAno = vMatchArray[ 4 ];

	// Checando o mês.
	if ( iMes < 1 || iMes > 12 ) 
		{
		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
		return false;
		}

	// Checando o básico do Dia ( maior ou igual a 1 e menor ou igual ao 31.
	if ( iDia < 1 || iDia > 31 ) 
		{
		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n"; 
		return false;
		}
	
	// Verificando se o dia está como 31 em um mês que não tem
	// 31 dias.
	if ( ( iMes == 4 || iMes == 6 || iMes == 9 || iMes == 11 ) && iDia == 31 ) 
		{
		pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";	
		return false
		}
	
	// Verificando se o mês é fevereiro, se for vou tratar o caso do ano bissexto.
	if ( iMes == 2 ) 
		{ 
		var bBissexto = ( iAno % 4 == 0 && ( iAno % 100 != 0 || iAno % 400 == 0 ) );
		if ( iDia > 29 || ( iDia == 29 && !bBissexto ) ) 
			{
			pagStrErro += "A data inserida no campo [" + peStrDescricao + "] é inválida!\n";
			return false;
   		}
		}
	return true;  // Data válida.
	}