/**
 * Adiciona método lpad() à classe String.
 * Preenche a String à esquerda com o caractere fornecido,
 * até que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch  = String(pCharPad).charAt(0);

	for (; dif > 0; dif--)    { str = ch + str; }

	return (str);
} //String.lpad


/**
 * Adiciona método trim() à classe String.
 * Elimina brancos no início e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, '').replace(/\s*$/, '');
} //String.trim


/**
 * Adiciona método search() à classe Array.
 * Procura por um valor em um array e retorna 
 * sua chave correspondente caso seja encontrado
 * e FALSE em caso contrário.
 */
Array.prototype.search = function(valor)
{
	var elemtArr = this;

	for (var i = 0; i < elemtArr.length; i++)
	{
		if (elemtArr[i] == valor) { return i; }
	}

	return false;
} //Array.search


/**
 * Função que abre uma janela parametrizada no centro da tela.
 * --------------------------------------------------------------
 * @PARÂMETROS
 * mypage -> Arquivo a ser aberto na janela.
 * myname -> Nome da janela.
 * largura -> Seta o atributo width da janela (valor em pixel)
 * altura -> Seta o atributo height da janela (valor em pixel)
 * local -> Seta o atributo location da janela
 * menu -> Seta o atributo menubar da janela
 * resize -> Seta o atributo resizable da janela
 * scroll -> Seta o atributo scrollbars da janela
 * stat -> Seta o atributo statusbar da janela
 * tool -> Seta o atributo toolbar da janela
 * --------------------------------------------------------------
 */
function PoupUp(mypage, myname, largura, altura, local, menu, resize, scroll, stat, tool)
{
	var winprops = '';

	var winl = (screen.width - largura) / 2;
	var wint = (screen.height - altura) / 2;

	winprops  = 'height=' + altura + ', width=' + largura + ', top=' + wint + ', left=' + winl + ', scrollbars=' + scroll;
	winprops +=  ', resizable=' + resize + ', location=' + local + ', menubar=' + menu + ', statusbar=' + stat + ', toolbar=' + tool;

	if(!window.werror)    { win = window.open(mypage, myname, winprops); }

	if (parseInt(navigator.appVersion) >= 4)    { win.window.focus(); }
}




/**
 * Funções da Button Bar
 */

// Flag que informa se as imagens de rollover já foram carregadas no cache.
var preloadFlag = false;


// Função para a troca de imagens da button bar da ferramenta.
function changeImages()
{
	if (document.images && (preloadFlag == true))
	{
		for(var i = 0; i < changeImages.arguments.length; i += 2)
		{
			document[changeImages.arguments[i]].src = changeImages.arguments[i + 1];
		}
	}
}


