//+---------------------------------------------------------------------------.
//  Function:       isEmpty(s)																								|
//  Description:    Check whether string s is empty.													|
//  Arguments:      s = document.forms[0].elemment														|
//  Returns:        true/false																								|
//----------------------------------------------------------------------------'

function isEmpty(s){
	return ((s == null) || (s.length == 0))
}


//+-----------------------------------------------------------------------------------.
//  Function:       isWhitespace (s)																									|
//  Description:    Returns true if string s is empty or whitespace characters only.	|
//  Arguments:      s = document.forms[0].elemment																		|
//  Returns:        true/false																												|
//------------------------------------------------------------------------------------'

var whitespace = " \t\n\r";

function isWhitespace (s) {
		var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

//################################################################################//
//  Function:     isChecked()																											//
//--------------------------------------------------------------------------------//
//  Description:  Retorna true ou false se o objeto passado está checado					//
//################################################################################//
function isChecked(objCheck){
	
	if(objCheck == null)
		return false;
	
	if(objCheck.length == undefined){
		if(objCheck.checked)
			return true;
	}else{
		for(indx=0;indx<objCheck.length;indx++){
			if(objCheck[indx].checked)
				return true;
		}
	}
	return false;	
}

//##################################################################//
//										RadioSel(RadioButton)													//
//	PARAMETROS																											//
//		RadioButton: Obejto que	será buscado													//
//	DESCRIÇÃO																												//
//		Retorna o value do radio button que estiver checado						//
//##################################################################//
function RadioSel(objeRadio){
	var varcRadValue;
	if(objeRadio == null)
		return false
	inteLen	=	objeRadio.length
	if(inteLen == null)
		varcRadValue = objeRadio.value
	else
		for(Indx = 0;Indx < inteLen;Indx++)
			if(objeRadio[Indx].checked)
				varcRadValue =	objeRadio[Indx].value	
		
	return varcRadValue
}

//+---------------------------------------------------------------------------.
//  Function:       fctOnlyNumbers()																					|
//  Description:    Permite somente números (0-9).														|
//  Arguments:      nothing																										|
//  Returns:        nothing																										|
//----------------------------------------------------------------------------'
function fctOnlyNumbers(e) {

	if (!e) var e = window.event;
	
	if (e.keyCode){
		code = e.keyCode;
	}else if(e.which){
		code = e.which;
	}
	if((code > 47 && code < 58)|| code == 8 || code == 9 ||(code == 37 && !e.shiftKey) || code == 39){
		return true;
	}else{
		return false;
	}
}



//####################################################################################################//
//  Function:     fctVerificaMoney[( [intEscQtde] [,intPreQtde] [,strEscPt] [,strPrePt] )]            //
//----------------------------------------------------------------------------------------------------//
//  Description:                                                                                      //
//    * Permite somente números (0 à 9).                                                              //
//    * A soma da (Precisão) com a (Escala) não pode ser maior que 16.                                //
//    * Del => O valor do campo vai a zero.                                                           //
//    * BackSpace => remove um digito do valor do campo, da extrema direita.                          //
//----------------------------------------------------------------------------------------------------//
//  Eventos: [OnKeyDown]                                                                              //
//----------------------------------------------------------------------------------------------------//
//  Arguments:                                                                                        //
//    intEscQtde  = (Escala)   Quantidade de casas a esquerda do separador decimal.                   //
//    intPreQtde  = (Precisão) Quantidade de casas a direita do separador decimal.                    //
//    strEscPt    = Separador das casas a esquerda do ponto decimal.                                  //
//    strPrePt    = Separador decimal.                                                                //
//----------------------------------------------------------------------------------------------------//
//  Returns:      nothing                                                                             //
//####################################################################################################//
function fctVerificaMoney()
	{
	var intKCode		= (event.keyCode>=96 && event.keyCode<=105) ? (event.keyCode-48) : event.keyCode;
	var intKChar		= String.fromCharCode(intKCode);
	if( intKCode==9 )
		return;
	event.returnValue	= false;
	var objAtivo		= event.srcElement;
	var intEscQtde	= arguments[0];
	var intPreQtde	= arguments[1];
	var strEscPt		= arguments[2];
	var strPrePt		= arguments[3];
	var Valor				= objAtivo.value.toString();
	var tmpValor		= '';
	objAtivo.style.textAlign	= 'right';

	if( intKCode!=8 && intKCode!=46 && (isNaN(intKChar) || intKCode==13 || intKCode==32 ) )
		return;
	if( intPreQtde=='' || isNaN(intPreQtde) || parseInt(intPreQtde,10)<0 )
		intPreQtde		= 0;
	if( intPreQtde==0 )
		strPrePt			= '';
	if( isNaN(intEscQtde) || intEscQtde<0 )
		intEscQtde		= objAtivo.maxLength - intPreQtde;
	if( strPrePt==strEscPt && strPrePt!='' )
		strEscPt			= '';
	if( (intEscQtde+intPreQtde) > 16 )
		{
		alert('A função não aceita mais que 16 digitos')
		return;
		}

	if( Valor=='' || intKCode==46 )
		Valor					= 0;
	else
		{
		if( strEscPt!='' )
			while( Valor.indexOf(strEscPt)!=-1 )
				Valor			= Valor.replace(strEscPt, '');
		if( strPrePt!='' && strPrePt!='.' )
			Valor				= Valor.replace(strPrePt, '.');
		}

	if( intPreQtde!=0 && Valor!=0 )
		Valor					= (Math.round(Valor*Math.pow(10,intPreQtde))).toString();
	else
		Valor					= (parseFloat(Valor)).toString();
	if( (intEscQtde+intPreQtde)<Valor.length+1 && intKCode!=8 )
		return;

	if( intKCode==8 && Valor!=0 )
		{
		Valor					= Valor.substr(0, Valor.length-1);
		Valor					= (Valor==0) ? '0' : Valor;
		}
	else if( intKCode!=8 && intKCode!=46 )
		Valor					= (parseInt(Valor +''+ intKChar,10)).toString();

	if( intPreQtde!=0 )
		{
		tmpValor			= Valor.substr(Valor.length-intPreQtde, Valor.length);
		Valor					= (Valor*Math.pow(10,intPreQtde*-1)).toString();
		if( Valor.indexOf('.')!=-1 && Valor.indexOf('.')!=0 )
			Valor				= Valor.substr(0, Valor.indexOf('.')+intPreQtde+1);
		else if( Valor!=0 )
			Valor				= Valor +'.'+ tmpValor;
		else
			Valor				= Valor +'.';
		}

	Valor						= Valor.toString();
	tmpValor				= (Valor.substr(Valor.indexOf('.')+1, Valor.length)).length;
	if( tmpValor < intPreQtde && Valor==0 )
		Valor					= Valor + (Math.pow(10,intPreQtde)).toString().substr(1,intPreQtde);
	else if( tmpValor < intPreQtde )
		Valor					= Valor + (Math.pow(10,intPreQtde-tmpValor)).toString().substr(1,intPreQtde);

	if( strPrePt!='' && strPrePt!='.' )
		Valor					= Valor.replace('.', strPrePt);
	if( strEscPt!='' )
		{
		tmpValor			= Valor.indexOf(strPrePt);
		tmpValor			= (tmpValor==0) ? (Valor.length-3) : (tmpValor-3);
		while( tmpValor>0 )
			{
			Valor				= Valor.substr(0,tmpValor) + strEscPt + Valor.substr(tmpValor,Valor.length);
			tmpValor		-= 3;
			}
		}

	objAtivo.value		= Valor;
	}
	
	
//+---------------------------------------------------------------------------.
//  Function:       InputTextAnterior(i, c)																		|
//  Description:    Retorna índice do input-text anterior na coleção c.				|
//  Arguments:      i e c																											|
//  Returns:        nothing																										|
//----------------------------------------------------------------------------'

function InputTextAnterior(i, c) {
	var j;

	for (j = i - 1; j >= 0; j--) {
		if ( (c.item(j).type == 'text') ||
			(c.item(j).type == 'password') ) {
			return(j);
		}
	}

	return(i);
}

//+---------------------------------------------------------------------------.
//  Function:       ProximoInputText(i, c)																		|
//  Description:    Retorna índice do próximo input-text na coleção c.				|
//  Arguments:      i e c																											|
//  Returns:        nothing																										|
//----------------------------------------------------------------------------'

function ProximoInputText(i, c) {
	var j;

	for (j = i + 1; j <= c.length - 1; j++) {
		if ( (c.item(j).type == 'text') ||
			(c.item(j).type == 'password') ) {
			return(j);
		}
	}

	return(i);
}


//+---------------------------------------------------------------------------.
//  Function:       fctAutoTab()																							|
//  Description:    Pula para o próximo campo automaticamente.								|
//  Arguments:      nothing																										|
//  Returns:        nothing																										|
//----------------------------------------------------------------------------'

function fctAutoTab() {
	if(window.event){
		var el = event.srcElement;
		var coll = document.all.tags("input");
		var i = 0, j;
		var kc = event.keyCode;

		switch (kc) {
		//case  8:  //backspace
		//case 46:  //delete
		//	return;
		case 38:  //seta para cima
			while (el != coll.item(i)) i++;  // Descobre em que elemento estamos na coleção de TAGS INPUT
			j = InputTextAnterior(i, coll);  // Pega índice do input-text anterior
			if (j != i) {
				// Coloca o foco no elemento anterior:
				coll.item(j).select();
				coll.item(j).focus();
			}
			return;
		case 40:  //seta para baixo
			while (el != coll.item(i)) i++;  // Descobre em que elemento estamos na coleção de TAGS INPUT
			j = ProximoInputText(i, coll);  // Pega índice do próximo input-text
			if (j != i) {
				// Coloca o foco no próximo elemento:
				coll.item(j).select();
				coll.item(j).focus();
			}
			return;
		}

		if ( (kc >= 48 && kc <= 57) ||  //'0' a '9'
				(kc >= 96 && kc <= 105) ||  //'0' a '9' no teclado numérico
				(kc >= 65 && kc <= 90) ) {  // A-Z
 			if (el.value.length == el.maxLength) {
				while (el != coll.item(i)) i++;  // Descobre em que elemento estamos na coleção de TAGS INPUT
				j = ProximoInputText(i, coll);  // Pega índice do próximo input-text
				if (j != i) {
					// Coloca o foco no próximo elemento:
					coll.item(j).select();
					coll.item(j).focus();
				}
			}
		}
		return;
	}
}//AutoTab


//#############################################################
//####    Verifica  formatação do campo como aaa@bbb.cc    ####
//####         Retorna true se for um E-Mail valido        ####
//####        Retorna false nao for um E-Mail valido       ####
//#############################################################
function IsValidEmail( Value )
{
	var i, Current, Tmp
	var Array = Value.split( '@' , 3 );

	// Se tiver mais ou menos que 1 Arroba ou nao tiver nada antes ou apos o Arroba
	if( Array.length != 2 || Array[0] == '' || Array[1] == '' )
		return false;

	Tmp = Array[0];
	// Se contiver caracteres especiais antes do Arroba
	for(i=0; i < Tmp.length ;i++)
		{
		Current =  Tmp.charAt(i);
		if( (Current < '0' || Current > '9') && (Current < 'A' || Current > 'Z') && (Current < 'a' || Current > 'z') && Current != '_' && Current != '-' && Current != '.' )
			return false;
		}

	Tmp = Array[1];
	// Se contiver caracteres especiais depois do Arroba
	for(i=0; i < Tmp.length ;i++)
		{
		Current =  Tmp.charAt(i);
		if( (Current < '0' || Current > '9') && (Current < 'A' || Current > 'Z') && (Current < 'a' || Current > 'z') && Current != '.' )
			return false;
		}

	Tmp = Tmp.split( '.' , 4 );
	// Se depois do arroba existir menos de 2 ou mais de 3 pontos
	if( Tmp.length != 2 && Tmp.length != 3 )
		return false;

	// Se depois do arroba existir menos de 2 ou mais de 3 pontos
	if( Tmp.length == 2 && (Tmp[0] == '' || Tmp[1] == '') )
		return false;

	// Se depois do arroba existir menos de 2 ou mais de 3 pontos
	if( Tmp.length == 3 && (Tmp[0] == '' || Tmp[1] == '' || Tmp[2] == '') )
		return false;

	return true
	}

//####################################################
//####    Verifica se o RG informado é Valido     ####
//####      Recebe o RG e o DIGITO                ####
//####      Retorna true se for Valido            ####
//####      Retorna false se nao for Valido       ####
//####################################################
function IsValidRG( RG, DIGITO )
	{
	if( RG.toString().length < 4 || isNaN(RG) )
		return false;
	if( DIGITO != '' && DIGITO.toString().length != 1 )
		return false;
	if( DIGITO != '' && isNaN(DIGITO) && DIGITO.toLowerCase() != 'x' )
		return false;
	return true;
	}

//####################################################
//####    Verifica se o CPF informado é Valido    ####
//####      Recebe o CPF e o Controle do CPF      ####
//####      Retorna true se for Valido            ####
//####      Retorna false se nao for Valido       ####
//####################################################
function IsValidCPF( CPF, CONTROLE )
	{
	var Indx
	var Soma, Result, Pos
	var DigCPF, Dig1, Dig2

//	Verifica se o CPF esta no tamanho certo
	if( CPF.length != 9 )
		return false
//	Verifica se o Controle do CPF esta no tamanho certo
	if( CONTROLE.length != 2 )
		return false

//	Calcula o Primeiro Digito do CPF
	Soma = 0
	for(Indx=0, Pos = 10; Indx<9 ;Indx++, Pos--)
		{
		DigCPF = CPF.substr(Indx,1);
		Result = DigCPF * Pos
		Soma = Soma + Result
		}
	Dig1 = Soma % 11;
	if (Dig1 < 2)
		Dig1 = 0;
	else
		Dig1 = 11 - Dig1;

//	Verifica se o Primeiro Digito Informado é Valido
	if( Dig1 != CONTROLE.substr(0,1) )
		return false

//	Calcula o Segundo Digito do CPF
	Soma = 0
	for(Indx=0, Pos = 11; Indx<9 ;Indx++, Pos--)
		{
		DigCPF = CPF.substr(Indx,1);
		Result = DigCPF * Pos
		Soma = Soma + Result
		}
	Soma = Soma + (Dig1 * 2)
	Dig2 = Soma % 11;
	if (Dig2 < 2)
		Dig2 = 0;
	else
		Dig2 = 11 - Dig2;

//	Verifica se o Segundo Digito Informado é Valido
	if( Dig2 != CONTROLE.substr(1,1) )
		return false
	else
		return true
	}

//========================================================================================
//####################################  IsValidCNPJ  #####################################
//========================================================================================
function IsValidCNPJ( CNPJ , CTRL )
	{
	var I, SOMA, POS, TMP;
	var VETOR = new Array(13);

	if( CNPJ.length != 12 )
		return false;
	if( CTRL.length != 2 )
		return false;

	POS  = 5;
	SOMA = 0;
	for(I=0; I<=11; I++)
		{
		VETOR[I] = CNPJ.substr( I, 1);
		SOMA = SOMA + (VETOR[I] * POS)
		if( POS==2 )
			POS = 10;
		POS--;
		}
	VETOR[12] = SOMA % 11;
	if( VETOR[12] < 2 )
		VETOR[12] = 0;
	else
		VETOR[12] = 11 - VETOR[12];

	POS  = 6;
	SOMA = 0;
	for(I=0; I<=12; I++)
		{
		SOMA = SOMA + (VETOR[I] * POS)
		if( POS==2 )
			POS = 10;
		POS--;
		}
	VETOR[13] = SOMA % 11;
	if( VETOR[13] < 2 )
		VETOR[13] = 0;
	else
		VETOR[13] = 11 - VETOR[13];

	POS = VETOR[12] * 10 + VETOR[13];
	if( POS!=CTRL )
		return false;
	else
		return true;
	}
	
//###################################################
//####    Contador de Caracteres Digitados    #######
//###################################################
function textCounter(field, countfield, maxlimit)
	{
	if( field.value.length > maxlimit )
		field.value = field.value.substring(0, maxlimit);
	else if( countfield != '' )
		countfield.value = maxlimit - field.value.length;
	}