/*----------------------------------------------------
** Fóton Informática e Serviços Ltda
** Descrição: Biblioteca genérica contendo métodos para
** tratamento numérico, de datas, etc;
** $Workfile: $
** $Revision: $
** $Log: $
*/

/*----------------------------------------------------
 * Descrição : Faz troca de 2 elementos de um array.
 * Parâmetros:	arrayDate - array a ter os elementos trocados.
 *					i - índice do primeiro elemento a ser trocado.
 *					j - índice do segundo elemento a ser trocado.
 * Retorno: -
 * Globais: -
*/
function swap(arrayDate, i, j)
{
	var element = arrayDate[i];
	arrayDate[i] = arrayDate[j];
	arrayDate[j] = element;
}

/*----------------------------------------------------
 * Descrição : Algoritmo QuickSort para arrays de objetos do tipo Date.
 * Parâmetros: arrayDate - o array de objetos tipo Date a ser ordenado.
 *					lo0 - índice do menor elemento.
 *					hi0 - índice do maior elemento.
 * Retorno: -
 * Globais: -
*/
function quickSort(arrayDate, lo0, hi0)
{
	var lo = lo0;
	var hi = hi0;
	var mid;

	if (hi0 > lo0)
	{
		// Atribui o ponto médio do array
		mid = arrayDate[Math.floor((lo0 + hi0) / 2)];

		// Loop pelo array até o menor elemento
		while (lo <= hi)
		{
			while ( (lo < hi0) && (diffDate(arrayDate[lo], mid) < 0) ) //())
				++lo;

			while ( (hi > lo0) && (diffDate(arrayDate[hi], mid) > 0 ) )
				--hi;

			if (lo <= hi)
			{
				swap(arrayDate, lo, hi);
				++lo;
				--hi;
			}
		}

		if (lo0 < hi)
			quickSort(arrayDate, lo0, hi);

		if (lo < hi0)
			quickSort(arrayDate, lo, hi0);

	}
}

/*-----------------------------------------------------
 * Descrição : Ordena um array de objetos do tipo Date utilizando o QuickSort.
 * Parâmetros: arrayDate - o array com objetos do tipo Date a ser ordenado. 1: o array a ser ordenado.
 * Retorno: -
 * Globais: -
*/
function sortDate(arrayDate)
{
	quickSort(arrayDate, 0, arrayDate.length - 1);
}

/*-----------------------------------------------------
 * Descrição : Formata uma string (str) a esquerda com o caracter (ch)
 *					até o tamanho (length).
 * Parâmetros: str - a string a ser formatada.
 *					length - o tamanho a ser formatado a string.
 *					ch - o caracter a ser utilizado na formatação.
 * Retorno: uma string representando a string formatada.
 * Globais: -
*/
function format(str, length, ch)
{
	var fmtStr = "";
	var size = new Number(length);

	if (size <= str.length)
	{
		return str;
	}
	else
	{
		while (fmtStr.length < size - str.length)
		{
			fmtStr = fmtStr + ch;
		}
		return (fmtStr + str);
	}
}

/* -----------------------------------------------------------------------------
Descricao : Preenche uma string com o caracter informado até alcançar o tamanho
   desejado. O flag align indica o lado do preenchimento.
Parametro : cadeia - string a preencher
            tamanho - tamanho máximo a alcançar
				ch - caracter a ser usado no preenchimento
				align - true: preenche do lado direito e false do lado esquerdo
Retorno   : String preenchida com o caracter até o tamanho desejado ou a string
   original caso length seja menor que tamanho da string original
Globais   : -
Data de criação: 16/11/2000
Autor: José Bernardo Filho
*/
function format(cadeia, tamanho, ch, align)
{
	var fmtStr = "";
	var size = new Number(tamanho);

	if (size <= cadeia.length)
	{
		return cadeia;
	}
	else
	{
		while (fmtStr.length < size - cadeia.length)
		{
			fmtStr = fmtStr + ch;
		}

 		if (align == true)
		{
		   fmtStr = cadeia + fmtStr;
		}
		else
		{
		   fmtStr = fmtStr + cadeia;
		}

		return fmtStr;
	}
}


