//*************************************************************
//
// Função desenvolvida por Adriano de Sousa Rocha
// arochax@hotmail.com
//
// Descricao: Valida a digitação de um número em um INPUT
//            formatando-o com ou sem decimais
//
// Exemplo de utilização: (99999,99)
//
// <INPUT onkeypress="return FormatarNumero(this, 7, 2);">
//
//*************************************************************

var _bTextoInputSelecionado = 1;
var _bInicializadoFormatarNumero = 0;

function FormatarNumero(Campo, Tamanho, Decimais) {
	var strValor = Campo.value;
	var strValorFmt = new String();
	var strSinal = '';
	var intCont;
	var reLimparNumero = new RegExp("\\D", "g"); // \\D = Localiza <> 0-9
	                                             //   g = pesquisa global

	if (strValor.indexOf("-") > -1) {
		strSinal = "-";
	}

	//Limpa número deixando apenas os dígitos, sem zeros à esquerda
	strValor = String(Number(strValor.replace(reLimparNumero, "")));

    //Se evento for onblur
    if (event.keyCode == 0) {
        if (strValor == "0") {
            Campo.value = "";
            return false;
        }
    }
    else {
		// se digitado sinal de -
		if (event.keyCode == 45) {
	        if (_bTextoInputSelecionado == 1) {
	            strValor = "0";
	            _bTextoInputSelecionado = 0;
	        }
			strSinal = '-';
		}
		else {
			//valida o tamanho máximo
			if ((strValor.length == Tamanho) && (_bTextoInputSelecionado == 0)) {
		    	return false;
		    }

		    //Permite a digitação de apenas números
		    if (!(event.keyCode >= 48 && event.keyCode <= 57)) {
		    	return false;
		    }

	        if (strValor == "0") {
	            strValor = "";
	        }

            if (_bTextoInputSelecionado == 1) {
	            strValor = "";
            	strSinal = "";
            	_bTextoInputSelecionado = 0;
            }
	        
        	//Adiciona o número digitado
        	strValor += String.fromCharCode(event.keyCode);
        }
       	event.keyCode = 0;
    }

    // Se Constantes não foram definidas usa o padrao
    if (typeof(cSepDecimal) == 'undefined') {
    	cSepDecimal = ",";
    }

    if ((strValor.length < Decimais + 1) && (Decimais > 0)) {
        //preenche com 0 à esquerda
        for (intCont = strValor.length; intCont < Decimais + 1; intCont++) {
            strValor = "0" + strValor;
        }
    }

    //Formata o Valor do campo com Separador de Decimal
    for (intCont = strValor.length; intCont >= 0; intCont--) {
        if ((strValorFmt.length == Decimais) && (Decimais > 0)) {
            strValorFmt = cSepDecimal + strValorFmt;
        }
        strValorFmt = strValor.charAt(intCont) + strValorFmt;
	}
	Campo.value = strSinal + strValorFmt;
	
	if (_bInicializadoFormatarNumero == 0) {
		_bInicializadoFormatarNumero = 1;
		
		for (iCont = 0; iCont < Campo.form.elements.length; iCont++) {
			if (Campo.form.elements[iCont].onkeypress != undefined) {
				sEvento = Campo.form.elements[iCont].onkeypress.toString();
				if (sEvento.indexOf("FormatarNumero") > -1) {
					//Atribui o mesmo evento para formatação ao sair do campo
					if (Campo.form.elements[iCont].onblur == null) 
						Campo.form.elements[iCont].onblur = Campo.onkeypress;
						
					//Atribui uma função ao OnSelect e OnKeyDown
					Campo.form.elements[iCont].onselect = _OnSelect;
					Campo.form.elements[iCont].onkeydown = _OnKeyDown;
				}
			}
		}
	}
}

function _OnSelect() {
	_bTextoInputSelecionado = 1;
}

function _OnKeyDown() {
	//Se pressionadas as setas...
	if (event.keyCode >= 37 && event.keyCode <= 40) {
		_bTextoInputSelecionado = 0;
	}
}