var sele;

function maskNumberS ()
{
    sele = true;
}

function maskNumber(obj, casas)
{
    var valor;
    var acao = 0;
    valor = obj.value;
    if (sele == true)
        valor = '';

    if ((((event.keyCode >= 96) && (event.keyCode <= 105)) || ((event.keyCode >= 48) && (event.keyCode <= 57))) && (valor.length<19))  {
        if (event.keyCode < 96)
           valor = valor + String(event.keyCode - 48);  else
           valor = valor + String(event.keyCode - 96);

        obj.value = formata(valor, casas);
        acao = 1;
    }


    if (event.keyCode == 8)   {
        valor = valor.substr(0, valor.length - 1);
        obj.value = formata(valor, casas);
        acao = 2;
    }
    if ((event.keyCode == 9) || (event.keyCode == 46))   acao = 3;

    if (((event.keyCode==109) || (event.keyCode==189)) && (acao==0))  {
       if (valor.indexOf('-') < 0)
         valor = '-'+valor;  else
         valor = valor.substring(1,valor.length)
       obj.value = formata(valor, casas);
       acao = 1;
    }

    if (acao < 3)     event.keyCode = 35;
    sele = false;
}

function insere(original, novo, onde)
{
  return original.substring(0, onde) + novo + original.substring(onde, original.length);
}

function apaga(a, x)
{
  if (x==0)
    return a.substring(1); else
    return a.substr(0, x) + a.substring(x+1);
}

function formata(texto, casas)
{
  var menos=0;
  texto = String(texto);

  if (texto.indexOf('-') >= 0)  {
    texto = texto.substring(1,texto.length);
    menos = 1;
  }

  while (texto.indexOf('.') >= 0)
   texto = apaga(texto, texto.indexOf('.'));
  while (texto.indexOf(',') >= 0)
   texto = apaga(texto, texto.indexOf(','));

  while (texto.charAt(0) == '0')
    texto = texto.substring(1,texto.length);

  while (texto.length <  3) texto = '0'+texto;

  texto = insere(texto, '.', texto.length-2);
  while (texto.indexOf('.') > 3)
    texto = insere(texto, '.', texto.indexOf('.')-3);
  texto = texto.substring(0, texto.length-3) + ',' + texto.substring(texto.length-2, texto.length);

  if (menos>0)
    texto = '-'+texto;

  return(texto);
}