/*-----------------------------------------------------
	Descrição : Retorna o mês por extenso.
	Parâmetros: month - o mês.
	Retorno: mês por extenso.
	Globais: -
*/
function getMonthExt(month)
{
	var monExt = new Array('Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
					 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro');
	return monExt[month];
}

/*-----------------------------------------------------
	Descrição : Retorna o mês abreviado.
	Parâmetros: month - o mês.
	Retorno: o mês abreviado.
	Globais: -
*/
function getMonthAbr(month)
{
	var monAbr = new Array('Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun',
					 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez');
	return monAbr[month];
}

/*-----------------------------------------------------
	Descrição : Retorna o dia da semana por extenso.
	Parâmetros: day - o dia da semana.
	Retorno: o dia da semana por extenso.
	Globais: -
*/
function getDayExt(day)
{
	var dayExt = new Array('Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado');
	return dayExt[day];
}

/*-----------------------------------------------------
	Descrição : Retorna o dia da semana abreviado.
	Parâmetros: day - o dia da semana.
	Retorno: o dia da semana abreviado.
	Globais: -
*/
function getDayAbr(day)
{
	var dayAbr = new Array('Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab');
	return dayAbr[day];
}

/*-----------------------------------------------------
	Descrição : Retorna uma data de acordo com o layout informado.
	Parâmetros: date	- data a ser formatada.
					fmt	- string de formatação.
	Retorno: string resultante.
	Globais: -
*/
function fmtDate(date, fmt)
{
	var fmtVal = "";
	var ind = 0;
	do
	{
		var fmtParcial = "";
		switch(fmt.charAt(ind))
		{
			case "Y":
				var fator = 1;
				while (fmt.charAt(ind) == "Y")
				{
					ind++;
					fator *= 10;
				}
				fmtParcial = date.getFullYear() % fator;
				break;

			case "M":
				if (fmt.substring(ind, ind + 5) == "MONTH")
				{
					fmtParcial = getMonthExt(date.getMonth());
					ind +=  5;
				}
				else
					if (fmt.substring(ind, ind + 3) == "MON")
					{
						fmtParcial = getMonthAbr(date.getMonth());
						ind +=  3;
					}
					else
						if (fmt.substring(ind, ind + 2) == "MM")
						{
							fmtParcial = format(date.getMonth() + 1, 2, "0");
							ind += 2;
						}
						else
						{
							fmtParcial = date.getMonth() + 1;
							ind += 1;
						}
				break;

			case "D":
				if (fmt.substring(ind, ind + 3)== "DAY")
				{
					fmtParcial = getDayExt(date.getDay());
					ind += 3;
				}
				else
					if (fmt.substring(ind, ind + 2) == "DY")
					{
						fmtParcial = getDayAbr(date.getDay());
						ind += 2;
					}
					else
						if (fmt.substring(ind, ind + 2) == "DD")
						{
							fmtParcial = format(date.getDate(), 2, "0");
							ind += 2;
						}
						else
						{
							fmtParcial = date.getDay();
							ind++;
						}
				break;

			default:
				fmtParcial = fmt.charAt(ind);
				ind++;
				break;
		}
		fmtVal = fmtVal + fmtParcial;
	}while(ind < fmt.length)
	return fmtVal;
}

/*-----------------------------------------------------
 * Descrição : Calcula a diferença em dias entre duas datas.
 * Parâmetros: date1 - primeira data.
 *					date2 - segunda data.
 * Retorno: a diferença em dias entre as datas.
 * Globais: -
*/
function diffDate(date1, date2)
{
	return Math.floor((date1.valueOf() - date2.valueOf()) / (1000 * 60 * 60 * 24));
}

/*-----------------------------------------------------
	Descrição : retorna a hora do DATETime.
	Parâmetros: hms - hora no DATETime.
	Retorno: a hora
	Globais: -
*/
function getHours(hms)
{
	return Math.floor(hms / 10000) ;
}

/*-----------------------------------------------------
	Descrição : retorna os minutos da hora no formato hms (DATETime).
	Parâmetros: hms - hora no formato hms (DATETime)
	Retorno: os minutos da hora no formato hms.
	Globais: -
*/
function getMinutes(hms)
{
	return Math.floor((hms - getHours(hms) * 10000) / 100) ;
}

/*-----------------------------------------------------
	Descrição : retorna os segundos da hora no formato hms (DATETime).
	Parâmetros: hms - hora no formato hms (DATETime)
	Retorno: os segundos da hora no formato hms.
	Globais: -
*/
function getSeconds(hms)
{
	return ((hms - getHours(hms) * 10000) - getMinutes(hms) * 100);
}

/*-----------------------------------------------------
	Descrição : formata a hora do formato hms (DATETime) de acordo
					com o layout informado.
	Parâmetros: hms - hora no formato hms (DATETime)
	Retorno: string resultante da formatação.
	Globais: -
*/
function fmtTime(hms, fmt)
{
	var fmtVal = "";
	var ind = 0;

	do
	{
		var fmtParcial = "";
		switch(fmt.charAt(ind))
		{
			case 'A':
			case 'P':
				if ((fmt.substring(ind, ind + 2) == "AM") || (fmt.substring(ind, ind + 2) == "PM"))
				{
					if (getHour(hms) < 12)
						ftmParcial = "AM";
					else
						ftmParcial = "PM";
					ptr += 2;;
				}
				else
				{
					fmtParcial = fmt.charAt(ind);
					ind++;
				}
				break;

			case 'M':
				if (fmt.substring(ind, ind + 2) == "MI")
				{
					fmtParcial = format(getMinutes(hms), 2, "0");
					ind += 2;
				}
				else
				{
					fmtParcial = fmt.charAt(ind);
					ind++;
				}
				break;

			case 'H':
				if (fmt.substring(ind, ind + 4) == "HH24")
				{
					fmtParcial = format(getHours(hms), 2, "0");
					ind += 4;
				}
				else
					if (fmt.substring(ind, ind + 4) == "HH12")
					{
						var fator = getHours(hms);
						if (fator == 12 || fator == 24)
							fator = 12;
						else
							fator %= 12;

						fmtParcial = format(fator, 2, "0");
						ind += 4;
					}
					else
						if (fmt.substring(ind, ind + 2) == "HH")
						{
							fator = getHours(hms);
							if (fator > 12)
								fator %= 12;
							fmtParcial = format(fator, 2, "0");
							ind += 2;
						}
						else
						{
							fmtParcial = fmt.charAt(ind);
							ind++;
						}
				break;

			case 'S':
				if (fmt.substring(ind, ind + 2) == "SS")
				{
					fmtParcial = format(getSeconds(hms), 2, "0");
					ind += 2;
				}
				else
				{
					fmtParcial = fmt.charAt(ind);
					ind++;
				}
				break;

			default:
				fmtParcial = fmt.charAt(ind);
				ind++;
				break;
		}
		fmtVal = fmtVal + fmtParcial;
	}while(ind < fmt.length);

	return fmtVal;
}

/*----------------------------------------------------
 * Descrição : Retorna a representação numérica (hms) da hora corrente do sistema.
 * Parâmetros:	-
 * Retorno: representação numérica da hora corrente do sistema no formato hms.
 * Globais: -
*/
function getSysTime()
{
	var curDate = new Date();
	return (new Number((format(curDate.getHours(), 2, "0") + format(curDate.getMinutes(), 2, "0") +
				format(curDate.getSeconds(), 2, "0"))));
}

/*----------------------------------------------------
 * Descrição : Retorna a data corrente do sistema.
 * Parâmetros:	-
 * Retorno: data corrente formato DD/MM/YYYY
 * Globais: -
*/
function getSysDate()
{
	return (new Date());
}

/*-----------------------------------------------------
	Descrição : Formata um valor monetário (valMnt) com o caracter (ch)e número
	de casas decimais (numDec).
	Parâmetros: valMnt - valor monetário a ser formatado.
 					ch     - caracter utilizado na formatação e procura.
					numDec - Número de casas decimais.
	Retorno: valor monentário formatado com (ch)e (numDec).
	Globais: -
*/
function fmtValMnt(valMnt,ch,numDec)
{
   var valQtdMnt;
	var strMnt = new String(valMnt);
	var posCh = strMnt.indexOf(ch);
	if (posCh != -1)
	{
   	// calcula quantas casas decimais tem depois do ponto
		valQtdMnt = strMnt.length - (posCh + 1);
		for( var i=0; i < numDec - valQtdMnt; i++)
		{
			strMnt = strMnt + "0";

		}
		return strMnt;
	}
	else
	{
	   strMnt = strMnt + ch;
	   for( var i=0; i < numDec; i++)
	   {
			strMnt = strMnt + "0";
		}
		return strMnt;
	}
}

/*-----------------------------------------------------
	Descrição : Formata um valor (valMnt)com (numDec)
					quando ele possui depois do (ch) muitas casas decimais.
	Parâmetros: valMnt - valor a ser formatado.
					ch     - caracter utilizado na procura.
					numDec - Número de casas decimais.
	Retorno: valor formatado com (numDec).
	Globais: -
*/
function fmtVal(valMnt,ch,numDec)
{
   var valQtdMnt, i, posCh;
	var strMnt	= new String(valMnt);
	var posCh	= strMnt.indexOf(ch);

	if (posCh != -1)
	{
   	// calcula quantas casas decimais tem depois do ponto
		valQtdMnt = strMnt.length - (posCh + 1);
		if (valQtdMnt >= numDec )
		{
			strMnt = strMnt.substring(0, posCh + numDec + 1);
		}
		else
		{
			if (valQtdMnt < numDec )
			{
				strMnt = strMnt.substring(0, posCh + numDec + 1) + "0";
			}
		}
		return strMnt;
	}
	else
	{
	   strMnt = strMnt + ch;
	   for( i=0; i < numDec; i++)
	   {
			strMnt = strMnt + "0";
		}
		return strMnt;
	}
}

/*-----------------------------------------------------
	Descrição : Retira repetição de vetor ordenado.
	Parâmetros: vetor.
	Retorno: vetor sem repetição.
	Globais: -
*/
function rtdRptVet(rptVet)
{
	var i=0;
	var j=0;
	var valA;
	var ValB;

   vetSemRpt = new Array();

	while (j < rptVet.length)
	{
		valA = rptVet[j] + "" ;
		valB = "0";
		if (j + 1 < rptVet.length)
		{
			valB = rptVet[j + 1] + "";
		}
		if (valA != valB)
		{

			vetSemRpt[i] = rptVet[j];
			i++;
			j++;
		}
		else
		{
			j++;
		}
	}
	return vetSemRpt;
}

/*-----------------------------------------------------
	Descrição : tira repetição de vetor de datas ordenado.
	Parâmetros: vetor.
	Retorno: vetor sem repetição.
	Globais: -
*/
function rtdRptVetDat(rptVetDat)
{
	var i=0;
	var j=0;
	var diff;
	var valA;
	var valB;
	vetSemRpt = new Array();

	while (j < rptVetDat.length)
	{
		valA = 	rptVetDat[j];
		valB = 	new Date(00, 00, 00);
		if (j + 1 < rptVetDat.length)
		{

			valB = rptVetDat[j + 1];

		}
		diff = diffDate(valA,valB);
		if (diff != 0)
		{
			vetSemRpt[i] = rptVetDat[j];
			i++;
			j++;
		}
		else
		{
			j++;
		}
	}
	return vetSemRpt;
}


/* --------------------------------------------------------------------
	Descricao : funcao que prepara o parâmetro string que será passado
		    para a query.
	Parametros: item selecionado a ser passado para a query.
	Retorno   : string preparada.
	Globais   : -
*/

function fmtPmtQry(str)
{
   str = "'" + str + "'";
	return str;
}


/* --------------------------------------------------------------------
	Descricao : funcao troca o ponto por vírgula em números decimais
	Parametros: valor decimal a ser formatado
	Retorno   : valor decimal com vírgula.
	Globais   : -
*/
function fmtDec(val)
{
	val = new String(val);
	val = val.replace(".",",");
	return val;
}

/* --------------------------------------------------------------------
	Descricao : Retira espaço em branco a direita de uma string (str).
	Parametro : string (str).
	Retorno   : string(str) sem espaço em branco a direita.
	Globais   : -
*/
function rtdBrc(str)
{
	valStr = new String(str);
	l = valStr.length;

	while (valStr.charAt(l-1)== " ")
	{
		l--;
	}

	str = valStr.substring(0,l);
	return str;
}





 /*-----------------------------------------------------
			Descrição : Formata um valor (valMnt)com (numDec).
							E se (valMnt) tiver o número de casas decimais maior que
							(numDec) a função formata sem arredondar.
			Parâmetros: valMnt - valor a ser formatado.
							ch     - caracter utilizado na procura.
							numDec - Número de casas decimais.
			Retorno: valor formatado com (numDec).
			Globais: -
		*/
		function fmtVal(valMnt,ch,numDec)
		{
		   var valQtdMnt, i, posCh;
			var strMnt	= new String(valMnt);
			var posCh	= strMnt.indexOf(ch);

			if (posCh != -1)
			{
		   	// calcula quantas casas decimais tem depois do ponto
				valQtdMnt = strMnt.length - (posCh + 1);

				if (valQtdMnt >= numDec )
				{
					strMnt = strMnt.substring(0, posCh + numDec + 1);
				}
				else
				{
					while (valQtdMnt < numDec )
					{
						strMnt = strMnt.substring(0, posCh + numDec + 1) + "0";
						valQtdMnt = valQtdMnt + 1;
					}
				}
				return strMnt;
			}
			else
			{
			   strMnt = strMnt + ch;
			   for( i = 0; i < numDec; i++)
			   {
					strMnt = strMnt + "0";
				}
				return strMnt;
			}
		}



/* --------------------------------------------------------------------
 *	Descricao : Obtém data anterior ou posterior a data atual
 *	Parametro : número de dia que deseja antes ou depois da data
 *					atual. Se for antes deve ser negativo(numdia).
 *	Retorno   : data anterior ou posterior a data atual
 *	Globais   : -
 */

function getDat(datSel, numdia)
{
	var datAtu;			//data atual
	var datAtuMil;		//data atual em milisegundos
	var dat;				//data anterior ou posterior
	var datMil;			//data anterior em milisegundos
	var minMil;			//minuto em milisegundo
	var horMil;			//hora em milisegundo
	var diaMil;			//dia em milisegundo
	var dia;				//dias em milisegundos

	minMil	= 1000 * 60
	horMil	= minMil * 60
	diaMil	= horMil * 24

	dia = diaMil * numdia

	datAtu		= new Date(datSel);
	datAtuMil	= datAtu.getTime();
	datMil		= datAtuMil + dia
	dat			= new Date(datMil);

	return dat;
}


/*--------------------------------------------------------------------
	Descrição : Formata um valor, com casas decimais (numDec) e com "."
					nas casas de milhares.
	Parâmetros: val	 - valor a ser formatado.
					numDec - Número de casas decimais.
	Retorno: valor formatado com (numDec).
	Globais: -
---------------------------------------------------------------------*/

function fmtNumber(val, numDec)
{
	var valFmt = new String();
	var arrVal = new Array();
	var arrFmt = new Array();
	var dec	  = new Number();
	var Int	  = new Number();
	var i		  = 0;
	var ind	  = 0;
	var valInt;
	var valDec;
	var flg;
	var flgNeg;

	val	 = new String(val);
	flg	 = val.indexOf(",");
	flgNeg = val.indexOf("-");

	if (flgNeg != -1)
		val = val.substr(1, val.length);

	for (i = 0; i < val.length; i ++)
	{
		if (val.charAt(i) == "," || val.charAt(i) == ".")
		{
			dec = val.length - (i);
			break;
		}
		else
		{
			Int++;
		}
	}

	valDec = val.substr(Int, val.length);
	valInt = val.substr(0, Int);

	if (numDec != 0)
	{
		if (flg != -1)
		{
			val = valInt + "." + valDec.substr(1, valDec.length);
			val = fmtVal(val, ".", numDec);
			val = fmtDec(val);
		}
		else
		{
			val = fmtVal(val, ".", numDec);
			val = fmtDec(val);
		}

		Int = 0;
		dec = 0;
		counter:
			for (i = 0; i < val.length; i ++)
			{
				if (val.charAt(i) == "," || val.charAt(i) == ".")
				{
					dec = val.length - (i);
					break counter;
				}
				else
				{
					Int++;
				}
			}

		valDec = val.substr(Int, val.length);
		valInt = val.substr(0, Int);
	}

	valInt = rtdBrc(valInt);

	for (i = 0; i < valInt.length; i++)
	{
		arrVal[i] = valInt.substr(i, 1);
	}
	arrVal = arrVal.reverse();

	for (i = 0; i < valInt.length; i++)
	{
		if (ind == 2)
		{
			if (i == (valInt.length-1))
			{
				arrFmt[i] = arrVal[i];
			}
			else
			{
				arrFmt[i] = "." + arrVal[i];
				ind++;
				ind = 0;
			}
		}
		else
		{
			arrFmt[i] = arrVal[i];
			ind++;
		}
	}

	arrFmt = arrFmt.reverse();
	for (i = 0; i < arrFmt.length; i++)
	{
		valFmt = valFmt + arrFmt[i];
	}

	if (numDec != 0)
	{
		valFmt = valFmt + valDec;
	}
	else
	{
		valFmt;
	}

	if (flgNeg != -1)
		valFmt = "-" + valFmt;

	return(valFmt);
}

/*----------------------------------------------------------------------
	Descrição : Concatena "0" a string de hora a ser formatada, caso
					esta não possui o length igual a seis.
	Parâmetros: hmsFmt - valor a ser formatado.
	Retorno: string concatenada com "0" até o possuir length igual a seis.
	Globais: -
-----------------------------------------------------------------------*/

function fmtTamTime(hmsFmt)
{
	var fmtVal = "";
	var ind = 0;
	var dfrCplDireita = new Number();
	var dfrCplEsquerda = new Number();
	var hms = new String(hmsFmt);
	var tam = new Number(hms.length);
	var i = 0;
	var hmsAux = "";

	if (tam < 6)
	{
		if (tam < 4)
		{
			dfrCplDireita = 4 - tam;
			while (i < dfrCplDireita)
			{
				hmsAux = hmsAux + "0";
				i++;
			}
			hmsAux = hmsAux + hms;
			hms	 = hmsAux;
		}


		dfrCplEsquerda = 6 - hms.length;
		i = 0;
		while (i < dfrCplEsquerda)
		{
			hms = hms + "0";
			i++;
		}
	}
	return hms;
}
/*----------------------------------------------------------------------
	Descrição :valida o endereço de email digitado.
	Parâmetros: emaStr - endereço email digitado.
	Retorno: true ou false
	Globais: -
-----------------------------------------------------------------------*/

function vldEmail(emaStr)
{

//padrão usada para verificar se o e-mail está no formato padrão usuário@domínio
emaPad = /^(.+)@(.+)$/

// string que contém caracteres especiais não permitidos em um usuário ou domínio
strEsp = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

// string que contém caracteres especiais permitidos em um usuário ou domínio
 vldStr = "\[^\\s" + strEsp + "\]"

/* padrão que contém caracteres válidos para a primeira posição do usuário
ou domínio*/
 prmStr = vldStr

// padrão aplicado se o "usuário" está  entre aspas
usrStr = "(\"[^\"]*\")"

//padrão aplicado para domínios que são IP addresses
ipDomPad = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

/* string que representa uma série de caracteres válidos */
 strval = "(" + prmStr + vldStr + "*" + ")"

// string que representa um usuárioname válido.
 usrVld = "(" + strval + "|" + usrStr + ")"

// padrão que descreve a estrutura do usuário
usrPad = new RegExp("^" + usrVld + "(\\." + usrVld + ")*$")

// padrão que descreve a estrutura de um domínio */
 domPad = new RegExp("^" + strval + "(\\." + strval +")*$")


/*----------------------------------------------------
 Validando endereço
 ---------------------------------------------------*/

/* dividindo o email em partes */
 emaArr = emaStr.match(emaPad)

if (emaArr == null)
{
 	alert(	"O formato do email é usuario@domino.")
	return false
}
usr = emaArr[1]
dom = emaArr[2]

/*----------------------------------------------------
 Validando usuário
 ---------------------------------------------------*/
if (usr.match(usrPad) == null)
{
    alert("Usuário inválido.")
    return false
}

/*----------------------------------------------------
 Validando domínio
 ---------------------------------------------------*/
/* verifica validade se o endereço e-mail se o domínio for um endereço
 IP address */
IpArr = dom.match(ipDomPad)

if (IpArr != null)
{
	for (i = 1; i <= 4; i++)
	{
		if (IpArr[i] > 255)
	    {
			alert("Domínio inválido.")
			return false
	    }
    }
    return true
}

// se domínio for um nome
domArr = dom.match(domPad)

if ( domArr == null)
{
	alert("Domínio inválido.")
    return false
}

/* Divide o domínio em partes para validar cada uma delas*/
 strVldPad	= new RegExp(strval,"g")
 domArr		= dom.match(strVldPad)
 tamDom		= domArr.length

// verifica se a última parte do domínio possui duas ou três letras.
if (domArr[domArr.length-1].length < 2 ||
    domArr[domArr.length-1].length > 3)
{
   alert("O domínio deve ser finalizado com duas ou três letras após o ponto.")
   return false
}

return true;
}

/*--------------------------------------------------------------------
	Descrição : Separa uma string em substrings e armazena em um vetor.
	Parâmetros: str	- string a ser dividida.
				ch	- caracter a ser procurado na string para separá-la
	Retorno: vetor contendo as substrings.
	Globais: -
--------------------------------------------------------*/


function newArr(str, ch)
{
	var tamstr	= str.length;
	var strAux	= new String();
	var strArr	= new Array();
	var i			= 0;
	var j			= 0;

	while (i <= tamstr)
	{

		if ((str.charAt(i) != ch) && (str.charAt(i) != ""))
		{
			strAux = strAux + str.charAt(i);
		}
		else
		{
			strArr[j] = strAux;
			strAux	  = "";
			j++;
		}
		i++;
	}
	return strArr;
}

/*----------------------------------------------------------------------
	Descrição : Concatena "0" hora a ser formatada, caso
				seu tamanho seja menor que 4.
	Parâmetros: hmStr - valor a ser formatado.
	Retorno: array contendo hora e minutos ambos com dois dígitos.
	Globais: -
-----------------------------------------------------------------------*/

function fmtTamHor(hmStr)
{
	hmStr	= new String(hmStr)
	tamhor	= hmStr.length;
	horArr	= new Array();

	if(tamhor < 4)
	{
		if(tamhor < 3)
		{
			hor = hmStr;
			min = "00"
			if(tamhor == 1)
			{
				hor = "0" + hor;
			}
		}
		else
		{
			hor = "0" + hmStr.substring(0,1);
			min = hmStr.substring(1,3);
		}

	}
	else
	{
		hor = hmStr.substring(0,2);
		min = hmStr.substring(2,4);
	}
	horArr[0] = hor;
	horArr[1] = min;
	return horArr;
}

/*--------------------------------------------------------------------
	Descrição : Formata um valor, com casas decimais (numDec) e com "."
					nas casas de milhares.
	Parâmetros: val	 - valor a ser formatado.
					numDec - Número de casas decimais.
	Retorno: valor formatado com (numDec).
	Globais: -
---------------------------------------------------------------------*/

function fmtNumber(val, numDec)
{
	var valFmt = new String();
	var arrVal = new Array();
	var arrFmt = new Array();
	var dec	  = new Number();
	var Int	  = new Number();
	var i		  = 0;
	var ind	  = 0;
	var valInt;
	var valDec;
	var flg;
	var flgNeg;

	val	 = new String(val);
	flg	 = val.indexOf(",");
	flgNeg = val.indexOf("-");

	if (flgNeg != -1)
		val = val.substr(1, val.length);

	for (i = 0; i < val.length; i ++)
	{
		if (val.charAt(i) == "," || val.charAt(i) == ".")
		{
			dec = val.length - (i);
			break;
		}
		else
		{
			Int++;
		}
	}

	valDec = val.substr(Int, val.length);
	valInt = val.substr(0, Int);

	if (numDec != 0)
	{
		if (flg != -1)
		{
			val = valInt + "." + valDec.substr(1, valDec.length);
			val = fmtVal(val, ".", numDec);
			val = fmtDec(val);
		}
		else
		{
			val = fmtVal(val, ".", numDec);
			val = fmtDec(val);
		}

		Int = 0;
		dec = 0;
		counter:
			for (i = 0; i < val.length; i ++)
			{
				if (val.charAt(i) == "," || val.charAt(i) == ".")
				{
					dec = val.length - (i);
					break counter;
				}
				else
				{
					Int++;
				}
			}

		valDec = val.substr(Int, val.length);
		valInt = val.substr(0, Int);
	}

	valInt = rtdBrc(valInt);

	for (i = 0; i < valInt.length; i++)
	{
		arrVal[i] = valInt.substr(i, 1);
	}
	arrVal = arrVal.reverse();

	for (i = 0; i < valInt.length; i++)
	{
		if (ind == 2)
		{
			if (i == (valInt.length-1))
			{
				arrFmt[i] = arrVal[i];
			}
			else
			{
				arrFmt[i] = "." + arrVal[i];
				ind++;
				ind = 0;
			}
		}
		else
		{
			arrFmt[i] = arrVal[i];
			ind++;
		}
	}

	arrFmt = arrFmt.reverse();
	for (i = 0; i < arrFmt.length; i++)
	{
		valFmt = valFmt + arrFmt[i];
	}

	if (numDec != 0)
	{
		valFmt = valFmt + valDec;
	}
	else
	{
		valFmt;
	}

	if (flgNeg != -1)
		valFmt = "-" + valFmt;

	return(valFmt);
}

/*----------------------------------------------------------------------------
	Descrição : Formata o número do telefone, inserindo o caractere "-" e
					retirando o caractere "0" do início da string caso este exista.
	Parâmetros: tel - string a ser formatada.
	Retorno: retTel - String formatada.
	Globais: -
-----------------------------------------------------------------------------*/

function fmtTel(tel)
{
	var i;
	var retTel = "";

	tel = tel + "";

	if (tel.charAt(0) == "0")
	{
		tel = tel.substring(1, tel.length);
	}

	for (i = 0; i < tel.length; i++)
	{
		retTel += tel.charAt(i);

		if (retTel.length == 3 && tel.length == 7)
		{
			retTel += "-";
		}

		if (retTel.length == 4 && tel.length == 8)
		{
			retTel += "-";
		}
	}

	return retTel;
}

function Formata_Data(Campo,teclapres) {
	var tecla = teclapres.keyCode;
	vr = document.form[Campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
			document.form[Campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			document.form[Campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); }
}



/* -----------------------------------------------------------------------------
Descricao : Retira espaços em branco a esquerda e a direita de uma string.
Parametro : str - string.
Retorno   : string sem espaço em branco a esquerda e a direita
Globais   : -
Data de criação: 16/11/2000
Autor: José Bernardo Filho
*/
function trim(str)
{
   str1 = ltrim(str);
	return rtrim(str1);
}


/* -----------------------------------------------------------------------------
Descricao : Retira espaços em branco a direita de uma string.
Parametro : str - string.
Retorno   : string sem espaço em branco a direita
Globais   : -
Data de criação: 16/11/2000
Autor: José Bernardo Filho
*/
function rtrim(str)
{
	valStr = new String(str);

	i = valStr.length;

	while (valStr.charAt(i - 1) == " " || valStr.charAt(i) == '\n' || valStr.charAt(i) == '\t' ||
      valStr.charAt(i) == '\r')
	{
		i--;
	}

	return valStr.substring(0, i);
}



/* -----------------------------------------------------------------------------
Descricao : Retira espaços em branco a esquerda de uma string.
Parametro : str - string.
Retorno   : string sem espaço em branco a esquerda
Globais   : -
Data de criação: 16/11/2000
Autor: José Bernardo Filho
*/
function ltrim(str)
{
	valStr = new String(str);
	i = 0;

	//Retirando  brancos a esquerda
	while (valStr.charAt(i) == " " || valStr.charAt(i) == '\n' || valStr.charAt(i) == '\t' ||
      valStr.charAt(i) == '\r')
	{
		i++;
	}

	return valStr.substring(i);
}

/* -----------------------------------------------------------------------------
Descricao : Verifica se o campo possue valor númerico, apresenta mensagem
   de erro para usuário em caso negativo.
Parametro : cmp - Campo a verificar.
Retorno   : true se possue valor numérico e false em caso contrário
Globais   : -
Data de criação: 16/11/2000
Autor: José Bernardo Filho
*/
function isDigitOnly(cmp)
{
   str = new String(cmp.value);

   if (isNaN(cmp.value) || (str.indexOf('.') != -1))
	{
                if (cmp.id != "" ){
                    alert("O campo " + cmp.id + " só aceita valores numéricos.");
                }
		cmp.value = "";
		cmp.focus();
		return false;
	}

	return true;
}

/* -----------------------------------------------------------------------------
Descricao : Verifica se foi teclado um  valor númerico, apresenta mensagem
   de erro para usuário em caso negativo.
Parametro : tcl - caracter a verificar (valor numerico).
            cpo - campo sendo digitado
Retorno   : true se possue valor numérico e false em caso contrário
Globais   : -
Data de criação: 21/03/2001
Autor: Marco Aurelio
*/
function isDigit(key, cpo)
{
   tcl = key.keyCode;
   if (tcl != 8 && tcl != 9)
   {
      if ((tcl < 48 || tcl > 57) && tcl != 27 && tcl != 13)
      {
         if (cpo.id != "" )
         {
            alert("O campo " + cpo.id + " só aceita valores numéricos.");
         }
         key.keyCode = 0;
         cpo.focus();
         return false;
      }
   }
   return true;
}

/* -----------------------------------------------------------------------------
Descricao : Verifica se o campo está read only.
Parametro : tcl - caracter a verificar (valor numerico).
            cpo - campo sendo digitado
            flag - campo read only
Retorno   : sempre true
Globais   : -
Data de criação: 27/03/2001
Autor: Leonardo Borges
*/
function isReadOnly(key, cpo, flag)
{
   tcl = key.keyCode;
   if (flag)
   {
      alert("O campo " + cpo.name + " está somente leitura.");
      key.keyCode = 0;
      cpo.focus();
   }
	return true;
}

/* -----------------------------------------------------------------------------
Descricao : Verifica se string é uma hora válida. NO formato 0 às 23 horas
Parametro : hour - cadeia de caracteres representando a hora. Pode estar nos
   formatos HHMM ou HHMMSS.
Retorno   : true, caso seja uma hora e false em caso contrário
Globais   : -
Data de criação: 17/11/2000
Autor: José Bernardo Filho
*/
function isHour(hour)
{
   hh = 0, mm = 0, ss = 0;

   if (isNaN(hour))
   {
      return false;
   }

   if (hour.length == 3 || hour.length == 5)
   {
      hour = "0" + hour;
   }

   if (hour.length == 4)
   {
      hh = new Number(hour.substring(0, 2));
      mm = new Number(hour.substring(2));
   }
   else if (hour.length == 6)
   {
      hh = new Number(hour.substring(0, 2));
      mm = new Number(hour.substring(2, 4));
      ss = new Number(hour.substring(5));
   }
   else
   {
      if (new Number(hour) == 0)
         return true;

      return false;
   }

   if (hh <= 23 && mm <= 59 && ss <= 59)
   {
      return true;
   }

   return false;
}



/* -----------------------------------------------------------------------------
Descricao : Decodifica string codificada no formato MIME  "x- www-form-urlencoded".
Parametro : cadeia - cadeia de caracteres a ser decodificada.
Retorno   : String decodificada
Globais   : -
Data de criação: 20/11/2000
Autor: José Bernardo Filho
*/
function decode(cadeia)
{
  str = new String(cadeia);

  while (str.indexOf('+') != -1)
     str = str.replace("+", " ");

   return unescape(str);
}


/* -----------------------------------------------------------------------------
Descricao : Valida INSS e Primeira parte segundo a regra abaixo:
- Se INSS é Recorrido Primeira Parte não pode ser;
- Se INSS é Recorrente Primeira Parte não pode ser;
- Se Primeira Parte é Recorrido INSS não pode ser;
- Se Primeira Parte é Recorrente INSS não pode ser;
- Recorrente/Recorrido é livre
Parametro : val - indice do item selecionado
            primeiro - primeiro radiobutton
            segundo - primeiro radiobutton
Retorno   :
Globais   : -
Data de criação: 22/11/2000
Autor: José Bernardo Filho
*/
function selRbtInss(val, primeiro, segundo)
{
   primeiro[0].disabled = false;
   primeiro[1].disabled = false;
   primeiro[2].disabled = false;
   segundo[0].disabled = false;
   segundo[1].disabled = false;
   segundo[2].disabled = false;

   if (segundo[val].checked == true)
   {
      segundo[2].checked = true;
   }

   if (val != 2)
   {
      segundo[val].disabled = true;
   }
}


/* -----------------------------------------------------------------------------
Descricao : Validação para aceitar apenas digitos numéricos, emiti mensagem
   infromando esta restrição; quando atingir o maxLength pula para o proximo campo
Parametro : val - indice do item selecionado
            primeiro - primeiro radiobutton
            segundo - primeiro radiobutton
Retorno   :
Globais   : -
Data de criação: 22/11/2000
Autor: José Bernardo Filho
*/
function validaPula(cmp, form, num1, num2, num3, event1)
{
   if (isDigitOnly(cmp) == true)
   {
      PulaCpo(form, num1, num2, num3, event1)
   }
}


function removeMask(value)
{
   while(value.indexOf(".") != -1)
      value = value.replace(".", "");

   while(value.indexOf("/") != -1)
      value = value.replace( "/", "" );
   while(value.indexOf("-") != -1)
      value = value.replace( "-", "" );
   while(value.indexOf(",") != -1)
      value = value.replace( ",", "" );
   return value;
}

function frmComMascara(mascara, cpo, prx, tclPres)
{
   var tcl = tclPres.keyCode;
   vr = cpo.value;
   vr = removeMask(vr);
   tam = vr.length;

   if (mascara == "999.999.999-99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 4)
        cpo.value =  vr.substr(0, tam -1) + '-' +
                     vr.substr(tam-1, 2);

       if ( tam > 4 && tam <= 7 )
         cpo.value = vr.substr(0, tam-4) + '.' +
                     vr.substr(tam-4, 3) + '-' +
                     vr.substr(tam-1, 2);

       if ( tam > 7 && tam < 11 )
         cpo.value = vr.substr(0, tam-7) + '.' +
                     vr.substr(tam-7, 3) + '.' +
                     vr.substr(tam-4, 3) + '-' +
                     vr.substr(tam-1, 2);
      }

      tamVr = vr.length;
      if (tamVr == 11)
         prx.focus();
   }
   else if (mascara == "99.999-999")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 5)
        cpo.value =  vr.substr(0, tam -2) + '-' +
                     vr.substr(tam-2, 3);

       if ( tam > 5 && tam < 8 )
         cpo.value = vr.substr(0, tam-5) + '.' +
                     vr.substr(tam-5, 3) + '-' +
                     vr.substr(tam-2, 3);
      }


      tamVr = vr.length;
      if (tamVr == 10)
         prx.focus();
   }

   else if (mascara == "99.999.999-99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 4)
        cpo.value =  vr.substr(0, tam -1) + '-' +
                     vr.substr(tam-1, 2);

       if ( tam > 4 && tam <= 7 )
         cpo.value = vr.substr(0, tam-4) + '.' +
                     vr.substr(tam-4, 3) + '-' +
                     vr.substr(tam-1, 2);

       if ( tam > 7 && tam < 10 )
         cpo.value = vr.substr(0, tam-7) + '.' +
                     vr.substr(tam-7, 3) + '.' +
                     vr.substr(tam-4, 3) + '-' +
                     vr.substr(tam-1, 2);
      }

      tamVr = vr.length;
      if (tamVr == 10)
         prx.focus();
   }
   else if (mascara == "9999.999.999-9")
   {
      if (isDigit(tclPres, cpo))
      {
         strAux = "00000000000";

         if (tam < 11)
         {
            vr1 = strAux.substr(0,11-tam) + vr;
            vr  = vr1;
         }

         if (
              tcl != 8  && tcl != 9  && tcl != 13 && tcl != 32 && tcl != 34 &&
              tcl != 39 && tcl != 42 && tcl != 43 && tcl != 44 && tcl != 45 &&
              tcl != 46 && tcl != 47 && tcl != 59 && tcl != 61
            )
         {
            strAux2 = vr.substr(0,1);
            vr = vr.substr(1, 11);
            if ( strAux2 == '0' )
               cpo.value = vr.substr(0, 4) + '.' + vr.substr(4, 3) + '.' +
                           vr.substr(7, 3) + '-' + vr.substr(10, 1);
            else
               prx.focus() ;
         }

   /*
         if ( tcl != 9 && tcl != 8 )
         {
          if (tam > 0 && tam <= 3)
           cpo.value =  vr.substr(0, tam) + '-';

          if ( tam > 3 && tam <= 6 )
            cpo.value = vr.substr(0, tam-3) + '.' +
                        vr.substr(tam-3, 3) + '-' +
                        vr.substr(tam, 1);

          if ( tam > 6 && tam < 11 )
            cpo.value = vr.substr(0, tam-6) + '.' +
                        vr.substr(tam-6, 3) + '.' +
                        vr.substr(tam-3, 3) + '-' +
                        vr.substr(tam, 1);
         }

         tamVr = vr.length;
         if (tamVr == 11)
            prx.focus();
   */ }
   }
   else if (mascara == "99.999.999/9999-99")
   {

      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 5 )
        cpo.value =  vr.substr(0, tam-1) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 5 && tam <= 8)
         cpo.value = vr.substr(0, tam-5) + '/' +
                     vr.substr(tam-5, 4) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 8 && tam <= 11 )
         cpo.value = vr.substr(0, tam-8) + '.' +
                     vr.substr(tam-8, 3) + '/' +
                     vr.substr(tam-5, 4) + '-' +
                     vr.substr(tam-1, 2);
        if (tam > 11 && tam < 14)
         cpo.value = vr.substr(0, tam-11) + '.' +
                     vr.substr(tam-11, 3) + '.' +
                     vr.substr(tam-8, 3)  + '/' +
                     vr.substr(tam-5, 4)  + '-' +
                     vr.substr(tam-1, 2);
       }

       tamVr = vr.length;
       if (tamVr == 14)
          prx.focus() ;
   }

   else if (mascara == "9999.9999.999/9999-99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 5 )
        cpo.value =  vr.substr(0, tam-1) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 5 && tam <= 8)
         cpo.value = vr.substr(0, tam-5) + '/' +
                     vr.substr(tam-5, 4) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 8 && tam <= 12 )
         cpo.value = vr.substr(0, tam-8) + '.' +
                     vr.substr(tam-8, 3) + '/' +
                     vr.substr(tam-5, 4) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 12 && tam < 17)
         cpo.value = vr.substr(0, tam-12) + '.' +
                     vr.substr(tam-12, 4) + '.' +
                     vr.substr(tam-8, 3)  + '/' +
                     vr.substr(tam-5, 4)  + '-' +
                     vr.substr(tam-1, 2);
      }
      tamVr = vr.length;
      if (tamVr == 17)
         prx.focus() ;
   }
   else if (mascara == "99999.999999/9999-99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 5 )
        cpo.value =  vr.substr(0, tam-1) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 5 && tam <= 11)
         cpo.value = vr.substr(0, tam-5) + '/' +
                     vr.substr(tam-5, 4) + '-' +
                     vr.substr(tam-1, 2);
       if (tam > 11 && tam < 17 )
         cpo.value = vr.substr(0, tam-11) + '.' +
                     vr.substr(tam-11, 6) + '/' +
                     vr.substr(tam-5, 4)  + '-' +
                     vr.substr(tam-1, 2);
      }
      tamVr = vr.length;
      if (tamVr == 17)
         prx.focus() ;
   }
   else if (mascara == "9.999.999.999.999,99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 4 )
        cpo.value =  vr.substr(0, tam-1) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 4 && tam <= 7)
         cpo.value = vr.substr(0, tam-4) + '.' +
                     vr.substr(tam-4, 3) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 7 && tam <= 10)
         cpo.value = vr.substr(0, tam-7) + '.' +
                     vr.substr(tam-7, 3) + '.' +
                     vr.substr(tam-4, 3) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 10 && tam < 13)
         cpo.value = vr.substr(0, tam-10) + '.' +
                     vr.substr(tam-10, 3) + '.' +
                     vr.substr(tam-7, 3)  + '.' +
                     vr.substr(tam-4, 3)  + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 13 && tam < 15)
         cpo.value = vr.substr(0, tam-13) + '.' +
                     vr.substr(tam-13, 3) + '.' +
                     vr.substr(tam-10, 3) + '.' +
                     vr.substr(tam-7, 3)  + '.' +
                     vr.substr(tam-4, 3)  + ',' +
                     vr.substr(tam-1, 2);
      }
      tamVr = vr.length;
      if (tamVr == 15)
         prx.focus() ;
   }
   else if (mascara == "99.999.999/9999-99")
   {

   }
   /*
   else if (mascara == "9.999.999.999.999,99")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 4 )
        cpo.value =  vr.substr(0, tam-1) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 4 && tam <= 7)
         cpo.value = vr.substr(0, tam-4) + '.' +
                     vr.substr(tam-4, 3) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 7 && tam <= 10)
         cpo.value = vr.substr(0, tam-7) + '.' +
                     vr.substr(tam-7, 3) + '.' +
                     vr.substr(tam-4, 3) + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 10 && tam < 13)
         cpo.value = vr.substr(0, tam-10) + '.' +
                     vr.substr(tam-10, 3) + '.' +
                     vr.substr(tam-7, 3)  + '.' +
                     vr.substr(tam-4, 3)  + ',' +
                     vr.substr(tam-1, 2);
       if (tam > 13 && tam < 17)
         cpo.value = vr.substr(0, tam-13) + '.' +
                     vr.substr(tam-13, 3) + '.' +
                     vr.substr(tam-10, 3) + '.' +
                     vr.substr(tam-7, 3)  + '.' +
                     vr.substr(tam-4, 3)  + ',' +
                     vr.substr(tam-1, 2);
      }
      tamVr = vr.length;
      if (tamVr == 17)
         prx.focus() ;
   }

   */
   else if (mascara == "DD/MM/YYYY")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 3)
         cpo.value = vr.substr(0, tam - 1) + '/' +
                     vr.substr(tam-1, 2);
       if (tam > 3 && tam < 8)
         cpo.value = vr.substr(0, 2) + '/' +
                     vr.substr(2, 2) + '/' +
                     vr.substring(4);
      }
      tamVr = vr.length;
      if (tamVr == 8)
         prx.focus() ;
   }
   else if (mascara == "MM/YYYY")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam < 6)
         cpo.value = vr.substr(0, 2) + '/' +
                     vr.substring(2);
      }
      tamVr = vr.length;
      if (tamVr == 6)
         prx.focus() ;
   }
   else if (mascara == "9,9999")
   {
      if (isDigit(tclPres, cpo))
      {
          if (tam > 0 && tam < 5)
             cpo.value = vr.substr(0, 1) + ',' + vr.substring(1);
      }

      tamVr = vr.length;

      if (tamVr == 5)  prx.focus() ;
   }
   else if (mascara == "HH:MM:SS")
   {
      if (isDigit(tclPres, cpo))
      {
       if (tam > 1 && tam <= 3)
         cpo.value = vr.substr(0, tam - 1) + ':' +
                     vr.substr(tam-1, 2);
       if (tam > 3 && tam < 8)
         cpo.value = vr.substr(0, 2) + ':' +
                     vr.substr(2, 2) + ':' +
                     vr.substring(4);
      }
      tamVr = vr.length;
      if (tamVr == 6)
         prx.focus() ;
   }
   else if (mascara == "HH:MM")
   {
      if (isDigit(tclPres, cpo))
      {
          if (tam > 1 && tam < 4)
            cpo.value = vr.substr(0, 2) + ':' +
                        vr.substring(2);

      }
      tamVr = vr.length;
      if (tamVr == 4)
         prx.focus() ;
   }
   else
      alert("Mascara de entrada de dados não reconhecida");
}

