// PESSOAL //
/*
** Variáveis globais
*/
var gfShowAlert = true;
var gfAllDate   = false;

function validaCpfCnpj(strcpf,tipo){
	var ret;
	var strCPFlimpo;
	
	var numero;
	
	numero = strcpf.value;
	
	numero = numero.replace( "/", "" );
	numero = numero.replace( "/", "" );
	numero = numero.replace( ",", "" );
	numero = numero.replace( ",", "" );
	numero = numero.replace( ",", "" );
	numero = numero.replace( ".", "" );
	numero = numero.replace( ".", "" );
	numero = numero.replace( ".", "" );
	numero = numero.replace( "-", "" );
	numero = numero.replace( "-", "" );
	numero = numero.replace( " ", "" );
	
	
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace(".","")
//	strcpf = strcpf.replace("/","")
//	strcpf = strcpf.replace("/","")
//	strcpf = strcpf.replace("-","")
//	strcpf = strcpf.replace("-","")
  
   if (numero.length!=0)
   {
  
	ret = VerificaCpfCnpj(numero,tipo);
	if(ret==false){
		alert("CPF/CNPJ Invalido.");
		strcpf.focus();
	}
	}
}

function FormataRG(tammax,teclapres,obj)
	{
	var tecla = teclapres; /*.keyCode;	*/
	vr = obj.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length;
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	if (tecla == 8 ){	tam = tam - 1 ; }

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105  || tecla == 120 || tecla == 88){
	 	if ( (tam > 1) && (tam <= 4) ){
	 		obj.value = vr.substr( 0, tam - 1 ) + '-' + vr.substr( tam - 1, tam ) ; }
	 	if ( (tam >= 5) && (tam <= 7) ){
	 		obj.value = vr.substr( 0, tam - 4 ) + '.' + vr.substr( tam - 4, 3 ) + '-' + vr.substr( tam - 1, tam ) ; }
	 	if ( (tam >= 8) && (tam <= 9) ){
	 		obj.value = vr.substr( 0, tam - 7 ) + '.' + vr.substr( tam - 7, 3 ) + '.' + vr.substr( tam - 4, 3 ) + '-' + vr.substr( tam - 1, tam ) ; }
	 	if (tam >= 10){	 		
	 		obj.value = vr.substr( 0, tam - 7 ) + '.' + vr.substr( tam - 7, 3 ) + '.' + vr.substr( tam - 4, 3 ) + '-' + vr.substr( tam - 1, tam ) ; }
	}		
}

function FormataIE(tammax,teclapres,obj)
	{
	// INSCRICAO ESTADUAL
	var tecla = teclapres.keyCode;	
	vr = obj.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );	
	tam = vr.length;
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }

	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
	 	if ( (tam > 3) && (tam <= 6) ){
	 		obj.value = vr.substr( 0, tam - 3 ) + '.' + vr.substr( tam - 3, tam ) ; }
	 	if ( (tam >= 7) && (tam <= 9) ){
	 		obj.value = vr.substr( 0, tam - 6 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam ) ; }
	 	if ( (tam >= 10) && (tam <= 12) ){
	 		obj.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam - 3, tam ) ; }
	 	if (tam >= 13){	 		
	 		obj.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '.' + vr.substr( tam - 6, 3 ) + '.' + vr.substr( tam -3, tam ) ; }
	}		
}

function FormataCpf(tammax,teclapres,obj) {
	var tecla = teclapres.keyCode;	
	//vr = document.form[campo].value;
	vr = obj.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length;
		
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		//document.form[campo].value = vr ; }
	 		obj.value = vr;}
	 	if ( (tam > 2) && (tam <= 5) ){
	 		//document.form[campo].value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 		obj.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		obj.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		obj.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		obj.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		obj.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
	}		
}
function FormataCgc(tammax,teclapres, obj) {
	var tecla = teclapres.keyCode;
	vr = obj.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		obj.value = vr ; }
	 	if ( (tam > 2) && (tam <= 6) ){
	 		obj.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 7) && (tam <= 9) ){
	 		obj.value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 10) && (tam <= 12) ){
	 		obj.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 13) && (tam <= 14) ){
	 		obj.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		obj.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
	}		
}
function MascararCPF_CNPJ(pControl, vr)
{
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( "-", "" );
	var tam;
	var ret;	
	tam = vr.length;
	
	if ( tam > 12)
	{
		// CNPJ
	 	if ( (tam >= 10) && (tam <= 12) ){
	 		pControl.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 13) && (tam <= 14) ){
	 		pControl.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		pControl.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
	}
	else
	{	// CPF
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		pControl.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		pControl.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		pControl.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		pControl.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ;}
	}	
}

/*
'[======================================================================================
'[=                      ROTINAS GENÉRICAS DE VALIDAÇÕES JAVASCRIPT
'[=
'[======================================================================================
'[=
'[======================================================================================
'[= Funções de Digitação
'[======================================================================================
'[=		OnlyDecimal()
'[=		OnlyNumbers()
'[=		MaxLength()
'[======================================================================================
'[= Funções de Validação de Dados
'[======================================================================================
'[=		IsNumber()
'[=		IsEmpty()
'[=		IsDate()
'[=		IsMonth()
'[=		IsNumberInside()
'[======================================================================================
'[= Funções de Data
'[======================================================================================
'[=		GetDate()
'[=		DateValue()
'[=		FormatDate()
'[=		CompareDate()
'[= 		FormatarData()
'[======================================================================================
'[= Funções de Valor
'[======================================================================================
'[=		ExactVal()
'[=		NumberFormat()
'[=		NumberFormatAll()
'[=		Round()
'[======================================================================================
'[= Funções de String
'[======================================================================================
'[=		TrimString()
'[=		LTrimString()
'[=		RTrimString()
'[======================================================================================
'[= Funções Especiais
'[======================================================================================
'[=		LeadingZeros()
'[=		CheckIdenticos()
'[======================================================================================
'[= Funções Auxiliares
'[======================================================================================
'[=		IIf()
'[=		Left()
'[=		Right()
'[=		Replace()
'[=		SplitString()
'[=		GetValueFromText()
'[=		TypeOf()
'[======================================================================================
'[= Funções Mistas
'[======================================================================================
'[=		ExibeDataCorrente()
'[=		LimpaString()
'[=		ValidaCnpjCpf()
'[=		ValidaLetraRepetida()
'[=		VerificaCpfCnpj()
'[=		checkCPF()
'[=		checkCGC()
'[======================================================================================
*/

/*
** Variáveis globais
*/
var gfShowAlert = true;
var gfAllDate   = false;


/*
'[======================================================================================
'[= FUNÇÕES DE DIGITAÇÃO
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: OnlyDecimal
'[= Descrição		: Permite a digitação de números decimais
'[= Entrada		: poObject   - TextBox
'[=			  pbNegative - Flag indicativo se pode haver digitação de números negativos.
'[= Saida		: 
'[= OBS			: Altera a propriedade event.returnValue que controle se um evento será 
'[=				  ou não processado	
'[======================================================================================
*/
function OnlyDecimal(poObject, pbNegative)
{
	/*
	** Se poObject não for um objeto retorna
	*/
	if (poObject != '[object]')
		return;
	
	/*
	** Se for caracter de controle retorna
	*/
	if (event.keyCode < 32)
	{
		event.returnValue = true;
		return;
	}

	/*
	** Se permitir números negativos
	*/
	if (pbNegative)
		if (String.fromCharCode(event.keyCode) == '-')
		{
			/*
			** Se for digitado um hífem, somente permite se o conteúdo for vazio.
			*/
			event.returnValue = (IsEmpty(poObject.value));
			return;
		}

	/*
	** Se for digitado uma vírgula, somente permite ainda não foi digitada.
	*/
	if (String.fromCharCode(event.keyCode) == ',')
	{
		event.returnValue = (poObject.value.indexOf(',') == (-1));
		return;
	}
	
	/*
	** Verifica se foi digitado um número
	*/
	if ((String.fromCharCode(event.keyCode) < '0') || 
		(String.fromCharCode(event.keyCode) > '9'))
		event.returnValue = (false)
	else
		event.returnValue = (true);
}

