/*
Descrição.: formata um campo do formulário de
acordo com a máscara informada...
Parâmetros: - objForm (o Objeto Form)
- strField (string contendo o nome do textbox)

* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

function txtBoxFormat(objForm, strField, sMask, evtKeyPress) {
var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

if(document.all) { // Internet Explorer
    nTecla = evtKeyPress.keyCode;
} else if(document.layers) { // Nestcape
    nTecla = evtKeyPress.which;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

sValue = objForm[strField].value;
// Limpa todos os caracteres de formatação que
// já estiverem no campo.
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( "-", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( ".", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "/", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( "(", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( ")", "" );
sValue = sValue.toString().replace( " ", "" );
sValue = sValue.toString().replace( " ", "" );
fldLen = sValue.length;
mskLen = sMask.length;

i = 0;
nCount = 0;
sCod = "";
mskLen = fldLen;

while (i <= mskLen) {
bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ":") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

if (bolMask) {
    sCod += sMask.charAt(i);
    mskLen++;
} else {
    sCod += sValue.charAt(nCount);
    nCount++;
}
i++;
}

objForm[strField].value = sCod;
if (nTecla != 8) { // backspace
    if (sMask.charAt(i-1) == "9") { // apenas números...
    return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
else { // qualquer caracter...
    return true;
}
} else {
    return true;
}
}

//Fim da Função Máscaras Gerais

/***
* AUTO TAB - ao prencher o campo, automaticamente manda o foco para o próximo!
***/
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
    var keyCode = (isNN) ? e.which : e.keyCode;
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

function containsElement(arr, ele) {
    var found = false, index = 0;
    while(!found && index < arr.length)
    if(arr[index] == ele)
        found = true;
    else
        index++;
        return found;
    }

function getIndex(input) {
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
        return index;
    }
    return true;
}
//Fim da Função AutoTab


function Verifica_Data(data, obrigatorio){
 //Se o parâmetro obrigatório for igual à zero, significa que elepode estar vazio, caso contrário, não

 	var strdata = data;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
 			alert("Formato da data não é válido. Formato correto: dd/mm/aaaa.");
 			return false
 		}
 		//Verifica máscara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
 			alert("Formato da data não é válido. Formato correto: dd/mm/aaaa.");
 			return false
 		}
 		var dia = strdata.substr(0,2);
 		var mes = strdata.substr(3,2);
 		var ano = strdata.substr(6,4);
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Formato do dia não é válido.");
 			return false
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mês informado não possui 31 dias.");
 				return false
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mês informado possui somente 29 dias.");
 					return false
 				}
 			}else{
 				if (dia > 28){
 					alert("O mês informado possui somente 28 dias.");
 					return false
 				}
 			}
 		}
 	//Verifica o mês
 		if (isNaN(mes) || mes > 12 || mes < 1){
 			alert("Formato do mês não é válido.");
 			return false
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Formato do ano não é válido.");
 			return false
 		}
				
 	}
 }


/*
* função para permitir a digitação de números decimais e inteiros

** Para permitir a digitação de números inteiros de decimais positivos ou negativos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric" value=""
    onkeydown="ForceNumericInput(event, this, true, true)" />
	
** Para permitir a digitação de inteiros positivos ou negativos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, true)" />
	
** Para permitir a digitação de inteiros e decimais positivos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, true, false)" />

** Para permitir a digitação de somente inteiros positivos
<input type="text" name="TextBoxNumeric" id="TextBoxNumeric"
    value="" onkeydown="ForceNumericInput(event, this, false, false)" />
*/



/*
function ForceNumericInput(event, This, AllowDecimal, AllowMinus)
{
if(arguments.length == 1)
{
var s = This.value;
// garante que o sinal de "-" seja o primeiro do índice
var i = s.lastIndexOf("-");
if(i == -1)
return;
if(i != 0)
This.value = s.substring(0,i)+s.substring(i+1);
return;
}
switch(event.keyCode)
{
case 8:     // backspace
case 9:     // tab
case 37:    // left arrow
case 39:    // right arrow
case 46:    // delete
event.returnValue = true;
return;
}
if(event.keyCode == 189)     // sinal de número de negativo
{
if(AllowMinus == false)
{
CancelEventExecution(event);
return;
}
// aguarda até que o controle tenha sido atualizado
var s = "ForceNumericInput(document.getElementById('"+This.id+"'))";
setTimeout(s, 250);
return;
}
if(AllowDecimal &amp;&amp; event.keyCode == 188)
{
if(This.value.indexOf(",") &gt;= 0)
{
// restringe a digitação de apenas uma vírgula
CancelEventExecution(event);
return;
}
event.returnValue = true;
return;
}
// permite caracteres entre 0 e 9
if(event.keyCode &gt;= 48 &amp;&amp; event.keyCode &lt;= 57)
{
event.returnValue = true;
return;
}
CancelEventExecution(event);
}
/*
* Cancela a execução de uma function mapeada por um evento
*/
function CancelEventExecution(event)
{
if (navigator.appName == "Netscape")
{
event.preventDefault();
}
else
{
event.returnValue = false;
}
}