/* ---------------------------------------------------------------------------
	Descricao : Verifica a validade de um cpf.
	Parametros: cpf - cpf a ser testado
	Retorno   : true  - se for um cpf valido;
					false - caso contrario.
	Globais   : -
*/
function validaCpf(cpf)
{
   cpf = removeMask(trim(cpf));

	if (cpf.length == 11 &&
		 calcDV(cpf, 9, 2, 11)  == new Number(cpf.substring( 9, 10)) &&
		 calcDV(cpf, 10, 2, 11) == new Number(cpf.substring(10, 11)))
		return true;

	return false;
}

/* ---------------------------------------------------------------------------
	Descricao : Verifica a validade de um cgc.
	Parametros: cgc - cgc a ser testado
	Retorno   : true  - se for um cgc valido;
					false - caso contrario.
	Globais   : -
*/
function validaCgc(cgc)
{
   cgc = removeMask(trim(cgc));

	if (cgc.length == 14 &&
		 calcDV(cgc, 12, 2, 9) == new Number(cgc.substring(12, 13)) &&
		 calcDV(cgc, 13, 2, 9) == new Number(cgc.substring(13, 14)))
		return true;

	return false;
}

/* ---------------------------------------------------------------------------
	Descricao : Verifica a validade de um pis.
	Parametros: pis - pis a ser testado
	Retorno   : true  - se for um cpf valido;
					false - caso contrario.
	Globais   : -
*/
function validaPis(pis)
{
   pis = removeMask(trim(pis));

   /* Nao sei a regra de validacao do PIS */
	if (pis.length == 11 /*&&
		 calcDV(pis, 10, 2, 11) == new Number(pis.substring(10, 11))*/)
		return true;

	return false;
}