/*
'[======================================================================================
'[= Nome		: OnlyNumbers
'[= Descrição		: Permite a digitação de números
'[= Entrada		: 
'[= Saida		: 
'[= OBS			: Altera a propriedade event.returnValue que controle se um evento será 
'[=				  ou não processado	
'[======================================================================================
*/
function OnlyNumbers()
{
	/*
	** Se for caracter de controle retorna
	*/
	if (event.keyCode < 32)
	{
		event.returnValue = true;
		return;
	}

	/*
	** Verifica se foi digitado um número
	*/
	if ((String.fromCharCode(event.keyCode) < '0') || 
		(String.fromCharCode(event.keyCode) > '9'))
		event.returnValue = (false)
	else
		event.returnValue = (true);
}

/*
'[======================================================================================
'[= Nome		: MaxLength
'[= Descrição		: Inibe a digitação no campo de valores maiores do que plTamanho
'[= Entrada		: poObject - TextArea
'[=			  plSize   - Número máximo de caracteres
'[= Saida		: 
'[= OBS			: Altera a propriedade event.returnValue que controle se um evento será 
'[=				  ou não processado	
'[======================================================================================
*/
function MaxLength(poObject, plSize)
{
	/*
	** Se poObject não for um objeto retorna
	*/
	if (poObject != '[object]')
		return;

	/*
	** Se o tamanho for maior que o permitido, invalida a digitação
	*/
	event.returnValue = (poObject.value.length < plSize);
}

/*
'[======================================================================================
'[=	FUNÇÕES DE VALIDAÇÃO DE DADOS
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: IsNumber
'[= Descrição		: Verifica se uma string é um número.
'[= Entrada		: psNumber
'[= Saida		: True  - se a string for um número
'[=			  False - caso contrário
'[= OBS			:	
'[======================================================================================
*/
function IsNumber(psNumber)
{
	var InvalidChar = IsEmpty(psNumber);
	
	for (var i = 0; i < psNumber.length; i++)
	{
		var Char = psNumber.charAt(i);
		if (Char != "." && Char != "," && Char != "-")
			if (isNaN(parseInt(Char)))
				InvalidChar = true  || InvalidChar
			else
				InvalidChar = false || InvalidChar;
	}
	
	return (!InvalidChar);
}

/*
'[======================================================================================
'[= Nome		: IsEmpty
'[= Descrição		: Verifica se uma string está vazia ou somente com caracteres nulos
'[= Entrada		: psString 
'[= Saida		: True  - se a string estiver vazia
'[=			  False - caso contrário
'[= OBS			:	
'[======================================================================================
*/
function IsEmpty(psString)
{
	/*
	** Caracteres Inválidos
	*/
	var lsTab   = '\t', // Tab Char
		lsSpace = ' ' , // Space
        lsCRLF  = '\n', // CR LF
		lsCR    = '\r'; // CR
	
	/*
	** Procura por caracteres válidos
	*/
	for (var liPos = 0; liPos < psString.length; liPos++)
	{
		var lsChar = psString.charAt(liPos);
		if (lsChar != lsTab   &&
			lsChar != lsSpace && 
			lsChar != lsCRLF  && 
			lsChar != lsCR )
			return (false);
	}
	
	return (true);
}

/*
'[======================================================================================
'[= Nome		: IsDate
'[= Descrição		: Verifica se uma string é uma data válida
'[= Entrada		: psData - String de data no formato DD/MM/YYYY
'[= Saida		: True  - se a string for uma data
'[=			  False - caso contrário
'[= OBS			:
'[======================================================================================
*/
function IsDate(psData)
{
	var laDiasMes = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var laData    = SplitString(psData, '/');

	/*
	** Se não houver três partes a data é considerada inválida
	*/
	if (laData.length != 3)
		return false;
	
	/*
	** A string é dividida em três partes :
	**
	** laData[0] - Dia
	** laData[1] - Mês
	** laData[2] - Ano
	*/

	/*
	** Verifica se o mes está no intervalo [1,12]
	*/
	if (!(laData[1] >= 1 && laData[1] <= 12))
		return false;

	/*
	** Se o ano não tiver 4 digitos, é invalida
	*/
	if (laData[2].length != 4) 
		return false;

	/*
	** Se for ano bissexto, o Limite p/ o mes de Fevereiro é 29 dias
	*/
	if (Math.floor(laData[2] / 4) * 4 == laData[2]) 
		laDiasMes[1] = 29;

	/*
	** Verifica se cada parte eh um numero POSITIVO
	*/
	for(var i = 0; i < laData.length; i++)
	{
		if (IsEmpty(laData[i]))
			return (false);
		if (!IsNumber(laData[i]))
			return (false)
		else if (parseFloat(laData[i]) < 0)
			return (false);
	}

	/*
	** Se o dia estiver fora do limite para o mes dado, é invalida
	*/
	if (!((laData[0] >= 1) && (laData[0] <= laDiasMes[laData[1] - 1])))
		return (false);

	/*
	** Finalmente, se chegou até aqui, é uma data válida
	*/
	return (true);
}

/*
'[======================================================================================
'[= Nome		: IsMonth
'[= Descrição		: Verifica se uma string é um mês válida
'[= Entrada		: psData - String de data no formato MM/YYYY
'[= Saida		: True  - se a string for um mês
'[=			  False - caso contrário
'[= OBS			:
'[======================================================================================
*/
function IsMonth(psData)
{
	var laData    = SplitString(psData, '/');

	/*
	** Se não houver três partes a data é considerada inválida
	*/
	if (laData.length != 2)
		return false;
	
	/*
	** A string é dividida em três partes :
	**
	** laData[0] - Mês
	** laData[1] - Ano
	*/

	/*
	** Verifica se o mes está no intervalo [1,12]
	*/
	if (!(laData[0] >= 1 && laData[0] <= 12))
		return false;

	/*
	** Se o ano não tiver 4 digitos, é invalida
	*/
	if (laData[1].length != 4) 
		return false;

	/*
	** Finalmente, se chegou até aqui, é uma data válida
	*/
	return (true);
}

/*
'[================================================================================================
'[= Nome		: IsNumberInside
'[= Descrição		: Verifica se existe um número na string
'[= Entrada		: psText - Texto a ser verificado (pode ser um objeto)
'[= Saida		: True  - se a string contiver ao menos um número
'[=			  False - caso contrário
'[= OBS			: 
'[================================================================================================
*/
function IsNumberInside(psText)
{
	/*
	** Verifica se psText é um objeto
	*/
	if (psText == '[object]')
		var lsText = psText.value
	else
		var lsText = psText;
	
	/*
	** Percorre a string e verifica se exite um número
	*/
	for (var liPos = 0; liPos < lsText.length; liPos++)
		if (!isNaN(lsText.charAt(liPos)))
			return (true);
	
	/*
	** Se chegou até aqui, não existe número na string
	*/
	return (false);
}

/*
'[======================================================================================
'[= Constantes para a função FormatDate() e GetDate()
'[======================================================================================
*/
var dfShortDate       = 0;	// DD/MM/YYYY
var dfMediumDate      = 1;	// DD/MMM/YYYY
var dfLongDate        = 2;	// DDDD, DD de MMMM de YYYY.
var dfISO             = 3;	// YYYY/MM/DD
var dfAmerican        = 4;	// MM/DD/YYYY
var dfNoSlash         = 5;	// DDMMYYYY
var dfISONoSlash      = 6;	// YYYYMMDD
var dfAmericanNoSlash = 7;	// MMDDYYYY
/*
'[======================================================================================
*/

/*
'[======================================================================================
'[= FUNÇÕES DE DATA
'[======================================================================================
*/

//--------------------------------------------------------------------------------------
// Exibe a data corrente em formato (DDDD, DD de MMMM de YYYY)
//--------------------------------------------------------------------------------------
function GetDate(piFormat)
{
	var ldToday = new Date();
	var lsExit  = FormatDate(ldToday.getDate()       + '/' + 
							(ldToday.getMonth() + 1) + '/' + 
							 ldToday.getYear(), piFormat);
	return (lsExit);
}