// Função que armazena imagem no cache.
function newImage(arg)
{
	if (document.images)
	{
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}





/**
 * Função que limita o número de caracteres possíveis a serem inputados em um campo textarea.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="text" name="counter" value="500" size="3" readonly>
 * <textarea cols="65" rows="5" name="OBS" onKeyDown="textCounter(this.form.OBS, this.form.counter, 500);" onKeyUp="textCounter(this.form.OBS, this.form.counter, 500);">
 * </textarea>
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> textarea a ser imposto um limite.
 * countElemt -> elemento text que apresentará a qtde. de caracteres restantes possíveis de serem inputados.
 * maxLimit -> qtde. máxima de caracteres possíveis a serem inseridos no textarea
 * -------------------------------------------------------------------------------------------------------------
 */
function textCounter(input, countElemt, maxLimit)
{
	if (input.value.length > maxLimit) // if too long...trim it!
		input.value = input.value.substring(0, maxLimit);
	else // otherwise, update 'characters left' counter
		countElemt.value = maxLimit - input.value.length;
}


// Função que seta o campo action de um formulário com um valor e depois submete o formulário.
function setActionSubmit(formName, urlDest)
{
	document.forms[formName].action = urlDest;
	document.forms[formName].submit();
}


// Função que move o foco do cursor para o primeiro elemento do primeiro formulário.
function putFocus(formInst, elementInst)
{
	if(formInst && elementInst)
	{
		if (document.forms.length > 0)	{ document.forms[formInst].elements[elementInst].focus(); }
	}
}


// Função utilizada para fechar uma janela do browser no tempo especificado.
function close_automatic(sec)
{
	var time = sec * 1000; // time in secs

	setTimeout("window.close();" , time);
}


// Função que marca e desmarca todos os itens de uma lista de checkbox.
var CheckAllFlag = false;

function CheckAll(formName)
{
	for (var i = 0; i < document.forms[formName].elements.length; i++)
	{
		if(document.forms[formName].elements[i].type == 'checkbox')
		{
			document.forms[formName].elements[i].checked = !(document.forms[formName].elements[i].checked);
		}
	}

	if (!CheckAllFlag)
	{
		CheckAllFlag = true;

		return 'DESMARCAR TODAS';
	}
	else
	{
		CheckAllFlag = false;

		return 'MARCAR TODAS';
	}
}


// Função para a passagem de foco quando o campo atingir a sua qtde. máxima de caracteres (maxlength).
function autoTab(input, e)
{
	var keyCode = (window.Event) ? e.which : e.keyCode;

	var keyFilter = [0, 8, 9, 16, 17, 18, 20, 35, 36, 37, 38, 39, 40];

	var elemtForm = input.form;
	var elemtNumb = elemtForm.length;
	var elemtMaxL = input.maxLength;

	if((elemtMaxL == 2147483647) || (elemtMaxL == -1))    { return true; } // atributo maxlength não foi definido no html.

	var elemtIndex = aux = getIndex();
	var elemtValue = input.value;

	if((elemtValue.length >= elemtMaxL) && (keyFilter.search(keyCode) === false))
	{
		elemtValue = elemtValue.slice(0, elemtMaxL);

		var nxtField = (elemtIndex < (elemtNumb - 1)) ? (elemtIndex + 1) : 0;

		while(elemtForm[nxtField].isDisabled || elemtForm[nxtField].readOnly || (elemtForm[nxtField].type == 'hidden'))
		{
			aux++;

			if(aux > (elemtNumb - 1))    { aux = 0; }

			nxtField = (aux < (elemtNumb - 1)) ? (aux + 1) : 0;
		}

		elemtForm[nxtField].focus();
	}

	function getIndex()
	{
		var elemtName = input.name;

		for(var i = 0; i < elemtNumb; i++)
		{
			if(elemtForm[i].name == elemtName)    { return i; }
		}

		return false;
	}

	return true;
}





/**
 * Funções de Auto Completition e Formatação
 * ------------------------------------------
 */

/**
 * Função que formata valores numéricos com o número de casas decimais especificada.
 * Filtra os carcteres não numéricos impedindo que os mesmos sejão inseridos no campo.
 * ---------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyPress'. 
 * ---------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="VALOR" size="25" maxlength="14" onKeyPress="return FormatDec(this, 2, event);">
 * ---------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * nDec -> número de casas decimais
 * e -> event
 */
function FormatDec(input, nDec, e)
{
	var milSep = '.';
	var decSep = ',';

	var strCheck = '0123456789';

	var key = aux = aux2 = '';
	var len2 = 0;

	var elemtVal = input.value;
	var elemtMax = input.maxLength;
	var elemtLen = elemtVal.length;

	var kCode = (window.Event) ? e.which : e.keyCode;

	if(kCode == 8 || kCode == 0)    { return true; } // press Backspace or (Home, End, Delete <-, -> ...)

	if(elemtLen >= elemtMax)    { return false; }  // input maxlength is exceed

	key = String.fromCharCode(kCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1)    { return false; }  // Not a valid key

	aux  = String(elemtVal).replace(/\D/g, '').replace(/^0+/, ''); // Elimina caracteres de formatação e zeros à esquerda da string
	aux += key;

	elemtLen = aux.length;

	if(elemtLen <= nDec)
	{
		for(; elemtLen < nDec; elemtLen++)    { aux = '0' + aux; }

		input.value = '0,' + aux;
	}
	else
	{
		for(var j = 0, i = elemtLen - (nDec + 1); i >= 0; i--)
		{
			if (j == 3)
			{
				aux2 += milSep;
				j = 0;
			}

			aux2 += aux.charAt(i);
			j++;
		}

		input.value = '';
		len2 = aux2.length;

		for (i = len2 - 1; i >= 0; i--)    { input.value += aux2.charAt(i); }

		input.value += decSep + aux.substr(elemtLen - nDec, elemtLen);
	}

	return false;
}


/**
 * Função que restringe a entrada de um campo a apenas valores numéricos.
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyPress'. 
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="NUMERO" size="25" maxlength="10" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * e -> event
 * -------------------------------------------------------------------------------------------------------------
 */
function CompleteNumeric(input, e)
{
	kCode = (window.Event) ? e.which : e.keyCode;

	if(kCode == 8 || kCode == 0)    { return true; } // pressionando o Backspace ou (Home, End, Delete <-, -> ...)

	return ((kCode < 48 || kCode > 57) ? false : true);
}


/**
 * Função que completa automaticamente os marcadores de um telefone. (NN) NNNN-NNNN
 * No momento em que o usuário preenche os números os marcadores são adicionados ao seu valor
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyUp'. É obrigatório o uso da 
 * função 'CompleteNumeric' na tag html de evento 'onKeyPress' para que os valores inputados pelo usuário 
 * sejam apenas numéricos. O atributo 'maxlength' do campo deve ser 14.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="FONE" size="25" maxlength="14" onKeyUp="CompletePhone(this);" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * -------------------------------------------------------------------------------------------------------------
 */
function CompletePhone(input)
{
	var phone = input.value;

	if(arguments.length != 2)
	{
		if(phone.length == 1)         { input.value = '(' + input.value; }
		else if(phone.length == 3)    { input.value += ') '; }
		else if(phone.length == 9)    { input.value += '-'; }
	}
	else
	{
		if(phone.length == 4)    { input.value += '-'; }
	}
}

/**
 * Função que completa automaticamente os marcadores de um CPF. NNN.NNN.NNN-NN
 * No momento em que o usuário preenche os números os marcadores são adicionados ao seu valor
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyUp'. É obrigatório o uso da 
 * função 'CompleteNumeric' na tag html de evento 'onKeyPress' para que os valores inputados pelo usuário 
 * sejam apenas numéricos. O atributo 'maxlength' do campo deve ser 14.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="CPF" size="25" maxlength="14" onKeyUp="CompleteCPF(this);" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * -------------------------------------------------------------------------------------------------------------
 */
function CompleteCPF(input)
{
	var cpf = input.value;

	if(cpf.length == 3 || cpf.length == 7)    { input.value += '.'; }
	if(cpf.length == 11)					  { input.value += '-'; }
}


/**
 * Função que completa automaticamente os marcadores de um CNPJ. NN.NNN.NNN/NNNN-NN
 * No momento em que o usuário preenche os números os marcadores são adicionados ao seu valor
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyUp'. É obrigatório o uso da 
 * função 'CompleteNumeric' na tag html de evento 'onKeyPress' para que os valores inputados pelo usuário 
 * sejam apenas numéricos. O atributo 'maxlength' do campo deve ser 18.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="CNPJ" size="25" maxlength="18" onKeyUp="CompleteCNPJ(this);" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * -------------------------------------------------------------------------------------------------------------
 */
function CompleteCNPJ(input)
{
	var cnpj = input.value;

	if(cnpj.length == 2 || cnpj.length == 6)	{ input.value += '.'; }
	if(cnpj.length == 10)					    { input.value += '/'; }
	if(cnpj.length == 15)					    { input.value += '-'; }
}


/**
 * Função que completa automaticamente os marcadores de um CEP. NNNNN-NNN
 * No momento em que o usuário preenche os números os marcadores são adicionados ao seu valor
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyUp'. É obrigatório o uso da 
 * função 'CompleteNumeric' na tag html de evento 'onKeyPress' para que os valores inputados pelo usuário 
 * sejam apenas numéricos. O atributo 'maxlength' do campo deve ser 9.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="CEP" size="25" maxlength="9" onKeyUp="CompleteCEP(this);" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * -------------------------------------------------------------------------------------------------------------
 */
function CompleteCEP(input)
{
	var cep = input.value;

	if(cep.length == 5)    { input.value += '-'; }
}


/**
 * Função que completa automaticamente os marcadores de uma data, hora e data-hora. 
 * (DD/MM/YYYY - HH:MI - HH:MI:SS - DD/MM/YYYY HH:MI - DD/MM/YYYY HH:MI:SS)
 * No momento em que o usuário preenche os números os marcadores são adicionados ao seu valor
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyUp'. É obrigatório o uso da 
 * função 'CompleteNumeric' na tag html de evento 'onKeyPress' para que os valores inputados pelo usuário 
 * sejam apenas numéricos. O atributo 'maxlength' do campo deve ser equivalente a qtde. de caracteres do padão acima escolhido.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="DT_NASCIMENTO" size="25" maxlength="10" onKeyUp="CompleteDate(this, 'DATE');" onKeyPress="return CompleteNumeric(this, event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * input -> elemento do formulário
 * e -> event
 * fType:
 * DATE - DD/MM/YYYY - 10
 * TIME - HH:MI - 5
 * TIMESEC - HH:MI:SS - 8
 * DATETIME - DD/MM/YYYY HH:MI - 16
 * DATETIMESEC - DD/MM/YYYY HH:MI:SS - 19
 * -------------------------------------------------------------------------------------------------------------
 */
function CompleteDate(input, fType)
{
	var data = input.value;

	if((fType == 'DATE') || (fType == 'DATETIME') || (fType == 'DATETIMESEC'))
	{
		if(data.length == 2 || data.length == 5)    { input.value += '/'; }

		if((fType == 'DATETIME') || (fType == 'DATETIMESEC'))
		{
			if(data.length == 10)    { input.value += ' '; }
			if(data.length == 13)    { input.value += ':'; }

			if(fType == 'DATETIMESEC')
			{
				if(data.length == 16)    { input.value += ':'; }
			}
		}
	}
	else
	{
		if(data.length == 2)    { input.value += ':'; }

		if(fType == 'TIMESEC')
		{
			if(data.length == 5)    { input.value += ':'; }
		}
	}
}





/*
+----------------------+
| Funções de Validação |
+----------------------+
*/

// Função que verifica se a string 'str' é um cpf válido.
function ValidaCPF(str)
{
	if(str)
	{
		var posicao = 10, soma = 0, dv, dvInform, cpf;
		var digito = new Array(10);

		cpf = String(str).replace(/\D/g, ''); // Remove da string 'str' todos os caracteres especiais

		if(isBlank(cpf))    { return false; } // Entrada não numérica.

		dvInform = cpf.substr(9, 2);

		for(var i = 0; i <= 8; i++)
		{
			digito[i] = cpf.charAt(i);

			soma += digito[i] * posicao;

			posicao--;
		}

		digito[9] = soma % 11;
		digito[9] = (digito[9] < 2) ? 0 : (11 - digito[9]);

		posicao = 11;
		soma = 0;

		for(i = 0; i <= 9; i++)
		{
			soma += digito[i] * posicao;
			posicao--;
		}

		digito[10] = soma % 11;
		digito[10] = (digito[10] < 2) ? 0 : (11 - digito[10]);

		dv = digito[9] * 10 + digito[10];

		return ((dv != dvInform) ? false : true);
	}

	return false;
}


// Função que verifica se a string 'str' é um cnpj válido.
function ValidaCNPJ(str)
{
	if(str)
	{
		var soma = 0, cnpj, aux2;
		var digito = new Array;
		var aux = [6,5,4,3,2,9,8,7,6,5,4,3,2];

		cnpj = String(str).replace(/\D/g, ''); // Remove da string 'str' todos os caracteres especiais

		if(isBlank(cnpj))    { return false; } // Entrada não numérica.

		for(var i = 0; i < 12; i++)
		{
			digito[i] = cnpj.charAt(i);
			soma += digito[i] * aux[i + 1];
		}

		digito[12] = ((aux2 = soma % 11) < 2) ? 0 : (11 - aux2);

		soma = 0;

		for(i = 0; i < 13; i++)
		{
			soma += (digito[i] * aux[i]);
		}

		digito[13] = ((aux2 = soma % 11) < 2) ? 0 : (11 - aux2);

		return (((cnpj.charAt(12) != digito[12]) || (cnpj.charAt(13) != digito[13])) ? false : true);
	}

	return false;
}


// Função que verifica se a string 'str' é um número inteiro não-negativo sem sinal, ou seja, apenas dígitos
function isDigit(str)
{
	var pattern = /^\d+$/;
	var result  = str.match(pattern);

	return ((result != null) ? true: false);
}


// Função que verifica se a string 'str' é um número real em ponto flutuante (decimal). Permite: sinal, separadores de milhar e casas decimais.
function isDecimal(str)
{
	var pattern = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
	var result  = str.match(pattern);

	return ((result != null) ? true: false);
}


// Função que verifica se a string 'str' é um valor monetário. Permite: separadores de milhar e casas decimais.
function isMoney(str)
{
	var pattern = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
	var result  = str.match(pattern);

	return ((result != null) ? true: false);
}


// A utility function that returns true if a string contains only 
// whitespace characters.
function isBlank(s)
{
	if((s != null) && (s != ''))
	{
		for(var i = 0; i < s.length; i++)
		{
		   var c = s.charAt(i);
	
		   if ((c != ' ') && (c != '\n') && (c != '\t'))    { return false; }
		}
	}

	return true;
}


// Função que verifica se a string 'str' é um endereço de e-mail (correio eletrônico) valido.
function isEmail(str)
{
	var pattern = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	var result  = str.match(pattern);

	return ((result != null) ? true: false);
}


// Função que verifica se a string 'str' é um telefone válido. Segue padrão definido pela função 'CompletePhone' - (NN) NNNN-NNNN
function isPhone(str)
{
	return true;
}


// Função que verifica se a string 'str' é um CEP válido. Segue padrão definido pela função 'CompleteCEP' - NNNNN-NNN
function isCEP(str)
{
	return true;
}


/**
 * Função que verifica se a string é uma data valida.
 * ------------------------------------------------------
 * @PARÂMETROS
 * str -> String contendo a data a ser validada
 * format:
 * DATE -> DD/MM/YYYY
 * DATETIME -> DD/MM/YYYY HH24:MI
 * DATETIMESEC -> DD/MM/YYYY HH24:MI:SS
 * TIME -> HH24:MI
 * TIMESEC -> HH24:MI:SS
 * ------------------------------------------------------
 */
function isDate(str, format)
{
	switch(format)
	{
		case 'DATE':
			var pattern = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
			break;

		case 'DATETIME':
			var pattern = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}\s([0-1]\d|2[0-3]):[0-5]\d$/;
			break;

		case 'DATETIMESEC':
			var pattern = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}\s([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/;
			break;

		case 'TIME':
			var pattern = /^([0-1]\d|2[0-3]):[0-5]\d$/;
			break;

		case 'TIMESEC':
			var pattern = /^([0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/;
			break;
	}

	var result  = str.match(pattern);

	return ((result != null) ? true: false);
}


/**
 * Função que restringe os tipos de arquivo para upload de um campo do tipo 'file'. 
 * Retorna TRUE caso o arquivo esteja dentre os de extensão permitida. Caso contrário retornará FALSE;
 * ----------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * file -> elemento do tipo 'file'
 * arrExt -> array contendo as extensões permitidas
 * ----------------------------------------------------------------------------------------------------
 */
function FilterAttach(file, arrExt)
{
	var elemtExt = '', fileName = '';

	if(file)
	{
		fileName = file.slice(file.lastIndexOf('\\') + 1);
		elemtExt = fileName.slice(fileName.lastIndexOf('.')).toLowerCase();

		return ((arrExt.search(elemtExt) !== false) ? true : false);
	}

	return false;
}


/**
 * Função que abre uma janela de alert com um warning caso o usuário esteja com o CAPS Lock ligado.
 * -------------------------------------------------------------------------------------------------------------
 * @INSTRUÇÕES
 * Esta função deve ser utilizada na tag html de evento 'onKeyPress'. 
 * Ela é muito utilizado em formulários de login, onde geralmente o nome do usuário é case sensitive.
 * -------------------------------------------------------------------------------------------------------------
 * @EXEMPLO
 * <input type="Text" name="USUARIO" size="25" maxlength="20" onKeyPress="checkCapsLock(event);">
 * -------------------------------------------------------------------------------------------------------------
 * @PARÂMETROS
 * e -> event
 * -------------------------------------------------------------------------------------------------------------
 */
function checkCapsLock(e)
{
	var msgWarning = '', myKeyCode, myShiftKey = false;

	msgWarning  = 'Caps Lock está ativada!\n\n';
	msgWarning += 'Se Caps Lock estiver ativado, isso pode fazer com que você digite a senha incorretamente.\n\n';
	msgWarning += 'Você deve pressionar a tecla Caps Lock para desativá-la antes de digitar a senha.';

	if(window.Event)
	{
		myKeyCode = e.which;

		if(myKeyCode == 16)    { myShiftKey = true; }
	}
	else
	{
		myKeyCode  = e.keyCode;
		myShiftKey = e.shiftKey;
	}

	// 1. Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	// 2. Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on (only in IE)
	if (((myKeyCode >= 65 && myKeyCode <= 90) && !myShiftKey) || ((myKeyCode >= 97 && myKeyCode <= 122) && myShiftKey)) 
	{
		alert( msgWarning );
	}
}