/* ---------------------------------------------------------------------------
	Descricao : Verifica a validade de um numero de protocolo da previdencia.
	Parametros: numPro - protocolo a ser testado
	Retorno   : true  - se for um protocolo valido;
					false - caso contrario.
	Globais   : -
*/
function validaProtocolo(numPro)
{
   numPro = removeMask(trim(numPro));
 	if (numPro.length == 17 &&
		 calcDV(numPro, 15, 2, 17)  == new Number(numPro.substring(15, 16)) &&
		 calcDV(numPro, 16, 2, 17) == new Number(numPro.substring(16, 17)))
		return true;

	return false;
}

/*  ///////  Função antiga ///////////
function validaProtocolo(numPro)
{
   numPro = removeMask(trim(numPro));
 	if (numPro.length == 15 &&
		 calcDV(numPro, 13, 2, 15)  == new Number(numPro.substring(13, 14)) &&
		 calcDV(numPro, 14, 2, 15) == new Number(numPro.substring(14, 15)))
		return true;

	return false;
}
*/

/* ---------------------------------------------------------------------------
	Descricao : Verifica a validade de um numero de protocolo da previdencia.
		    Função copiada do sistema SIPPS feito em ASP.
	Parametros: numPro - protocolo a ser testado
	Retorno   : true  - se for um protocolo valido;
		    false - caso contrario.
	Globais   : -

	Data de criação: 22/11/2001
	Autor: Leonardo Borges
*/
function validaProtocoloSipps(numPro)
{
   numeroComp = numPro.value;
   numero     = numeroComp.substring(0,5) + numeroComp.substring(6,12) + numeroComp.substring(15,17);

   for ( j = 0; j < 2; j++ )
   {
      dig = "";
      for ( i = 0; i < 2; i++ ) 
      { 
         tamanho = numero.length;
         peso = 2;
         resto = 0;
         total = 0;
         dv2 = "";
         for ( contador = tamanho; contador > 0; contador-- )
         {
            total = total + ( peso * numero.substring( contador, contador - 1 ) );
            peso  = peso + 1;
         }
         resto = total % 11;
         dv = 11 - resto;
         if ( dv >= 10 ) 
         { 
            dv = 1 - resto
         }

         if ( dv2 = "" ) 
         { 
            dv2 = dv
         }
         else 
         {
            dv2 = ( dv2 * 10 ) + dv
         }
         dig = dig + dv
         numero = numero + dv
      }

      if ( dig != numeroComp.substring(18,21) )
      {
         erro = "Sim"
         numero = numeroComp.substring(0,5) + numeroComp.substring(6,12) + numeroComp.substring(13,17);
      }
      else
      {
         j++
         erro = ""
      }
   }

   if ( erro == "Sim" ) 
   {
      return (false);
   }
   else
   {
      return (true);
   }
}