/*
'[==========================================================================================
'[= Nome		: FormatDate
'[= Descrição		: Formata a data de acordo com o parâmetro passado
'[= Entrada		: psData   - Data a ser formatada (pode ser um Objeto ou String)
'[=			  piFormat - Identificação do Formato
'[= Saida		: Data Formatada
'[= OBS			: piFormat pode assumir um dos seguintes valores :
'[=
'[=         +-------------------+---+-----------------------+--------------------------+
'[=         | Costante          | # | Descrição             | Máscara VB               |
'[=         +-------------------+---+-----------------------+--------------------------+
'[=         | dfShotDate        | 0 | Data Curta            | DD/MM/YYYY               |
'[=         | dfMediumDate      | 1 | Data Média            | DD/MMM/YYYY              |
'[=         | dfLongDate        | 2 | Data Longa            | DDDD, DD de MMMM de YYYY |
'[=         | dfISO             | 3 | Data ISO              | YYYY/MM/DD               |
'[=         | dfAmerican        | 4 | Data Americana        | MM/DD/YYYY               |
'[=         | dfNoSlash         | 5 | Data Curta sem barras | DDMMYYYY                 |
'[=         | dfISONoSlash      | 6 | Data ISO sem barras   | YYYYMMDD                 |
'[=         | dfAmericanNoSlash | 7 | Data Americana s/ barr| MMDDYYYY                 |
'[=         +-------------------+---+-----------------------+--------------------------+
'[=
'[=			Se a psData for um objeto (por exemplo uma caixa de texto), a função também
'[=			altera a propriedade Value do objeto.
'[=
'[=			Default para piFormat : dfShortDate
'[=
'[==========================================================================================
*/
function FormatDate(psData, piFormat)
{
	var lsAux  = '';
	
	if (!(psData instanceof Date))
	{
		/*
		** Verifica se foi passado um objeto
		*/
		if (psData == '[object]')
			lsAux = psData.value
		else
			lsAux = psData;
	
		/*
		** Verifica o Default para piFormat
		*/
		piFormat = IIf ((piFormat == null), 0, piFormat);
	
		/*
		** Obtém a data como um objeto
		*/
		var ldData = DateValue(lsAux);
		
		
	}
	else
		var ldData = psData;
	
	/*
	** Se o Objeto não for uma data, retorna 
	*/
	if (ldData == null)
		return ('');
	
	/*
	** Formata a data corretamente
	*/
	var liWeekDay   = ldData.getDay();
	var liDay       = ldData.getDate();
	var liMonth     = ldData.getMonth();
	// esta função do javascript pega o ano menor que 1900 apenas dois digitos
	// portanto foi tirada = ldData.getYear();
	var liYear      
	
	liYear = Right('00'+ldData,4)

	var laWeekDays  = new Array('Domingo',
								'Segunda-feira',
								'Terca-feira',
								'Quarta-feira',
								'Quinta-feira',
								'Sexta-feira',
								'Sabado');
	var laMonthAbrev= new Array('JAN',
								'FEV',
								'MAR',
								'ABR',
								'MAI',
								'JUN',
								'JUL',
								'AGO',
								'SET',
								'OUT',
								'NOV',
								'DEZ');
	var laMonthName = new Array('Janeiro',
								'Fevereiro',
								'Marco',
								'Abril',
								'Maio',
								'Junho',
								'Julho',
								'Agosto',
								'Setembro',
								'Outubro',
								'Novembro',
								'Dezembro');
	var lsExit = '';
	

	
	if (piFormat == dfShortDate)
		/*
		** DD/MM/YYYY
		*/
		
		lsExit = Right('00' + liDay, 2) + '/' + Right('00' + (liMonth + 1), 2) + '/' + liYear
	else if (piFormat == dfMediumDate)
		/*
		** DD/MMM/YYYY
		*/
		lsExit = Right('00' + liDay, 2) + '/' + laMonthAbrev[liMonth] + '/' + liYear
	else if (piFormat == dfLongDate)
		/*
		** DDDD, DD de MMMM de YYYY
		*/
		lsExit = laWeekDays[liWeekDay] + ', ' + Right('00' + liDay, 2) + ' de ' + laMonthName[liMonth] + ' de ' + liYear
	else if (piFormat == dfISO)
		/*
		** YYYY/MM/DD
		*/
		lsExit = liYear + '/' + Right('00' + (liMonth + 1), 2) + '/' + Right('00' + liDay, 2)
	else if (piFormat == dfAmerican)
		/*
		** MM/DD/YYYY
		*/
		lsExit = Right('00' + (liMonth + 1), 2) + '/' + Right('00' + liDay, 2) + '/' + liYear
	else if (piFormat == dfNoSlash)
		/*
		** DDMMYYYY
		*/
		lsExit = Right('00' + liDay, 2) + Right('00' + (liMonth + 1), 2) + liYear
	else if (piFormat == dfISONoSlash)
		/*
		** YYYYMMDD
		*/
		lsExit = liYear + Right('00' + (liMonth + 1), 2) + Right('00' + liDay, 2)
	else if (piFormat == dfAmericanNoSlash)
		/*
		** MMDDYYYY
		*/
		lsExit = Right('00' + (liMonth + 1), 2) + Right('00' + liDay, 2) + liYear;
	
	return (lsExit);
}


/*
'[======================================================================================
'[= Nome		: CompareDate
'[= Descrição		: Compara duas datas no formato DD/MM/YYYY
'[= Entrada		: pdData1, pdData2
'[= Saida		: 1 - Se a pdData1 é posterior a pdData2
'[=			  0 - Se a pdData1 é igual     a pdData2
'[=			 -1 - Se a pdData1 é anterior  a pdData2
'[=	
'[= OBS			: A função retorna (-2) se as datas forem inválidas
'[======================================================================================
*/
function CompareDate1(pdData1, pdData2)
{
	/*
	** Varifica se os parâmetros são realmente datas
	*/
	if (!IsDate(pdData1) || !IsDate(pdData2))
		return (-2); // Código de Erro

	/*
	** Transforma as data de YYYYMMDD
	*/
	aData1 = pdData1.substring(6,10) + pdData1.substring(3,5) + pdData1.substring(0,2);
	aData2 = pdData2.substring(6,10) + pdData2.substring(3,5) + pdData2.substring(0,2);


	/*
	**Compara as datas
	*/

	if (aData1 > aData2){
		return (1); // Data1 é posterior a Data2
	}
	if (aData1 < aData2){
		return (-1); // Data1 é anterior  a Data2
	}
	return (0); // Data1 é igual a Data2
}


/*
'[======================================================================================
'[= Nome		: CompareDate
'[= Descrição		: Compara duas datas no formato DD/MM/YYYY
'[= Entrada		: pdData1, pdData2
'[= Saida		: 1 - Se a pdData1 é posterior a pdData2
'[=			  0 - Se a pdData1 é igual     a pdData2
'[=			 -1 - Se a pdData1 é anterior  a pdData2
'[=	
'[= OBS			: A função retorna (-2) se as datas forem inválidas
'[======================================================================================
*/
function CompareDate(pdData1, pdData2)
{
	/*
	** Varifica se os parâmetros são realmente datas
	*/
	if (!IsDate(pdData1) || !IsDate(pdData2))
		return (-2); // Código de Erro

	/*
	** Divide as Datas
	*/
	aData1 = SplitString(pdData1, '/');
	aData2 = SplitString(pdData2, '/');

	/*
	** Compara os Anos
	*/
	if (aData1[2] > aData2[2])
		return (1);  // Data1 é posterior a Data2
	
	if (aData1[2] < aData2[2])
		return (-1); // Data1 é anterior  a Data2
	
	/*
	** Compara os Meses
	*/
	if (aData1[1] > aData2[1])
		return (1);  // Data1 é posterior a Data2
	
	if (aData1[1] < aData2[1])
		return (-1); // Data1 é anterior  a Data2
	
	/*
	** Compara os Dias
	*/
	if (aData1[0] > aData2[0])
		return (1);  // Data1 é posterior a Data2
	
	if (aData1[0] < aData2[0])
		return (-1); // Data1 é anterior  a Data2
	
	return (0); // Data1 é igual a Data2
}

