/**
 * Função...: txtBoxFormat(campo, sMask, evtKeyPress)
 * Descrição: formata um campo do formulário de acordo com uma máscara informada
 * Uso......:
 *  <input type="textbox" name="xxx" onkeypress="return txtBoxFormat(this, '99999-999', event);">
 * Observação: As máscaras podem ser representadas como nos 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)
 **/
function txtBoxFormat(campo, 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 if(document.getElementById) { // FireFox
    nTecla = evtKeyPress.which;
  }
  sValue = limpar(campo.value,'0123456789');
  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) == "/"))
    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++;
  }
  campo.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
    return true;
  }
  return true;
}

/**
 * Função....: printPage()
 * Descrição.: Envia a página corrente para a impressão
 * Uso.......: onClick="printPage()"
 */
var da = (document.all) ? 1 : 0;
var pr = (window.print) ? 1 : 0;
var mac = (navigator.userAgent.indexOf("Mac") != -1);

function printPage() {
  if (pr) // NS4, IE5
    window.print()
  else if (da && !mac) // IE4 (Windows)
    vbPrintPage()
  else // other browsers
    alert("Desculpe seu browser nao suporta esta funcao. Por favor utilize " +
      "a barra de trabalho para imprimir a p�gina.");
  return false;
  if (da && !pr && !mac) with (document) {
    writeln('<OBJECT ID="WB" WIDTH="0" HEIGHT="0" CLASSID="clsid:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>');
    writeln('<SCRIPT LANGUAGE="VBScript">');
    writeln('Sub window_onunload');
    writeln('  On Error Resume Next');
    writeln('  Set WB = nothing');
    writeln('End Sub');
    writeln('Sub vbPrintPage');
    writeln('  OLECMDID_PRINT = 6');
    writeln('  OLECMDEXECOPT_DONTPROMPTUSER = 2');
    writeln('  OLECMDEXECOPT_PROMPTUSER = 1');
    writeln('  On Error Resume Next');
    writeln('  WB.ExecWB OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER');
    writeln('End Sub');
    writeln('</SCRIPT>');
    }
}

/**
 * Função....: formataMoeda(campo, SeparadorMilesimo, SeparadorDecimal, e, max)
 * Descrição.: formata um valor numérico com decimais em formulários
 * Uso.......: onKeyPress="return(formataMoeda(this,'.',',',event,12,2))"
 */
function formataMoeda(campo, sepMil, sepDec, e, max, tamDec) {
  var whichCode = (e.which > 0) ? e.which : e.keyCode;
  // Teclas Especiais: 13 = Enter, 0 = Delete, Setas, etc, 9 - Tab
  if ((whichCode == 13) || (whichCode == 0) || (whichCode == 9)) {
    return true;
  }
  var aux = campo.value;
  var len = aux.length;

  // Se for Backspace (8)
  if (whichCode == 8) {
    len--;
    aux = campo.value.substring(0,len);
  } else {
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if ('0123456789'.indexOf(key) == -1) {
      return false; // Chave inválida
    }
    // Limpa 0's a esquerda
    if (len == 1 && aux.charAt(0) == '0') {
      len = 0;
      aux = '';
    }
    aux += key;
    len++;
  }
  // Se chegar ao máximo informado
  if ((len > max) && (whichCode != 8)) {
    return false;
  }
  // Mascarar se o tamanho passar dos Milésimos
  if (len > (5+tamDec)) {
    // Retira a parte decimal
    aux = limpar(aux, '0123456789');
    decs = aux.substring(aux.length-tamDec);
    aux = aux.substring(0,aux.length-tamDec);
    aux2 = '';
    for (i = aux.length-1, j = 0; i > -1; i--, j++) {
      if (j == 3) {
        aux2 = sepMil + aux2;
        j = 0;
      }
      aux2 = aux.charAt(i) + aux2;
    }
    aux2 = aux2 + sepDec + decs;
  } else {
    aux = limpar(aux, '0123456789'); // Tira a "parte decimal"
    // Retira os zeros a esquerda
    while (aux.length > 1 && aux.charAt(0) == '0') {
      aux = aux.substring(1);
    }
    // corrige o tamanho
    while (aux.length < tamDec+1) {
      aux = '0' + aux;
    }
    aux2= aux.substring(0,aux.length-tamDec) + sepDec + aux.substring(aux.length-tamDec);
  }
  // Transfere o valor para o Campo
  if (len == 0) {
    campo.value = '0' + sepDec + '00';
  } else {
    campo.value = aux2;
  }
  return false;
}

/**
 * Função....: formataInt(campo, SeparadorMilesimo, e, max)
 * Descrição.: formata um valor inteiro em formulários
 * Uso.......: onKeyPress="return(formataInt(this,'.',event,5))"
 */
function formataInt(campo, sepMil, e, max){
  var whichCode = (e.which > 0) ? e.which : e.keyCode;
  // Teclas Especiais: 13 = Enter, 0 = Delete, Setas, etc, 9 - Tab
  if ((whichCode == 13) || (whichCode == 0) || (whichCode == 9)) {
    return true;
  }
  var aux = campo.value;
  var len = aux.length;

  // Se for Backspace (8)
  if (whichCode == 8) {
    len--;
    aux = campo.value.substring(0,len);
  } else {
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if ('0123456789'.indexOf(key) == -1) {
      return false; // Chave inválida
    }
    // Limpa 0's a esquerda
    if (len == 1 && aux.charAt(0) == '0') {
      len = 0;
      aux = '';
    }
    aux += key;
    len++;
  }
  // Se chegar ao máximo informado
  if ((len > max) && (whichCode != 8)) {
    return false;
  }
  // Mascarar se o tamanho passar dos Milésimos
  if (len > 3) {
    aux = limpar(aux, '0123456789');
    aux2 = '';
    for (i = aux.length-1, j = 0; i > -1; i--, j++) {
      if (j == 3) {
        aux2 = sepMil + aux2;
        j = 0;
      }
      aux2 = aux.charAt(i) + aux2;
    }
  } else {
    aux2 = aux;
  }
  // Transfere o valor para o Campo
  if (len == 0) {
    campo.value = '0';
  } else {
    campo.value = aux2;
  }
  return false;
}

/**
 * Função....: limpar(valor, validos)
 * Descrição.: Limpa o campo de qualquer caractere exceto os validos
 * Uso.......: onblur="this.value = limpar(this.value,'0123456789');"
 */
function limpar(valor, validos) {
  // retira caracteres invalidos da string
  var result = "";
  var aux;
  for (var i=0; i < valor.length; i++) {
    aux = validos.indexOf(valor.substring(i, i+1));
    if (aux>=0) {
      result += aux;
    }
  }
  return result;
}