/* ---------------------------------------------------------------------------
	Descricao : Rotina generica para calculo do d¡gito verificador m¢dulo 11,
					de uma cadeia numerica. Esta rotina e utilizada no calculo do
					DV de cpf e cgc.
	Parametros: numero 		 - string de digitos decimais;
					tam 			 - numero de d¡gitos a serem utilizados no calculo;
					fatorInicial - valor base do fator de multiplicacao;
					faforFinal   - valor limite do fator de multiplicacao.
	Retorno   : Valor (decimal) do digito verificador.
	Globais   : -
*/
function calcDV(cadeia, tam, fatorInicial, fatorFinal)
{
   tot = 0;

	fator = fatorInicial;

	for (i = 0; i < tam; i++)
	{
      pos = tam - i - 1;                                  /* posicao */
      num = new Number(cadeia.substring(pos, pos + 1));   /* valor da posicao */
		tot += fator * num;
		fator++;
		if (fator > fatorFinal)
			fator = fatorInicial;
	}

	tot = tot % 11;
	if (tot < 2)
		dv = 0;
   else
   	dv = 11 - tot;

   return dv;
}



/* ---------------------------------------------------------------------------
	Descricao : Limpa as barras de uma data no formato DD/MM/YYYY e retorna
               no formato YYYYMMDD. Muito útil para Comparações
	Parametros: data 		 - string de data no formato DD/MM/YYYY;
	Retorno   : String de data no formato YYYYMMDD.
*/