/*
'[======================================================================================
'[= Nome		: DateValue
'[= Descrição		: Retorna um objeto Date com o valor da data passada
'[= Entrada		: psData   - Data a ser convertida para objeto (pode ser um Objeto ou String)
'[= Saida		: Objeto Date
'[= OBS			: 
'[======================================================================================
*/
function DateValue(psData)
{
	var liDay   = 0;
	var liMonth = -1;
	var liYear  = 0;
	var lsAux   = '';
	
	/*
	** Verifica se psData já não é um Objeto Data
	*/
	if (psData instanceof Date)
		return (psData);
	
	/*
	** Verifica se psData é um Objeto
	*/
	if (psData == '[object]')
		var lsData = psData.value.toUpperCase()
	else
		var lsData = psData.toUpperCase();
	
	/*
	** Verifica se o valor passado não é uma dáta válida (DD/MM/YYYY)
	*/
	if (IsDate(lsData))
	{
		/*
		** É uma data válida
		*/
		var laData = SplitString(lsData, '/');
		
		return (new Date(laData[2], (laData[1] - 1), laData[0]));
	}

	/*
	** Tenta descobrir o Mês
	*/
	liMonth = IIf((lsData.indexOf('JAN') != (-1)), 0, liMonth);
	liMonth = IIf((lsData.indexOf('FEV') != (-1)), 1, liMonth);
	liMonth = IIf((lsData.indexOf('MAR') != (-1)), 2, liMonth);
	liMonth = IIf((lsData.indexOf('ABR') != (-1)), 3, liMonth);
	liMonth = IIf((lsData.indexOf('MAI') != (-1)), 4, liMonth);
	liMonth = IIf((lsData.indexOf('JUN') != (-1)), 5, liMonth);
	liMonth = IIf((lsData.indexOf('JUL') != (-1)), 6, liMonth);
	liMonth = IIf((lsData.indexOf('AGO') != (-1)), 7, liMonth);
	liMonth = IIf((lsData.indexOf('SET') != (-1)), 8, liMonth);
	liMonth = IIf((lsData.indexOf('OUT') != (-1)), 9, liMonth);
	liMonth = IIf((lsData.indexOf('NOV') != (-1)),10, liMonth);
	liMonth = IIf((lsData.indexOf('DEZ') != (-1)),11, liMonth);
	
	/*
	** Obtém só os caracteres numéricos
	*/
	for (var liPos = 0; liPos < psData.length; liPos++)
		if (!isNaN(psData.charAt(liPos)) && psData.charAt(liPos) != ' ')
			lsAux += psData.charAt(liPos);
	
	/*
	** Verifica quantos caracteres tem
	*/
	if (lsAux.length == 8)
	{
		/*
		** Se tiver 8 caracteres, tenta interpretar como data em diversos formatos
		*/
		liDay   = Left(lsAux, 2);
		liMonth = lsAux.substr(2, 2);
		liYear  = Right(lsAux, 4);
		
		/*
		** Verifica se gfAllDate é false para tratar apenas DD/MM/YYYY
		*/
		if (!gfAllDate)
		{
			/*
			** Tenta DD/MM/YYYY
			*/
			lsData  = Right('00' + liDay, 2) + '/' + Right('00' + liMonth, 2) + '/' + liYear;
			if (IsDate(lsData))
				return (new Date(liYear, (liMonth - 1), liDay));
			
			/*
			** Data considerada inválida.
			*/
			return (null);
		}
			
		/*
		** Se o Ano for > 1900 então tenta DD/MM/YYYY ou MM/DD/YYYY
		*/
		if (parseInt(liYear) > 1900)
		{
			/*
			** Tenta DD/MM/YYYY
			*/
			lsData  = Right('00' + liDay, 2) + '/' + Right('00' + liMonth, 2) + '/' + liYear;
			if (IsDate(lsData))
				return (new Date(liYear, (liMonth - 1), liDay));

			/*
			** Tenta MM/DD/YYYY
			*/
			lsData  = Right('00' + liMonth, 2) + '/' + Right('00' + liDay, 2) + '/' + liYear;
			if (IsDate(lsData))
				return (new Date(liYear, (liDay - 1), liMonth));
		}

		/*
		** Obtém Dia Mês e Ano para YYYY/MM/DD
		*/
		liDay   = Right(lsAux, 2);
		liMonth = lsAux.substr(4, 2);
		liYear  = Left(lsAux, 4);

		/*
		** Tenta YYYY/MM/DD
		*/
		lsData  = Right('00' + liDay, 2) + '/' + Right('00' + liMonth, 2) + '/' + liYear;
		if (IsDate(lsData))
			return (new Date(liYear, (liMonth - 1), liDay));
	}
	else if (lsAux.length == 6)
	{
		/*
		** Verifica se foi encontrado o mês
		*/
		if (liMonth != (-1))
		{
			/*
			** Assume DDYYYY
			*/
			liDay  = Left (lsAux, 2);
			liYear = Right(lsAux, 4);
		}
		else
		{
			/*
			** Assume MMYYYY
			*/
			liDay   = 1;
			liMonth = Left (lsAux, 2);
			liYear  = Right(lsAux, 4);
		}

		/*
		** Verifica se é uma Data válida
		*/
		lsData  = Right('00' + liDay, 2) + '/' + Right('00' + (liMonth + 1), 2) + '/' + liYear;
		if (IsDate(lsData))
			return (new Date(liYear, (liMonth - 1), liDay));
	}
	
	/*
	** Tenta obter a data através de Date.parse
	*/
	var ldData = Date.parse(lsData);
	
	/*
	** Verifica se é uma data válida
	*/
	if (!isNaN(ldData))
		return (new Date(ldData));

	/*
	** Se chegou aqui, não é uma data válida
	*/
	return (null);
}

/*
'[======================================================================================
'[= Nome		: DateAdd
'[= Descrição		: Soma um determinado número de dias à uma data
'[= Entrada		: psDate - Data a ser convertida para objeto (pode ser um Objeto ou String)
'[=			  piDays - Numero de dias a ser adicionado
'[= Saida		: Objeto Date
'[= OBS			: 
'[======================================================================================
*/
function DateAdd(pdDate, piDays)
{
	/*
	** Verifica se pdData é um Objeto Date
	*/
	if (pdDate instanceof Date)
		var ldData = pdDate;
	else
		/*
		** Verifica se o parâmetro não é um objeto
		*/
		if (pdDate == '[object]')
			var ldData = DateValue(pdDate.value)
		else
			var ldData = DateValue(pdDate);
	 
	/*
	** Adiciona o número de dias
	*/
	ldData.setDate(ldData.getDate() + piDays);
	 
	/*
	** Retorna a data somada
	*/
	return (ldData);
}

/*
'[======================================================================================
'[= FUNÇÕES DE VALOR
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: ExactVal
'[= Descrição		: Retorna o valor numérico de uma String
'[= Entrada		: psNumber - String Numérica
'[= Saida		: Valor Numérico
'[= OBS			: Tanto a vírgula quanto o ponto serão tratados como separador decimal,
'[=				  Sendo considerado o ponto ou a vírgula mais a direita.
'[=				  Retorna 0 se o valor passado não for numérico.
'[======================================================================================
*/
function ExactVal(psNumber)
{
	/*
	** Verifica se o valor passado é um número
	*/
	if (!IsNumber(psNumber))
		return (0);

	var strAux  = new String('');
	var strChar = '';
	
	/*
	** Fica apenas com os números e um ponto decimal
	*/
	for (intCount = (psNumber.length - 1); intCount >= 0; intCount--)
	{
		if ( (psNumber.charAt(intCount) >= '0') && (psNumber.charAt(intCount) <= '9') )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == '-') && ( strAux.indexOf('-') < 0 ) )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == '.') && ( strAux.indexOf('.') < 0 ) )
		{
			strChar = psNumber.charAt(intCount);
			strAux = strChar + strAux;
		}
		else if ( (psNumber.charAt(intCount) == ',') && ( strAux.indexOf(',') < 0 ) )
			if (strAux.indexOf('.') == (-1))
				strAux = '.' + strAux;
	}
	
	/*
	** Se não foi achado um ponto decimal, retorna o valor
	*/
	if (strAux.indexOf(".") < 0)
		return parseFloat(strAux);
	
	/*
	** Obtém a parte inteira e a parte decimal
	*/
	strInt = strAux.substr(0, strAux.indexOf("."));
	strDec = strAux.substr(strAux.indexOf(".") + 1, (strAux.length - (strAux.indexOf(".") + 1)));
	
	if (strInt == '-' || strInt == '')
		strInt = strInt + '0';
		
	if (strDec == '')
		strDec = '0';

	/*
	** Retorna o valor correto
	*/
	if (parseFloat(strInt) < 0)
		return (parseFloat(strInt) - parseFloat(strDec) / Math.pow(10, strDec.length));
	else
		return (parseFloat(strInt) + parseFloat(strDec) / Math.pow(10, strDec.length));
}

/*
'[======================================================================================
'[= Nome		: NumberFormat
'[= Descrição		: Formata um número com o seguinte formato #.##0,00 so para porcentagem
'[= Entrada		: pdblNumber - Número a ser formatado
'[=			  plDecimals - Número de casas Decimais
'[=			  plIntegers - Número de casas Interiras
'[= Saida		: Número formatado
'[= OBS			: 
'[======================================================================================
*/
function NumberFormat(tNum,tDec){
	var chknum = IsNumber(tNum);
	if(chknum==false){
		return '';
	}
	var i=0;
	if(tNum==''){
		tNum='0,00';
	}
	var stNum = tNum.replace(".",",");
	var TamstNum = stNum.length;
	var strVirgula = stNum.indexOf(",");
	if(strVirgula==-1){
		if(TamstNum > -1){
			strVirgula=TamstNum+1;
		}else{
			strVirgula='1';
		}
	}
	var nEsquerda = stNum.substring(0,strVirgula);
	var nDireita = stNum.substring(strVirgula+1,TamstNum);
	//Testa as casas decimais
	if(nDireita != ''){
		var strValidos = "0123456789" 
		for(i=0;nDireita.length>i;i++){
			if ( strValidos.indexOf( nDireita.substring(i,i+1) ) == -1 ){
				return '';
			}
		}
	}
	//Testa antes da virgula
	if(nEsquerda != ''){
		var strValidos = "0123456789" 
		for(i=0;nEsquerda.length>i;i++){
			if ( strValidos.indexOf( nEsquerda.substring(i,i+1) ) == -1 ){
				return '';
			}
		}
	}


	if(nEsquerda==''){
		nEsquerda='0';
	}
	if(nDireita.length > 2){
		alert('ATENCÃO!!!\nSó será permitido ' + tDec + ' casas decimais.\n\nO valor informado ' + tNum + ' será transformado em ' +  nEsquerda + ',' + nDireita.substring(0,tDec));
	}
	if(nDireita.length <= 1 || nDireita == ''){
		for(i=0;parseInt(tDec)>i;i++){
			nDireita += '0';
		}
	}
	if(nEsquerda.length > 3){
		return '';
	}
	if(nEsquerda > 100){
		return '';
	}

	return nEsquerda + ',' + nDireita.substring(0,tDec);
}





/*
'[======================================================================================
'[= Nome		: NumberFormatAll
'[= Descrição		: Formata um número com o seguinte formato #.##0,00
'[= Entrada		: pdblNumber - Número a ser formatado
'[=			  plDecimals - Número de casas Decimais
'[=			  plIntegers - Número de casas Interiras
'[= Saida		: Número formatado
'[= OBS			: 
'[======================================================================================
*/

function NumberFormatAll(pdblNumber, plDecimals, plIntegers)
{
	/*
	** Se assegura que é um número
	*/
	var ldblNumber = ExactVal(pdblNumber + IIf(plDecimals == 0, '.', ''));
	
	/*
	** Verifica se plDecimals é um número positivo
	*/
	plDecimals = Math.abs(plDecimals);
	
	/*
	** Obtém a parte Inteira e Decimal do número
	*/
	var lsInteger = Math.floor(ldblNumber).toString();
	var lsDecimal = ldblNumber.toString().slice(lsInteger.length + 1);
		lsDecimal = lsDecimal.toString();
	
	
	/*
	** Soluciona um pequeno bug com números negativos
	**
	** Explicação do Bug:
	**		A função Math.floor() retorna o menor número inteiro do parâmetro passado,
	**		ou seja, para 1.5 retorna 1.
	**
	**		O bug ocorre quando o núemro é negativo, então para -1.5 retorna -2, que é
	**		o menor número inteiro mais próximo de -1.5 (para quem não lembra -1.5 > -2)
	**
	**		Então as duas linhas abaixo consertam este pequeno desvio.
	*/
	if ((ldblNumber < 0) && (lsDecimal > 0))
		lsInteger = Math.floor(ldblNumber + 1).toString();
	
	/*
	** Verifica o tamanho da parte inteira, se for passado o parâmetro
	*/
	if (plIntegers != null)
		if (lsInteger.length > plIntegers)
		{
			if (gfShowAlert)
				alert ('Número maior que o permitido.');
			
			return ('');
		}

	/*
	** Coloca as casas decimais do tamanho certo
	*/
	if (lsDecimal.length > plDecimals){
		alert('ATENÇÃO!!!\nSó será permitido ' + plDecimals + ' casas decimais.\n\nO valor informado ' + pdblNumber + ' será transformado em ' + lsInteger + ',' + Left(lsDecimal, plDecimals));
	}
	if (lsDecimal.length < plDecimals)
		for (var liPos = lsDecimal.length; liPos < plDecimals; liPos++)
			lsDecimal += '0';
	else
		lsDecimal = Left(lsDecimal, plDecimals);

	/*
	** Varre a string da direita para a esquerda, colocando o ponto como separador de milhar
	*/
	var lsAux = '';
	var liCount = 0;
	for (var liPos = lsInteger.length - 1; liPos >= 0; liPos--)
	{
		if ((Math.floor((liCount) / 3) * 3 == liCount) && (liCount != 0) && (lsInteger.charAt(liPos) != '-'))
			lsAux = '.' + lsAux;
		
		lsAux = lsInteger.charAt(liPos) + lsAux;
		liCount++;
	}
	
	if (plDecimals == 0)
		return (lsAux)
	else
		return (lsAux + ',' + lsDecimal);
}

/*
'[======================================================================================
'[= Nome		: Round
'[= Descrição		: Arredonda um número Float em um número de casas determinado
'[= Entrada		: pdblNumber - Número a ser arredondado
'[=			  plDecimals - Número de casas decimais
'[= Saida		: Número arredondado
'[= OBS			: 
'[======================================================================================
*/
function Round(pfNumber, plDecimals)
{
	var lfAux = ExactVal(pfNumber.toString()) * Math.pow(10, plDecimals);
	
	return (Math.round(lfAux) / Math.pow(10, plDecimals));
}

/*
'[======================================================================================
'[= FUNÇÕES DE STRING
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: LTrimString
'[= Descrição		: Remove os Espaços à esquerda de uma String
'[= Entrada		: psText
'[= OBS			: String sem os espaços à esquerda
'[======================================================================================
*/
function LTrimString(psText)
{
	var lsAux = '';
	
	/*
	** Verifica se psText é um objeto
	*/
	if (psText == '[object]')
		lsAux = psText.value
	else
		lsAux = psText;
	
	for (var i = 0; i < lsAux.length; i++)
		if (lsAux.substr(i, 1) != ' ')
			break;
	
	return (lsAux.substr(i));
}

/*
'[======================================================================================
'[= Nome		: RTrimString
'[= Descrição		: Remove os Espaços à direita de uma String
'[= Entrada		: psText
'[= OBS			: String sem os espaços à direita
'[======================================================================================
*/
function RTrimString(psText)
{
	var lsAux = '';
	
	/*
	** Verifica se psText é um objeto
	*/
	if (psText == '[object]')
		lsAux = psText.value
	else
		lsAux = psText;
	
	for (var i = (lsAux.length - 1); i > 0; i--)
		if (lsAux.substr(i, 1) != ' ')
			break;
	
	return (lsAux.substr(0, i + 1));
}

/*
'[======================================================================================
'[= Nome		: TrimString
'[= Descrição		: Remove os Espaços à direita e à esquerda de uma String
'[= Entrada		: psText
'[= OBS			: String sem os espaços
'[======================================================================================
*/
function TrimString(psText)
{
	return (LTrimString(RTrimString(psText)));
}

/*
'[======================================================================================
'[= FUNÇÕES ESPECIAIS
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: LeadingZeros
'[= Descrição		: Completa campo com os zeros a esquerda
'[= Entrada		: psNumero  - Valor a ser alinhado a direita
'[=              	  plTamanho - Tamanho total
'[= OBS			:	
'[======================================================================================
*/
function LeadingZeros(psNumero,plTamanho)
{
	var lsZeros = '';
	
	for (var liCount = 0; liCount <= plTamanho; liCount++)
		lsZeros += '0';
	
	return (Right(lsZeros + psNumero, plTamanho));
}