function limpaData(data)
{
   var dia, mes, ano, tmpData;
   // DD/MM/YYYY
   dia = data.substr(0,2);
   mes = data.substr(3,2);
   ano = data.substr(6,4);
   tmpData = ano + mes + dia;
   return tmpData;
}

/* ---------------------------------------------------------------------------
	Descricao : Limpa o valor do campo informado
	Parametros: campo - campo a ser limpo
	Retorno   : não há. O campo fica limpo
*/

function limpaCampo(pmt, tip)
{
   if (tip == 0)
	{
		if (pmt.value != "")
			pmt.value = "";
	}
}

//Validação do número NFLD
function validaDocPrv(numDoc)
{
	numDoc = numDoc + "";
	tamNumDoc = numDoc.length;
	numCal = numDoc.substr(0, tamNumDoc - 1);
	numDv  = numDoc.substr(tamNumDoc - 1, 1);
   numDv  = new Number(numDv);

	vldNum = numDoc.substr(0, 2);
	vldNum = new Number(vldNum);

   if (numDv != calcDV(numCal, tamNumDoc - 1, 2, 9))
      return 1;
   else
   {
     if (numDoc.length == 9)
     {
        if (vldNum > 35)
        {
           return 1;
        }
     }
   }

   return 0;
}

function setMask(mascara,valor){
	temp = "";
	tam = valor.length;
	if (mascara == "99999.999999/9999-99"){
	temp = valor.substr(0, tam-12) + '.' +
	            valor.substr(tam-12, 6) + '/' +
	            valor.substr(tam-6, 4)  + '-' +
                    valor.substr(tam-2, 2);
        }
        
        
        if (mascara == "9999.999.999-9"){
	      var strAux,vr1
	         strAux = "00000000000";
	
	         if (tam < 11)
	         {
	            vr1 = strAux.substr(0,11-tam) + valor;
	            valor  = vr1;
	         }
	
	            strAux2 = valor.substr(0,1);
	            vr = valor.substr(1, 11);
	            if ( strAux2 == '0' )
	               temp = valor.substr(0, 4) + '.' + valor.substr(4, 3) + '.' +
	                           valor.substr(7, 3) + '-' + valor.substr(10, 1);
	           
         }
         
         if (mascara == "99:99"){
         	if(tam==3&& valor.substr(0,1)!='0'){
         		temp= '0'+valor.substr(0,1)+':'+valor.substr(1,2)
         	} else if(tam==3&& valor.substr(0,1)=='0'){
         		temp= valor.substr(0,2)+':0'+valor.substr(2,1)
         	}else if(tam==4){
         		temp= valor.substr(0,2)+':'+valor.substr(2,2)	
         	}
         	
         }
        
        return temp

}