/*
'[================================================================================================
'[= Nome		: CheckIdenticos
'[= Descrição		: Retorna um Array com os caracteres repetidos de uma String
'[= Entrada		: psText   - String a ser verificada (pode ser um objeto)
'[=             	  piMinLen - Número mínimo de repetições de um caracter para ser capturado pela função
'[= Saida		: Array contendo os caracteres repetidos
'[= OBS			:	
'[================================================================================================
*/
function CheckIdenticos(psText, piMinLen)
{
	var lsChar      = '';
	var lsIdenticos = '';
	var laIdenticos = new Array();
	
	/*
	** Verifica se foi passado o 2º parâmetro
	*/
	if (piMinLen == null)
		piMinLen = 2;
	
	/*
	** Verifica se piMinLen é um número
	*/
	if (isNaN(piMinLen))
		piMinLen = 2;
	
	/*
	** Verifica se psText é um objeto
	*/
	if (psText == '[object]')
		var lsText = psText.value
	else
		var lsText = psText;
	
	for (var liPos = 0; liPos < lsText.length; liPos++)
	{
		/*
		** Obtém um caracter
		*/
		if (lsChar == '')
			lsChar = lsText.charAt(liPos)
		else
		{
			/*
			** Verifica se o caracter atual é identico ao anterior
			*/
			if (lsChar == lsText.charAt(liPos))
				/*
				** Se for idêntico concatena na string
				*/
				lsIdenticos += lsChar
			else
			{
				/*
				** Verifica se há uma string de caracteres
				*/
				if (lsIdenticos != '')
				{
					/*
					** Adiciona no Array e limpa a string
					*/
					if ((lsIdenticos.length + 1) >= piMinLen)
						laIdenticos = laIdenticos.concat (lsChar + lsIdenticos);

					lsIdenticos = '';
				}
				
				/*
				** Assume o caracter como o atual
				*/
				lsChar = lsText.charAt(liPos);
			}
		}
	}
	
	/*
	** Verifica se há uma string de caracteres
	*/
	if (lsIdenticos != '')
	{
		/*
		** Adiciona no Array e limpa a string
		*/
		if ((lsIdenticos.length + 1) >= piMinLen)
			laIdenticos = laIdenticos.concat (lsIdenticos.charAt(0) + lsIdenticos);
			
		lsIdenticos = '';
	}
	
	/*
	** Retorna o array de identicos
	*/
	return (laIdenticos);
}

/*
'[======================================================================================
'[= FUNÇÕES AUXILIARES
'[======================================================================================
*/

/*
'[======================================================================================
'[= Nome		: Left
'[= Descrição		: Retorna os n primeiros caracteres de uma string
'[= Entrada		: psString  - String
'[=            		  plLength  - Número de caracteres
'[= Saida		: Retorna os n primeiros caracteres de uma string
'[= OBS			:	
'[======================================================================================
*/
function Left(psString, plLength)
{
	return (psString.substring (0, plLength));
}

/*
'[======================================================================================
'[= Nome		: Right
'[= Descrição		: Retorna os n últimos caracteres de uma string
'[= Entrada		: psString  - String
'[=               	  plLength  - Número de caracteres
'[= Saida		: Retorna os n últimos caracteres de uma string
'[= OBS			:	
'[======================================================================================
*/
function Right(psString, plLength)
{
	return (psString.substr(psString.length - plLength, plLength));
}

/*
'[======================================================================================
'[= Nome		: SplitString
'[= Descrição		: Divide a string por um separador dado, retornando um array com os valores.
'[= Entrada		: psString  - String a ser dividida
'[=               	  psDivider - Divisor
'[= Saida		: Array com os items
'[= OBS			:	
'[======================================================================================
*/
function SplitString(psString, psDivider)
{
	/*
	** Conta o número de ocorrências do separador para saber quantos elementos terá o Array.
	*/
	var liOccurs = 0;
	
	for (var liCount = 0; liCount < (psString.length - psDivider.length); liCount++)	
		if (psString.substr(liCount, psDivider.length) == psDivider)
			liOccurs++;
			
	/*
	** Cria o array
	*/
	var laRet = new Array(liOccurs);
	var lsAux = '';
	
	liCount  = 0;
	liOccurs = 0;
	do
	{
		if (psString.substr(liCount, psDivider.length) == psDivider)
		{
			liCount += psDivider.length;
			laRet[liOccurs++] = lsAux;
			lsAux = '';
		}
		
		lsAux += psString.charAt(liCount++);
	}
	while (liCount < psString.length);
	
	laRet[liOccurs++] = lsAux;
	
	return (laRet);
}

/*
'[======================================================================================
'[= Nome		: Replace
'[= Descrição		: Pesquisa a string psSearch dentro da string psText, trocando por psReplace
'[= Entrada		: psText    - String a ser pesquisada
'[=               	  psSearch  - String a ser localizada
'[=			  psReplace - String a ser colocada no lugar de psSearch
'[= Saida		: String com psSearch trocada por psReplace
'[= OBS			:	
'[======================================================================================
*/
function Replace(psText, psSearch, psReplace)
{
	var liLen   = psSearch.length;
	var liPos   = psText.indexOf(psSearch);
	var lsLeft  = '';
	var lsRight = '';
	        
	while (liPos > (-1))
	{
		lsLeft  = psText.substring(0, liPos);
		lsRight = psText.substring(liPos + liLen , psText.length);
		psText  = lsLeft + psReplace + lsRight;
		liPos   = psText.indexOf(psSearch);
	}
	        
	return (psText);
}

/*
'[======================================================================================
'[= Nome		: GetValueFromText
'[= Descrição		: Pesquisa no SELECT a string psText, retornando o valor do OPTION
'[= Entrada		: poSelect - Objeto SELECT
'[=			  psText   - String a ser pesquisada
'[= Saida		: Propriedade VALUE do OPTION referente a string psText
'[= OBS			:	
'[======================================================================================
*/
function GetValueFromText(poSelect, psText)
{

	var liPos = 0;

	for (liPos = 0; liPos < poSelect.options.length; liPos++)
		if (poSelect.options[liPos].text.toUpperCase() == psText.toUpperCase())
			return (poSelect.options[liPos].value);
	
	return ('\0x00'); 
}

/*
'[======================================================================================
'[= Nome		: IIf
'[= Descrição		: Caso a condição seja verdadeira assume o primeiro valor, senão o segundo.
'[= Entrada		: pbCond       - Condição a ser avaliada
'[=                  	  pvValueTrue  - Valor caso pbCond for verdadeiro
'[=               	  pvValueFalse - Valor caso contrário
'[= Saida		: pvValueTrue ou pvValueFalse
'[= OBS			:	
'[======================================================================================
*/
function IIf(pbCond, pvValueTrue, pvValueFalse)
{
	if (pbCond)
		return (pvValueTrue)
	else
		return (pvValueFalse);
}

/*
'[======================================================================================
'[= Nome		: TypeOf
'[= Descrição		: Retorna a descrição do tipo de objeto passado
'[= Entrada		: poObject - Objeto a ser testado
'[= Saida		: Nome do tipo de Objeto
'[= OBS			:	
'[======================================================================================
*/
function TypeOf(poObject)
{
	if (poObject instanceof ActiveXObject)
		return ('ActiveXObject');

	if (poObject instanceof Array)
		return ('Array');

	if (poObject instanceof Boolean)
		return ('Boolean');

	if (poObject instanceof Date)
		return ('Date');

	if (poObject instanceof Dictionary)
		return ('Dictionary');

	if (poObject instanceof Enumerator)
		return ('Enumerator');

	if (poObject instanceof Error)
		return ('Error');

	if (poObject instanceof FileSystemObject)
		return ('FileSystemObject');

	if (poObject instanceof Function)
		return ('Function');

	if (poObject instanceof Number)
		return ('Number');

	if (poObject instanceof RegExp)
		return ('RegExp');

	if (poObject instanceof String)
		return ('String');

	if (poObject instanceof VBArray)
		return ('VBArray');

	if (poObject instanceof Object)
		if (poObject.tagName == null)
			return ('Object')
		else
			return (poObject.tagName);

	return ('Unknown');
}

/*
'[======================================================================================
'[= FUNÇÕES MISTAS
'[======================================================================================
*/

//**************************************************************************************
//****  FUNÇÕES DE DATA
//**************************************************************************************

//--------------------------------------------------------------------------------------
// Exibe a data corrente em formato (Dia da Semana, Dia  Nome Mês  Ano)
//--------------------------------------------------------------------------------------
function ExibeDataCorrente()
{
	var DataCorrente = new Date();
	var Dia			 = DataCorrente.getDay();	
	var Mes			 = DataCorrente.getMonth();
	var Ano			 = DataCorrente.getYear();
	var Data		 = DataCorrente.getDate();
	var DiasSemana = new Array("Domingo","Segunda-feira","Terca-feira","Quarta-feira",
							   "Quinta-feira","Sexta-feira","Sabado");
	var MesesAno   = new Array("Janeiro","Fevereiro","Marco","Abril","Maio","Junho","Julho",
						  	   "Agosto","Setembro","Outubro","Novembro","Dezembro");
	var DataFormatada = DiasSemana[Dia] +
						", " + Data +
						" " + MesesAno[Mes] +
						" " + Ano;
	document.writeln(DataFormatada);
}



//--------------------------------------------------------------------------------------
// Retira ".", ",", "/", "-" da String
//--------------------------------------------------------------------------------------
	function LimpaString(obj)
	{
		var string
		var stringaux
		var stringinv
		var j
		var car
		
		string=obj.value
		stringaux = ''
		stringinv = ''
		
		for(j=string.length-1; j>=0; j--)
		{
			car=string.substring(j+1,j)
			stringinv=stringinv+car
		}
		
		for(j=stringinv.length-1; j>=0; j--)
		{
			car=stringinv.substring(j+1,j)
			if(car!=',' && car!='.' && car!='/' && car!='-')
			{
				stringaux=stringaux+car
			}
		}

		obj.value = stringaux
	}




//**************************************************************************************
//****  FUNÇÕES ESPECIAIS
//**************************************************************************************

//--------------------------------------------------------------------------------------
// Valida o CNPJ ou o CPF informado
//--------------------------------------------------------------------------------------
function ValidaCnpjCpf(controle)
{
	var tam=0,acum=0,i=0,fat_mult=0,aux,dv1,dv2;
	
	if (controle==null)
	{
		return false;
	}	

	if(controle.value=='' || controle.value == null)
	{
		return false;		
	}

	numero = new String(controle.value);
	tam = numero.length;

	if (tam != 11 && tam != 14)
	{
		if (gfShowAlert)
			alert('CNPJ/CPF inválido');
		controle.focus();
		return false;		
	}
	
	//verificando numerico
	aux='';
	for(i=0;i < tam;i++)
	{
		if (!(numero.charAt(i) >='0' && numero.charAt(i) <= '9'))
		{
			aux='Erro';
		}
	}
	if (aux == 'Erro')
	{
		if (gfShowAlert)
			alert('CNPJ/CPF inválido');
		controle.focus();
		return false;		
	}

	//validando CPF
	if (tam == 11)
	{
		//obtendo dv1
		acum =0;
		for (i=1;i<=9;i++)
		{
			fat_mult = (i + 1);
			acum = acum + (numero.charAt(9 - i) * fat_mult);
		}
		if ((acum % 11 == 0) || (acum % 11 == 1))
		{
			dv1 = '0';
		}
		else
		{
			dv1 = (11 - (acum % 11));
		}

		//obtendo dv2
		acum =0;
		for (i=0;i<=9;i++)
		{
			fat_mult = (i + 2);
			if (i == 0)
			{
				acum = acum + (dv1 * fat_mult);
			}
			else
			{
				acum = acum + (numero.charAt(9 - i) * fat_mult);
			}
		}
		if ((acum % 11 == 0) || (acum % 11 == 1))
		{
			dv2 = '0';
		}
		else
		{
			dv2 = (11 - (acum  % 11));
		}

		//comparando digitos
		aux = numero.charAt(9) + numero.charAt(10);
		if (aux != (dv1 + '' + dv2))
		{
			if (gfShowAlert)
				alert('CNPJ/CPF inválido');
			controle.focus();
			return false;		
		}
	}

	//validando CNPJ
	if (tam == 14)
	{
		//obtendo dv1
		acum = 0;
		for (i=1;i<=12;i++)
		{
			if (i <= 9)
			{
				fat_mult = i + 1;
			}
			else
			{
				fat_mult = i - 7;
			}
			acum = acum + (numero.charAt(13-i) * fat_mult);
		}
		if ((acum % 11 == 0) || (acum % 11 == 1))
		{
			dv1 = '0';
		}
		else
		{
			dv1 = (11 - (acum % 11));
		}

		//obtendo dv2
		for(i=0;i<=12;i++)
		{
			if (i <= 8)
			{
				fat_mult = i + 2;

				if (i ==0)
				{
					acum = acum + (dv1 * fat_mult);
				}
			}
			else
			{
				fat_mult = i - 6;
			}
			if (i > 0)
			{
				acum = acum + (numero.charAt(13-i) * fat_mult);
			}
		}
		if ((acum % 11 == 0) || (acum % 11 == 1))
		{
			dv2 = '0';
		}
		else
		{
			dv2 = (11 - (acum % 11));
		}

		//comparando digitos
		aux = numero.charAt(12) + numero.charAt(13);
		if (aux != (dv1 + '' + dv2))
		{
			if (gfShowAlert)
				alert('CNPJ/CPF inválido');
			controle.focus();
			return false;		
		}
	}
	
	return true;
}

//--------------------------------------------------------------------------------------
// Verifica se existem 3 letras repetidas consecutivas
//--------------------------------------------------------------------------------------
//Obj - Deve ser passado o value do objeto
//A Funcao irá retornar True ou False

function ValidaLetraRepetida(obj)
{    
	var liCont
	var lsCaracter
	 
	for (liCont = 0; liCont < (obj.length) - 1; liCont++)
	{
		lsCaracter = obj.substring(liCont, liCont + 1).toUpperCase()
		if ((lsCaracter == obj.substring(liCont + 1, liCont + 2).toUpperCase()) && (lsCaracter == obj.substring(liCont + 2, liCont + 3).toUpperCase()))
		return false
	}
	return true
}

/*
'[================================================================================================
'[= Nome		: VerificaCpfCnpj
'[= Descrição		: valida um CPF ou CNPJ de um campo ou string.
'[= Entrada		: str  - String Contendo o CPF ou CNPJ
'[=			  tipo - Identificador do CPJ ou CNPJ
'[=							1 - CPF
'[=							2 - CNPJ
'[=							3 - Autodetect
'[= Saida		: true  - se o CPF ou CNPJ for válido
'[=			  false - caso contrário
'[= OBS			: 
'[================================================================================================
*/
function VerificaCpfCnpj(str, tipo)
{
	/*
	** Verifica se str é um Objeto
	*/
	var lbObject = (str == '[object]');
//    var numero;
//	
//	numero = str.value;
////	
//	numero = numero.replace( "/", "" );
//	numero = numero.replace(".","");
//	numero = numero.replace(".","");
//	numero = numero.replace(".","");
//	numero = numero.replace(".","");
//	numero = numero.replace(".","");
//	numero = numero.replace(".","");
//	numero = numero.replace("/","");
//	numero = numero.replace("/","");
//	numero = numero.replace("-","");
//	numero = numero.replace("-","");
//	numero = numero.replace( " ", "" );
	
	/*
	** Valida CPF
	*/

	if (tipo == 1)
	{
		if (!checkCPF(str))
		{
			if (lbObject)
			{
				if (gfShowAlert)
					alert("CPF: "+ str.value + "\n\rCPF Invalido. Favor digita-lo corretamente.");
				str.focus();
			}
			return false; 
		}
		return true;
	}
	/*
	** Valida CNPJ
	*/
	else if (tipo == 2)
	{
		if (!checkCGC(str))
		{
			if (lbObject) 
			{
				if (gfShowAlert)
					alert("CNPJ: "+ str.value + "\n\rCNPJ Invalido. Favor digita-lo corretamente.");
				str.focus();
			}
			return false; 
		}
		return true;
	}
	/*
	** Autodetect (Valida os Dois, se um retornar verdadeiro...)
	*/
	else if(tipo == 3)
	{
		if (!checkCPF(str) && !checkCGC(str))
		{
			if (lbObject) 
			{
				if (gfShowAlert)
					alert("CPF/CNPJ: "+ str.value + "\n\rCPF/CNPJ Invalido. Favor digita-lo corretamente.");
				str.focus();
			}
			return false; 
		}
		return true;
	}
    
}