function enter(tclPres){
	if (tclPres.keyCode=='13'){
		return true;
	}else{
		return false;
	}
}

function tipoDoc(valor){
	
	switch(valor){
	case "1": document.write("NB"); break;	
	case "10": document.write("DENUNCIA");break;
	case "11": document.write("PDECADENCI");break;	
	case "12": document.write("PIMUNIDADE ");break;	
	case "13": document.write("PISENCAO");break; 	
	case "14": document.write("PPAGCONTRI");break;	
	case "15": document.write("PPARCREPAR");break;	
	case "16": document.write("PPAGDIVIDA");break;	
	case "17": document.write("PPAGDIVTDA");break;	
	case "18": document.write("PRECONSIDE");break;	
	case "19": document.write("PREEMBOLSO");break;	
	case "2" :document.write("ACL");break;
	case "20": document.write("PREENQUADR");break; 	
	case "21": document.write("PRESTITUIC");break; 	
	case "23": document.write("PETICAO ");break;	
	case "24": document.write("PROPOSTAQU");break; 	
	case "3" :document.write("AC");break; 	
	case "4" :document.write("AI");break; 	
	case "5" :document.write("NFLD");break; 	
	case "6" :document.write("NPP"); break;	
	case "7" :document.write("NRDV");break; 	
	case "8" :document.write("PAVERBACAO");break; 	
	case "9" :document.write("COMPENSACA");break; 	
	default: document.write("");
	}

}