/*
'[================================================================================================
'[= Nome		: checkCPF
'[= Descrição		: Efetua a validação de CPF
'[= Entrada		: cpf - CPF a ser validado
'[= Saida		: true  - se o CPF for válido
'[=			  false - caso contrário
'[= OBS			:	
'[================================================================================================
*/
function  checkCPF(psCPF) 
{

//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace(".","");
//	psCPF = psCPF.replace("/","");
//	psCPF = psCPF.replace("/","");
//	psCPF = psCPF.replace("-","");
//	psCPF = psCPF.replace("-","");

	var lsAux    = '';
	var lsCPF    = '';
	var liPeso   = 2;
	var liSoma   = 0;
	var liTemp   = 0;
	var liDigito = 0;
	
	/*
	** Verifica se recebeu um objeto
	*/
	if (psCPF == '[object]')
		lsCPF = psCPF.value
	else
		lsCPF = psCPF;
	
	var liPos  = 0;

	/*
	** Remove qualquer caracter que não seja número
	*/
	for (liPos = lsCPF.length - 1; liPos >= 0; liPos--)
		if (!isNaN(lsCPF.charAt(liPos)))
			lsAux = lsCPF.charAt(liPos) + lsAux;
			
	/*
	** Cálculo do 1º dígito
	*/
	for (liPos = lsAux.length - 3; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCPF.charAt(liPos)) * liPeso;
		liPeso++;
	}
	
	liTemp   = (liSoma % 11);
	liDigito = IIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 1º dígito
	*/
	if (parseInt(lsCPF.charAt(lsCPF.length - 2)) != liDigito)
		return (false);
	
	/*
	** Limpa as Variáveis
	*/
	liPeso = 2;
	liSoma = 0;

	/*
	** Cálculo do 2º dígito
	*/
	for (liPos = lsAux.length - 2; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCPF.charAt(liPos)) * liPeso;
		liPeso++;
	}
	
	liTemp   = (liSoma % 11);
	liDigito = IIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 2º dígito
	*/
	if (parseInt(lsCPF.charAt(lsCPF.length - 1)) != liDigito)
		return (false);
	
	return (true);
}
 
/*
'[================================================================================================
'[= Nome		: checkCGC
'[= Descrição		: Efetua a validação de CGC
'[= Entrada		: CGC - CGC a ser validado
'[= Saida		: true  - se o CGC for válido
'[=			  false - caso contrário
'[= OBS			:	
'[================================================================================================
*/
function checkCGC(psCNPJ) 
{

//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace(".","");
//	psCNPJ = psCNPJ.replace("/","");
//	psCNPJ = psCNPJ.replace("/","");
//	psCNPJ = psCNPJ.replace("-","");
//	psCNPJ = psCNPJ.replace("-","");

	var liPeso = 2;
	var liSoma = 0;
	var lsAux  = '';
	var liTemp = 0;
	var liDigito = 0;
	var lsCNPJ = '';
	
	/*
	** Verifica se recebeu um objeto
	*/
	if (psCNPJ == '[object]')
		lsCNPJ = psCNPJ.value
	else
		lsCNPJ = psCNPJ;
	
	var liPos  = 0;

	/*
	** Remove qualquer caracter que não seja número
	*/
	for (liPos = lsCNPJ.length - 1; liPos >= 0; liPos--)
		if (!isNaN(lsCNPJ.charAt(liPos)))
			lsAux = lsCNPJ.charAt(liPos) + lsAux;
			
	/*
	** Cálculo do 1º dígito
	*/
	for (liPos = lsAux.length - 3; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCNPJ.charAt(liPos)) * liPeso;
		liPeso  = IIf((liPeso == 9), 2, liPeso + 1);
	}
	
	liTemp   = (liSoma % 11);
	liDigito = IIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 1º dígito
	*/
	if (parseInt(lsCNPJ.charAt(lsCNPJ.length - 2)) != liDigito)
		return (false);
	
	/*
	** Limpa as Variáveis
	*/
	liPeso = 2;
	liSoma = 0;

	/*
	** Cálculo do 2º dígito
	*/
	for (liPos = lsAux.length - 2; liPos >= 0; liPos--)
	{
		liSoma += parseInt(lsCNPJ.charAt(liPos)) * liPeso;
		liPeso  = IIf((liPeso == 9), 2, liPeso + 1);
	}
	
	liTemp   = (liSoma % 11);
	liDigito = IIf((liTemp < 2), 0, (11 - liTemp));
	
	/*
	** Compara o 2º dígito
	*/
	if (parseInt(lsCNPJ.charAt(lsCNPJ.length - 1)) != liDigito)
		return (false);
	
	return (true);
}

/*
'[================================================================================================
'[= Nome		: FormatarData
'[=
'[= Descrição		: Efetua a formatação de data
'[= Entrada		: 
'[= Saida		: true  - se o CGC for válido
'[=			  false - caso contrário
'[= OBS			:	
'[================================================================================================
*/

function FormatarData(obj)
{
	var data = '';
	var dia = '';
	var mes = '';
	var ano = '';
	var i;

	if (obj.value == '')
	{
		return false;
	}

	for(i=0;i<obj.value.length;i++)
	{
		if ((obj.value.charAt(i) >= 0) && (obj.value.charAt(i) <= 9))
		{
			data = data + obj.value.charAt(i);
		} 
	}

	if (data.length != 8)
	{
		alert('Data invalida.');
		obj.value = '';
		obj.focus();
		return false;
	}

	for(i=0;i<data.length;i++)
	{
		if (i <= 1)
			dia = dia + data.charAt(i);
		if ((i >= 2) && (i <= 3))
			mes = mes + data.charAt(i);
		if (i >= 4)
			ano = ano + data.charAt(i);
	}
	
	if ((dia == '00') || (dia > 31))
	{
		alert('Dia invalido.');
		obj.focus();
		return false;
	}
	if ((mes == '00') || (mes > 12))
	{
		alert('Mes invalido.');
		obj.focus();
		return false;
	}
	if ((ano == '0000') || (ano >= 3000) || (ano < 1900))
	{
		alert('Ano Invalido.');
		obj.focus();
		return false;
	}

	obj.value = dia + '/' + mes + '/' + ano;
}



//====================================
//Funções de pagina botão direito do mouse
//====================================
//Botão direito do mouse
//function clickIE() {
//if (document.all) {
//return false;
//}
//} 
//function clickNS(e) {
//if (document.layers||(document.getElementById&&!document.all)) { 
//if (e.which==2||e.which==3) {
//return false;
//}
//}
//} 
//if (document.layers) {
//document.captureEvents(Event.MOUSEDOWN);
//document.onmousedown=clickNS;
//} 
//else{
//document.onmouseup=clickNS;
//document.oncontextmenu=clickIE;
//} 
//document.oncontextmenu=new Function("return false") 


//===================================
//Fim das funções de pagina
//===================================

/*
'[================================================================================================
'[= Nome		: Modulo10 para cmc7 de cheque
'[=
'[= Descrição		: Descobri o digito do modulo10
'[= Entrada		: string 
'[= Saida		: digito
'[= EXEMPLO		:
'[=var strdv1,strdv2,strdv3
'[=strdv1=Modulo10('2370200') //23702007 acha o dv1=4 do campo3
'[=strdv2=Modulo10('0005235') //0180005235 acha o dv2=7 do campo1
'[=strdv3=Modulo10('7750772550') //477507725503 acha o dv3= do campo3
'[================================================================================================
*/

function Modulo10(strCampo){
	var i
	var sTam 
	var vTot 
	var vPrima, vResult, vResto, vDigito, vInicio, vSegundo, vDigito2
	sTam = strCampo.length;
	vInicio = sTam;
	vPrima = 2;
	vTot = 0;
	for(i=1;sTam>=i;i++){
		//Primeira vez
		if(vPrima == 2){
			vResult = eval("'" + vPrima * strCampo.substring(vInicio-1, vInicio) + "'");
			if(vResult.length > 1){
				vResult = eval(parseInt(vResult.substring(0, 1)) + parseInt(vResult.substring(1, 2)));
			}
			vPrima = 1;
		}else{//Segunda vez 
			if(vPrima == 1){
				vResult = eval("'" + vPrima * strCampo.substring(vInicio-1, vInicio) + "'");
				if(vResult.length > 1){
					vResult = eval(parseInt(vResult.substring(0, 1)) + parseInt(vResult.substring(1,2)));
				}
				vPrima = 2;
			}
		}
		vTot = eval(parseInt(vTot) + parseInt(vResult));
		vInicio = vInicio - 1;
	}
	vTot = ("'" + vTot / 10 + "'");
	//ate aqui OK
	if(vTot.length > 1){
		vResto = vTot.substring(vTot.length-1,vTot.length-2);
	}else{
		vResto = 0;
	}
	if(vResto == 0){
		vDigito = 0;
	}else{
		vDigito = 10 - vResto;
	}
	return vDigito;
}