function tipoDocParte(valor){
	switch(valor){
	case "1":document.write("CI");break; 	
	case "2":document.write("CPF");break;  
	case "3":document.write("CTPS");break; 
	case "4":document.write("PIS_PASEP");break; 
	case "5":document.write("CEI");break; 
	case "6":document.write("CNPJ");break;
	default: document.write("");
	}

}

function tipoCsDocumento(valor){
	switch(valor){
		case "0":document.write("Não Aplicável(Sistema)");break;
		case "1":document.write("Número do Benefício");break;
		case "10":document.write("Denúncia Espontânea");break;
		case "11":document.write("Pedido de Declaração de Decadência");break;
		case "12":document.write("Pedido de Declaração de Imunidade");break;
		case "13":document.write("Pedido de Isenção de Contribuições");break;
		case "14":document.write("Pedido de Pag. Contrib. em Atraso");break;
		case "15":document.write("Pedido de Parcel/Reparcel. de Débito");break;
		case "16":document.write("Pedido de Pagt. de Dív. c/ Tit. Público");break;
		case "17":document.write("Pedido de Pagt. de Dív. com TDA'S");break;
		case "18":document.write("Pedido de Reconsideração");break;
		case "19":document.write("Pedido de Reembolso");break;
		case "2" :document.write("ACL-Aviso de Acréscimos Legais");break;
		case "20":document.write("Pedido de Reenquad. Tab. Salário-Base");break;
		case "21":document.write("Pedido-Restituição de Contribuição");break;
		case "23":document.write("Petição");break;
		case "24":document.write("Proposta Quit. Déb/Dação em Pagt.");break;
		case "3" :document.write("Ato Cancelatório");break;
		case "4" :document.write("Auto de Infração");break;
		case "5" :document.write("NFLD-Notif. Fiscal de Lanç. Débito");break;
		case "6" :document.write("NPP-Notificação para Pagamento");break;
		case "7" :document.write("NRDV-Notif. Rec. Déb. Verificados");break;
		case "8" :document.write("Pedido de Averb/Certidão de T. Serviço");break;
		case "9" :document.write("Pedido de Compensação");break;
		default: document.write("");
	}

}

   function disparaBotaoDefault(eventObject, vetExc)
   {
      achouElemPermitido = false;

      if (eventObject.keyCode == 13)
      {
         for (i = 0; i < vetExc.length; i++)
         {
            if (eventObject.srcElement == vetExc[i])
            {
               achouElemPermitido = true;
               break;
            }
         }

         if (achouElemPermitido == true)
         {
            executa();
         }
      }
   }


