/// $Id: funcoes.js,v 1.28 2003/12/12 13:05:31 ventura Exp $

function marcarTodos() {

    var check = eval("document.Navegacao.ckMarcaTodos");

    if(check.checked) {
        var cont = 1;
        for(i = 0; i < document.Navegacao.ckID.length; ++i) {
            ++cont;
            document.Navegacao.ckID[i].checked = true;
        }
        if(cont == 1) {
            document.Navegacao.ckID.checked = true;
        }
    } else {
        var cont = 1;
        for(i = 0; i < document.Navegacao.ckID.length; ++i) {
            ++cont;
            document.Navegacao.ckID[i].checked = false;
        }
        if(cont == 1) {
            document.Navegacao.ckID.checked = false;
        }
    }
}

function ignoreSpaces(fcn_string) {
        var fcn_temp = "";
        fcn_string = '' + fcn_string;
        splitstring = fcn_string.split(" ");
        for(fcn_i = 0; fcn_i < splitstring.length; fcn_i++)
        fcn_temp += splitstring[fcn_i];
        return fcn_temp;
}

function removeEspacosEmBranco(fcn_item)
{
  var fcn_tmp = "";
  var fcn_item_length = fcn_item.value.length;
  var fcn_item_length_minus_1 = fcn_item.value.length - 1;
  for (fcn_index = 0; fcn_index < fcn_item_length; fcn_index++)
  {
    if (fcn_item.value.charAt(fcn_index) != ' ')
    {
      fcn_tmp += fcn_item.value.charAt(fcn_index);
    }
  }
  fcn_item.value = fcn_tmp;
}

function removeEspacosAMais(fcn_item)
{
  var fcn_tmp = "";
  var fcn_item_length = fcn_item.value.length;
  var fcn_item_length_minus_1 = fcn_item.value.length - 1;
  for (fcn_index = 0; fcn_index < fcn_item_length; fcn_index++)
  {
    if (fcn_item.value.charAt(fcn_index) != ' ')
    {
      fcn_tmp += fcn_item.value.charAt(fcn_index);
    }
    else
    {
      if (fcn_tmp.length > 0)
      {
        if (fcn_item.value.charAt(fcn_index+1) != ' ' && fcn_index != fcn_item_length_minus_1)
        {
          fcn_tmp += fcn_item.value.charAt(fcn_index);
        }
      }
    }
  }
  fcn_item.value = fcn_tmp;
}


function fcEZero(fcn_numr){
  if (parseInt(fcn_numr,10) == 0)
    return true;
  return false;
}

function fcDigitoNumerico (fcn_digito) {
  return ( ( (fcn_digito >= "0") && (fcn_digito <= "9") ) || (fcn_digito == ",") || (fcn_digito == "."))
}

function fcDigitoNumerico2 (fcn_digito) {
  return ( ( (fcn_digito >= "000") && (fcn_digito <= "999") ) || (fcn_digito == ",") || (fcn_digito == "."))
}

function fcSigla2 (fcn_vlr) {
  if ( (fcn_vlr.length<2) || (!isNaN(fcn_vlr.substring(0,1))) || (!isNaN(fcn_vlr.substring(1,1))) )
    return false;
  return true;
}

function fcENumero(fcn_numr){
  var fcn_i;
  if (fcVazio(fcn_numr)) {
    window.alert("O valor não pode ser vazio.");
    return false;
  }
  for (fcn_i = 0; fcn_i < fcn_numr.length; fcn_i++) {
    var fcn_c = fcn_numr.charAt(fcn_i);
    if (!fcDigitoNumerico(fcn_c)) {
        window.alert("Informar apenas valores numéricos.");
        return false;
    }
  }
  return true;
}

function verificaSeNumero(campo) {
    fcn_numr = campo.value;
    var fcn_i;
    for (fcn_i = 0; fcn_i < fcn_numr.length; fcn_i++) {
        var fcn_c = fcn_numr.charAt(fcn_i);
        if (!fcDigitoNumerico(fcn_c)) {
            window.alert("Informar apenas valores numéricos.");
            campo.value = "";
            campo.focus();
            return false;
        }
    }
    return true;
}

function fcVazio(fcn_vlr) {
  if((fcn_vlr == null) || (fcn_vlr.length == 0))
      return true;
  return fcEspacoBranco2(fcn_vlr);
}

function verificaSeVazioComMensagem(campo) {

    valor = campo.value;

    if((valor == null) || (valor.length == 0)) {
      alert("O campo não deve estar vazio.");
      campo.focus();
      return false;
    } else if(fcEspacoBranco2(valor)) {
        alert("O campo não deve estar vazio.");
        campo.focus();
        return false;
    }

    return true;

}

function fcEspacoBranco(fcn_vlr) {
  if ((fcn_vlr.substring(0,1)==' ')||(fcn_vlr.substring(fcn_vlr.length-1,fcn_vlr.length)==' '))
    return true;
  return false;
}

function fcEspacoBranco2(fcn_vlr){//verifica se todos os caracteres são espaço em branco
   var strValidos = " ";
   var key;
   var nEspacos = 0;
   for (fcn_i = 0; fcn_i < (fcn_vlr.length);fcn_i++){
       key = fcn_vlr.substr(fcn_i,1);
       if ( strValidos.indexOf(key ) != -1 ){
       nEspacos++;
       }
   }
   if(nEspacos == fcn_vlr.length){
       fcn_vlr = '';
       return true;
   }else{
       return false;
   }
}

function fcEspacoNum(fcn_vlr) {
  if (fcn_vlr.indexOf(" ") >= 0)
    return true;
  return false;
}

function TrimLeft( fcn_str ) {
  var resultStr = "";
  var fcn_i = fcn_len = 0;
  if (fcn_str+"" == "undefined" || fcn_str == null)
    return null;

  fcn_str += "";

  if (fcn_str.length == 0)
    resultStr = "";
  else {
    fcn_len = fcn_str.length;
    while ((fcn_i <= fcn_len) && (fcn_str.charAt(fcn_i) == " "))
      fcn_i++;
    resultStr = fcn_str.substring(fcn_i, fcn_len);
  }
  return resultStr;
}

function TrimRight( fcn_str ) {
  var resultStr = "";
  var fcn_i = 0;

  if (fcn_str+"" == "undefined" || fcn_str == null)
    return null;
  fcn_str += "";

  if (fcn_str.length == 0)
    resultStr = "";
  else {
    fcn_i = fcn_str.length - 1;
    while ((fcn_i >= 0) && (fcn_str.charAt(fcn_i) == " "))
      fcn_i--;
    resultStr = fcn_str.substring(0, fcn_i + 1);
  }
  return resultStr;
}

function fcTrim( fcn_str ) {
  var resultStr = "";
  resultStr = TrimLeft(fcn_str);
  resultStr = TrimRight(resultStr);
  return resultStr;
}

function fcData(fcn_data){
      var fcn_dia = parseInt(fcn_data.substring(0,2),10);
      var fcn_mes = parseInt(fcn_data.substring(3,5),10);
      var fcn_ano = parseInt(fcn_data.substring(6,10),10);
       if (fcn_dia <= 31 && fcn_mes <=12 && fcn_ano >= 1000){
          if (fcn_data.substring(0,1)=='0' && fcn_data.substring(1,2) != '0' || fcn_data.substring(0,1)!='0'){
             if (fcn_data.substring(2,3)=="/"){
                if (fcn_data.substring(3,4)=='0' && fcn_data.substring(4,5)!='0' || fcn_data.substring(3,4)!='0'){
                    if (fcn_data.substring(5,6)=="/"){
                        if (fcn_data.substring(6,7)== '0' || fcn_data.substring(6,7)=='' && fcn_data.substring(7,8)!='0'){
                            window.alert('O ano que você digitou não existe!');
                            return false;
                        } else {
                          if (fcn_mes == 2){
                            if ((fcn_dia > 0 ) && (fcn_dia <= 29)){
                              if (fcn_dia == 29){
                                if ((fcn_ano % 4) == 0){
                                  return true;
                                }else{
                            window.alert('Este dia não existe, certifique - se de que digitou corretamente!');
                                  return false;
                               }
                             }
                           } else {
                          window.alert('Este dia não existe, certifique - se de que digitou corretamente!');
                              return false;
                           }
                         }
                         if ((fcn_mes == 4)||(fcn_mes == 6)||(fcn_mes == 9)||(fcn_mes == 11)){
                           if ((fcn_dia > 0 ) && (fcn_dia <= 30)){
                             return true;
                           }else{
                           window.alert('Este dia não existe, certifique - se de que digitou corretamente!');
                             return false;
                           }
                         }
                 if ((fcn_mes == 1)||(fcn_mes == 3)||(fcn_mes == 5)||(fcn_mes ==7)||(fcn_mes == 8)||(fcn_mes == 10)||(fcn_mes == 12)) {
                           if ((fcn_dia > 0) && (fcn_dia <= 31)) {
                              return true;
                           }else{
                             window.alert('Este dia não existe, certifique-se de que digitou corretamente!');
                             return false;
                           }
                         }
                        }
                    }else{
                       window.alert('A data foi digitada fora do padrão(dd/mm/aaaa)  !');
                       return false;
                    }
                }else{
                  window.alert('Você digitou um mês que não existe!');
                  return false;
                }
             }else{
               window.alert('A data foi digitada fora do padrão(dd/mm/aaaa)  !');
               return false;
             }
          }else{
            window.alert('Você digitou um fcn_dia que não existe!');
            return false;
          }
       }else{
 window.alert('O dia e/ou o mês que você digitou não existe, ou Você digitou fora do padrão (dd/mm/aaaa) !');
         return false;
       }
    return true;
}

function validaExercicio(fcn_exer) {
    fcn_hoje = new Date();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    if (fcVazio(fcn_anoinformado)) {
        window.alert('Informe o exercício.');
        return false;
    } else if (!fcENumero(fcn_anoinformado)) {
        return false;
    } else if (fcn_anoinformado.length != 4) {
        window.alert('Exercício incorreto.');
        return false;
       } else {
       if (fcn_anoinformado < (2000)) {
            window.alert('Exercício inválido! Deve ser maior que 1999');
            return false;
       } else if (fcn_anoinformado > (fcn_anoatual)) {
          window.alert('Exercício inválido! Não pode ser superior ao fcn_ano atual!');
          return false;
       }
    }
    return true;
}
function validaExercicioPeriodo(fcn_exer,fcn_inic) {
    fcn_hoje = new Date();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    fcn_anoinicio = fcn_inic;

    if (fcVazio(fcn_anoinformado)) {
        window.alert('Informe o exercício.');
        return false;
    } else if (!fcENumero(fcn_anoinformado)) {
        window.alert('O exercício deve ser numérico.');
        return false;
    } else if (fcn_anoinformado.length != 4) {
        window.alert('Exercício incorreto.');
        return false;
    } else {
       if (fcn_anoinformado < fcn_anoinicio) {
            window.alert('Exercício informado é invalido.');
            return false;
       } else if (fcn_anoinformado > fcn_anoatual) {
          window.alert('Exercício informado é invalido.');
          return false;
       }
    }
    return true;
}
function fcComparaData(fcn_dia1,fcn_mes1,fcn_ano1,fcn_dia2,fcn_mes2,fcn_ano2) {
  fcn_data1 = fcn_ano1+fcn_mes1+fcn_dia1;
  fcn_data2 = fcn_ano2+fcn_mes2+fcn_dia2;
  if (fcn_data1 > fcn_data2) {
    return true;
  }
  return false;
}

function fcValidaDataMaiorAtual(fcn_diainfo,fcn_mesinfo,fcn_anoinfo) {
  fcn_hoje = new Date();
  fcn_ano = fcn_hoje.getFullYear();
  fcn_mes = fcn_hoje.getMonth()+1;
  fcn_dia = fcn_hoje.getDate();

  if (fcn_dia < 10){
     fcn_dia = "0"+String(fcn_dia);
  }
  if (fcn_mes < 10){
     fcn_mes = "0"+String(fcn_mes);
  }
  fcn_datainfo = fcn_anoinfo+fcn_mesinfo+fcn_diainfo;
  fcn_data = String(fcn_ano)+String(fcn_mes)+String(fcn_dia);

  if ( fcn_data < fcn_datainfo){
     window.alert("A data não pode ser superior à atual.");
     return false;
  }
  return true;
}
function identificartrimestre(fcn_exer) { // identifica trimestre pelo fcn_ano atual
    fcn_hoje = new Date();
    fcn_diaatual = fcn_hoje.getDate();
    fcn_mesatual = fcn_hoje.getMonth();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    fcn_trim = 0;
    if ((fcn_mesatual == 1) || (fcn_mesatual == 2) ||(fcn_mesatual == 3)) {
       fcn_trim = 1;
    } else if ((fcn_mesatual == 4) || (fcn_mesatual == 5) ||(fcn_mesatual == 6)) {
       fcn_trim = 2;
    } else if ((fcn_mesatual == 7) || (fcn_mesatual == 8) ||(fcn_mesatual == 9)) {
       fcn_trim = 3;
    } else {
       fcn_trim = 4;
    }
    return fcn_trim;
  }

function identificardatatrimestre(fcn_mes) {
    fcn_mesatual = fcn_mes;
    fcn_trim_fcn_data = 0;
    if ((fcn_mesatual == 1) || (fcn_mesatual == 2) ||(fcn_mesatual == 3)) {
       fcn_trim_fcn_data = 1;
    } else if ((fcn_mesatual == 4) || (fcn_mesatual == 5) ||(fcn_mesatual == 6)) {
       fcn_trim_fcn_data = 2;
    } else if ((fcn_mesatual == 7) || (fcn_mesatual == 8) ||(fcn_mesatual == 9)) {
       fcn_trim_fcn_data = 3;
    } else {
       fcn_trim_fcn_data = 4;
    }
    return fcn_trim_fcn_data;
  }

function validaMesExercicio(fcn_exer,fcn_mes) {
    fcn_hoje = new Date();
    fcn_diaatual = fcn_hoje.getDate();
    fcn_mesatual = fcn_hoje.getMonth();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    fcn_mesinformado = fcn_mes;
    if (fcn_anoinformado == fcn_anoatual) {
        if (fcn_mesinformado > (fcn_mesatual + 2)) {
           window.alert('Mês informado é inválido.');
           return false;
        }
    } else if (fcn_anoinformado == (fcn_anoatual + 1)) {
        if (fcn_mesinformado != 1) {
           window.alert('Mês informado deve ser Janeiro.');
           return false;
        }
    } else if (fcn_anoinformado == (fcn_anoatual - 1)) {
        if (fcn_mesinformado != 12) {
           window.alert('Mês informado deve ser Dezembro.');
           return false;
        }
    }
    return true;
}

function validaTrimestreExercicio(fcn_exer,fcn_tri) {
    identificartrimestre(fcn_exer);
    fcn_hoje = new Date();
    fcn_diaatual = fcn_hoje.getDate();
    fcn_mesatual = fcn_hoje.getMonth();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    fcn_triminformado = fcn_tri;

    if (fcVazio(fcn_anoinformado)) {
        window.alert('Informe o exercício.');
        return false;
    } else if (!fcENumero(fcn_anoinformado)) {
        window.alert('O exercício deve ser numérico.');
        return false;
    } else if (fcn_anoinformado.length != 4) {
        window.alert('Exercício incorreto.');
        return false;
    } else {
       if (fcn_anoatual == fcn_anoinformado) {
          if ((fcn_triminformado == fcn_trim) || (fcn_triminformado == (fcn_trim+1)) || (fcn_triminformado <= fcn_trim)) {
             return true;
          } else {
             window.alert('Trimestre Informado é invalido.');
             return false;
          }
       } else if (fcn_anoinformado == (fcn_anoatual-1)) {
          if (fcn_triminformado != 4) {
             window.alert('Trimestre Informado deve ser o quarto.');
             return false;
          }
       } else if (fcn_anoinformado < (fcn_anoatual-1)) {
            window.alert('Exercício informado é invalido.');
            return false;
       } else if (fcn_anoinformado == (fcn_anoatual+1)) {
           if (fcn_triminformado != 1) {
              window.alert('Trimestre Informado deve ser o primeiro.');
              return false;
           }
       } else if (fcn_anoinformado > (fcn_anoatual+1)) {
           window.alert('Exercício informado é invalido.');
           return false;
       }
    }
    return true;
}

function validaConsultaTrimestreExercicio(fcn_exer,fcn_tri) {
    identificartrimestre(fcn_exer);
    fcn_hoje = new Date();
    fcn_diaatual = fcn_hoje.getDate();
    fcn_mesatual = fcn_hoje.getMonth();
    fcn_anoatual = fcn_hoje.getFullYear();
    fcn_anoinformado = fcn_exer;
    fcn_triminformado = fcn_tri;

    if (fcVazio(fcn_anoinformado)) {
        window.alert('Informe o exercício.');
        return false;
    } else if (!fcENumero(fcn_anoinformado)) {
        window.alert('O exercício deve ser numérico.');
        return false;
    } else if (fcn_anoinformado.length != 4) {
        window.alert('Exercício incorreto.');
        return false;
    } else {
       if (fcn_anoatual == fcn_anoinformado) {
          if ((fcn_triminformado == fcn_trim) || (fcn_triminformado == (fcn_trim+1)) || (fcn_triminformado <= fcn_trim)) {
            return true;
          } else {
            window.alert('Trimestre Informado é invalido.');
            return false;
          }
       } else if (fcn_anoinformado == (fcn_anoatual+1)) {
          if (fcn_triminformado != 1) {
             window.alert('Trimestre Informado deve ser o primeiro.');
             return false;
          }
       } else if (fcn_anoinformado > (fcn_anoatual+1)) {
          window.alert('Exercício informado é invalido.');
          return false;
       }
    }
    return true;
}

function alinhaNumero( fcn_num , fcn_tam , fcn_dir ) {
   var fcn_aux = "" , fcn_len = 0 , fcn_i = 0 ;
   // Tira espaços em branco
   fcn_num = String(fcn_num);
   fcn_len = fcn_num.length ;
   for( fcn_i = 0 ; fcn_i < fcn_len ; fcn_i++ )
      if( fcn_num.charAt( fcn_i ) != ' ' )
         fcn_aux += fcn_num.charAt( fcn_i ) ;

   // Completa com zeros a direita
   fcn_len = fcn_aux.length ;
   if( fcn_len < fcn_tam ) {
      if( (fcn_dir == "e" ) || (fcn_dir == "E") )
         for( fcn_i = 0 ; fcn_i < ( fcn_tam - fcn_len ) ; fcn_i++ )
            fcn_aux = "0" + fcn_aux ;
   else
      for( fcn_i = 0 ; fcn_i < ( fcn_tam - fcn_len ) ; fcn_i++ )
         fcn_aux = fcn_aux + "0" ;
   }
   return fcn_aux ;
}

function fcRetiraPonto(fcn_campo) {
  var Digitos = "0123456789"; // aceitar apenas esses valores
  var numrFormatado = "";
  var fcn_digito = "";
  for (var fcn_i=0; fcn_i < fcn_campo.length; fcn_i++){
      fcn_digito = fcn_campo.charAt(fcn_i);
      if ((Digitos.indexOf(fcn_digito)>=0) || (fcn_campo.charAt(fcn_i) == ",")) {
        numrFormatado = numrFormatado + fcn_digito;
      }
  }
  return (numrFormatado);
}

function fcTrocaVirgulaPonto(fcn_campo,vp) {
   if (vp == "vp") {
     var trocar = ",";
     var substitui =".";
   } else if (vp == "pv") {
     var trocar = ".";
     var substitui =",";
   }
   var Posic, Carac;
   var TempLog = "";
   for (var fcn_i=0; fcn_i < fcn_campo.length; fcn_i++){
      Carac = fcn_campo.charAt (fcn_i);
      Posic  = trocar.indexOf (Carac);
      if (Posic > -1)
         TempLog += substitui.charAt (Posic);
      else
         TempLog += fcn_campo.charAt (fcn_i);
   }
   return (TempLog);
}

function fcValidaValor(fcn_vlr) {
  fcn_a = fcn_vlr.split(",");
  fcn_b = fcn_vlr.split(".");
  if ((fcn_a.length > 2) || (fcn_b.length > 2) || ((fcn_a.length == 2) && (fcn_b.length ==2))) {
     window.alert("Informar apenas separador decimal.");
     return false;
  }
  return true;
}

function formatCurrency(fcn_num,comPonto) {
  var isNegative = false;
  fcn_num = fcn_num.toString().replace('/\\$|\\,/g','');

  if( isNaN( fcn_num ) ) {
    fcn_num = "0";
  }
  if ( fcn_num < 0 ) {
    fcn_num = Math.abs( fcn_num );
    isNegative = true;
  }
  cents = Math.floor( ( fcn_num * 100 + 0.5 ) % 100 );
  fcn_num = Math.floor( ( fcn_num * 100 + 0.5 ) / 100 ).toString();
  if ( cents < 10 ) {
    cents = "0" + cents;
  }
  if (comPonto == "S") {
    for ( fcn_i = 0; fcn_i < Math.floor( ( fcn_num.length - ( 1 + fcn_i ) ) / 3 ); fcn_i++) {
      fcn_num = fcn_num.substring( 0 ,fcn_num.length - ( 4 * fcn_i + 3 ) ) + '.' + fcn_num.substring( fcn_num.length - ( 4 * fcn_i + 3 ) );
    }
  } else if (comPonto == "N") {
    for ( fcn_i = 0; fcn_i < Math.floor( ( fcn_num.length - ( 1 + fcn_i ) ) / 3 ); fcn_i++) {
      fcn_num = fcn_num.substring( 0 ,fcn_num.length - ( 4 * fcn_i + 3 ) ) + fcn_num.substring( fcn_num.length - ( 4 * fcn_i + 3 ) );
    }
  }
  var result = fcn_num + ',' + cents;
  if ( isNegative ) {
    result = "-" + result;
  }
  return result;
}

function fcFormataNum(fld, e) {
   // constantes
   return fcFormataNumero (fld,e,2,false);
}
function fcFormataNum2(fld, e) {
   // constantes
   return fcFormataNumero (fld,e,4,false);
}
function fcFormataNumSinal(fld, e) {
   // constantes
   return fcFormataNumero (fld,e,2,true);
}

function fcFormataNumero(fld, e,qtdDec, isSinal) {
  // constantes
  var carDec = ',';
  var carMil = '.';
  var carNeg = '-';
  var carPos = '+';
  var tabNum = '0123456789';
  // variaveis
  var key = '';
  var fcn_orig = '';
  var fcn_aux = '';
  var fcn_i = 0;
  var fcn_len = 0;
  var whichCode = (window.Event) ? e.which : e.keyCode;
  if (whichCode == 13) return true;  // Enter
  key = String.fromCharCode(whichCode);  // Get key value from key code
  if ((tabNum.indexOf(key) == -1) && (key != carNeg) &&
       (key.charAt(fcn_i) != carPos))
    return false;  // Not a valid key
  if ( (key == carNeg)  && (! isSinal) )
    return false;  // Not a valid key

  // limpa mascara do fcn_campo numerico
  fcn_orig = fld.value;
  fcn_len = fcn_orig.length;
  fcn_aux = '';
  var sinal = carPos;
  if ( (key == carNeg) || (key == carPos) ) // digitou sinal primeiro,
     sinal = key;                           // nao entra no for

  for(fcn_i = 0; fcn_i < fcn_len; fcn_i++) {
    if (fcn_i == 0) {
       if ( (key == carNeg) || (key == carPos) ) // digitou sinal
           sinal = key;
       else
          if ( (fcn_orig.charAt(fcn_i) == carNeg ) ||
               (fcn_orig.charAt(fcn_i) == carPos) ) // tinha sinal
              sinal = fcn_orig.charAt(fcn_i);
    }

    if (tabNum.indexOf(fcn_orig.charAt(fcn_i)) != -1)  // digitos
            if ( ((fcn_aux != carNeg) && (fcn_aux != '')) || (fcn_orig.charAt(fcn_i) != '0' ) )  { // ja possui fcn_digito significativo ou veio diferente de zero
           fcn_aux += fcn_orig.charAt(fcn_i);
        }
  }
  if (tabNum.indexOf(key) != -1) // teclou fcn_digito, não sinal
    fcn_aux += key;
  // reformata numero
  fcn_orig = fcn_aux;
  fcn_len = fcn_orig.length;
  fcn_aux = '';
  var fcn_qtd = 0;
  for(fcn_i = fcn_len - 1 ; fcn_i >= 0; fcn_i--) {
    fcn_qtd += 1;

    if ( (fcn_qtd == qtdDec + 1) && (qtdDec  != 0) )
       fcn_aux = carDec + fcn_aux;
    if ( (fcn_qtd > qtdDec + 1) && ( (fcn_qtd - qtdDec - 1) % 3  == 0) )
       fcn_aux = carMil + fcn_aux;
    fcn_aux = fcn_orig.charAt(fcn_i) + fcn_aux;
  }
  for (;fcn_qtd < qtdDec; fcn_qtd++) // completa com zeros os decimais
    fcn_aux = '0' + fcn_aux;
  if ( (fcn_qtd == qtdDec) && (qtdDec != 0) )
    fcn_aux = '0' + carDec + fcn_aux;
  if (sinal == carNeg)
   fcn_aux = sinal + fcn_aux;
  fld.value = fcn_aux;
  return false;
}




VerifiqueTAB=true;
function fcSaltaTAB(quem, tammax) {
   var fcn_i=0,fcn_j=0, fcn_indice=-1;
   if ( (quem.value.length == tammax) && (VerifiqueTAB) ) {

     for (fcn_i=0; fcn_i<document.forms.length; fcn_i++) {
       for (fcn_j=0; fcn_j<document.forms[fcn_i].elements.length; fcn_j++) {
          if (document.forms[fcn_i].elements[fcn_j].name == quem.name) {
            fcn_indice=fcn_i;
            break;
          }
       }
       if (fcn_indice != -1) break;
     }
     for (fcn_i=0; fcn_i<=document.forms[fcn_indice].elements.length; fcn_i++) {
       if (document.forms[fcn_indice].elements[fcn_i].name == quem.name) {
          while ( (document.forms[fcn_indice].elements[(fcn_i+1)].type == "hidden") &&
                  (fcn_i < document.forms[fcn_indice].elements.length) ) {
             fcn_i++;
          }
          document.forms[fcn_indice].elements[(fcn_i+1)].focus();
          VerifiqueTAB=false;
          break;
       }
     }
   }
}

function numeroCaracteres(fcn_campo, Caracteres){

    intCaracteres = parseInt(Caracteres) - fcn_campo.value.length;

    if(intCaracteres > 0){

        return true;

    }else{

        intMensagem =  parseInt(Caracteres) - 1;

        fcn_campo.value = fcn_campo.value.substr(0,intMensagem);

        return false;

    }

}

function fcPararTAB(quem) { VerifiqueTAB=false; }
function fcChecarTAB() { VerifiqueTAB=true; }

function completaZero(fcn_campo){
var fcn_i = 0;
        if(fcn_campo.value.length >= 1){
                if (fcn_campo.value.length != fcn_campo.maxLength) {
                    for (fcn_i=0; ((fcn_campo.maxLength - fcn_campo.value.length)>0); fcn_i++){
                        fcn_campo.value = '0' + fcn_campo.value;
                    }
                }
            }
}



function validaTecla(fcn_campo, event)
{
    //caracteres aceitos
    var strValidos = "0123456789"
    var BACKSPACE =  8;
    var key;
    var fcn_tecla;
    CheckTAB = true;
    if (navigator.appName.indexOf("Netscape") != -1)
        fcn_tecla = event.which;
    else
        fcn_tecla = event.keyCode;
    key = String.fromCharCode( fcn_tecla);
    if ( fcn_tecla == 13 )
        return false;
    if ( fcn_tecla == BACKSPACE )
        return true;
    if ( strValidos.indexOf( key ) == -1 )
        return false;
    fcChecarTAB();
    return true;
}

function removeCaracteresEspeciais(fcn_campo, event)
{
    var BACKSPACE =  8;
    var key;
    var fcn_tecla;
    CheckTAB = true;
    if (navigator.appName.indexOf("Netscape") != -1)
        fcn_tecla = event.which;
    else
        fcn_tecla = event.keyCode;
   key = String.fromCharCode( fcn_tecla);
   if ((fcn_tecla > 32 && fcn_tecla < 48) || (fcn_tecla >=48 && fcn_tecla<=57) ||
   (fcn_tecla > 57 && fcn_tecla < 65) ||(fcn_tecla > 90 && fcn_tecla < 97)||
   fcn_tecla == 162 || fcn_tecla == 163 || fcn_tecla == 167 || fcn_tecla == 168 || fcn_tecla==170 ||
   fcn_tecla==172 || fcn_tecla==186)
        return false;
    if ( fcn_tecla == 13 )
        return false;
    if ( fcn_tecla == BACKSPACE )
        return true;

    fcChecarTAB();
    return true;
}

function checaExercicio(fcn_exercicio) {

        if (fcn_exercicio < 1500) {
                alert("Exercício inválido");
                return false;
        }
        return true;

}
//Função para bloquear multiplos submits
var bexec = true;
function bloquearSubmits(obj) {
	if (bexec) {
		bexec = false;
		if (obj == "") {
  			return true;
  		} else {
  			obj.submit();
  		}
	} else {
		return false;
	}
}

function acertarDouble(fcn_valor) {
   fcn_str = formatCurrency (fcn_valor,'N');
   fcn_str = fcTrocaVirgulaPonto(fcn_str,"vp");
   return fcn_str;
}

function fcValidaConta(fcn_conta){

        var fcn_num = "0123456789";
        var fcn_digito = "";
        var length = (fcn_conta.length - 1);

        for (fcn_i = 0; fcn_i <= length; fcn_i++) {

                fcn_digito = fcn_conta.charAt(fcn_i);

                if(fcn_i < length){

                        if (fcn_num.indexOf(fcn_digito) == -1){
                                var numDigito = (fcn_conta.length - 1);
                                window.alert("O dígito "+fcn_digito+" é inválido, ele deve ser numérico.");
                                return false;
                        }
                }else{
                        if ( (fcn_num.indexOf(fcn_digito) == -1) && (fcn_digito.toUpperCase() != "X")){
                                window.alert("O último dígito deve ser numérico ou \"x\".");
                                return false;
                        }
                }
        }

        return true;
}

function fcValidaContaCorrente(fcn_banco,fcn_agencia,fcn_conta){
    if ( fcValidaConta (fcn_conta) )
        if (fcn_banco == "341") {
            if ( ! ( fcENumero(fcn_agencia) && fcENumero(fcn_conta) ) )
               return false;
            var fcn_aux = '0000' + fcn_agencia;
            var agenciaConta = fcn_aux.substr(fcn_aux.length - 4,4);
            fcn_aux = '000000' + fcn_conta;
            restoConta = fcn_aux.substr(0,fcn_aux.length-6);
            fcn_aux = fcn_aux.substr(fcn_aux.length - 6,5);
            agenciaConta = agenciaConta + fcn_aux;
            for (fcn_i=restoConta.length -1 ;fcn_i >= 0 ;fcn_i--) {
                if ( restoConta.charAt(fcn_i) != "0") {
                    window.alert("Conta corrente com mais de 6 digitos");
                    return false;
                }
            }
            var fcn_parc = 0;
            var fcn_mult = 2;
            var fcn_soma = 0;
            for (fcn_i=agenciaConta.length -1 ;fcn_i >= 0 ;fcn_i--) {
                fcn_parc =   fcn_mult * agenciaConta.charAt(fcn_i);
                if (fcn_parc > 9)
                    fcn_parc = fcn_parc + 1;
                fcn_soma = fcn_soma + fcn_parc;
                if (fcn_mult == 2)
                    fcn_mult = 1;
                else
                    fcn_mult = 2;
            }
            fcn_soma = 10 - fcn_soma % 10;
            if (fcn_soma == 10)
               fcn_soma = 0;
            var dig = fcn_conta.substr(fcn_conta.length - 1 ,1);
            if (fcn_soma != dig) {
                window.alert("Dígito verificador da conta não confere");
                return false;
            }

            return true;

        }
        else
           return true;
 else

        return false;

}
function formatarData(fcn_campo, teclapres){
        var fcn_tecla = teclapres.keyCode;
        var vr = new String(fcn_campo.value);
        fcn_tam = vr.length;
        if(fcn_campo.maxLength == 7){ // formato mm/aaaa
            if(!(vr.substr(fcn_tam -1, fcn_tam) == '/' || vr.substr(fcn_tam -1, fcn_tam) == '' || vr.substr(fcn_tam -1, fcn_tam) == ' ')){
                vr = vr.replace("/", "");
                fcn_tam = vr.length + 1;
                if (fcn_tecla != 9 && fcn_tecla != 8){
                    if(fcn_tam < 7){
                        if (fcn_tam == 3)
                            fcn_campo.value = vr.substr(0,2) + '/' + vr.substr(3, fcn_tam);

                    }else{
                        fcn_campo.value = fcn_campo.value.substr(0,7);
                    }

                }
            }
        }else if(fcn_campo.maxLength == 10){ // formato dd/MM/aaaa
            if(!(vr.substr(fcn_tam -1, fcn_tam) == '' || vr.substr(fcn_tam -1, fcn_tam) == ' ')){
                vr = vr.replace("/", "");
                vr = vr.replace("/", "");
                fcn_tam = vr.length + 1;
                if (fcn_tecla != 9 && fcn_tecla != 8){
                    if(fcn_tam < 10){
                        if (fcn_tam == 3){
                            fcn_campo.value = vr.substr(0,2) + '/' + vr.substr(3, fcn_tam);
                        }
                        if(fcn_tam == 5){
                            fcn_campo.value = vr.substr(0,2) + '/' + vr.substr(2,4) + '/' + vr.substr(5, fcn_tam);
                        }
                    }else{
                        fcn_campo.value = fcn_campo.value.substr(0,10);
                    }

                }
            }
        }
}

//========================================================================================

/* Função utilizada pra formatar cnpj ou CNPJ, utilizando a ação onBlur,
   e de acordo com o parâmetro tipoPessoa:
   * PessoaFisica   = F
   * PessoaJuridica = J
*/
function formatarCPFCNPJOnBlur(campo, tipoPessoa){
    var cpfCNPJFormatado = new String(removerDelimitadores(campo));
    var cpfCNPJFormatadoAux;
    if(!ENumero(cpfCNPJFormatado)){
            campo.focus();
            campo.value = "";
            return false;
    }
    if(tipoPessoa =="F"){//Pessoa Física
            if(cpfCNPJFormatado.length <= 11 && cpfCNPJFormatado.length> 0){
                if(cpfCNPJFormatado.length < 11){
                    while(cpfCNPJFormatado.length!=11){
                        cpfCNPJFormatado = '0'+cpfCNPJFormatado;
                    }
                }
                campo.value = cpfCNPJFormatado.substr(0,3)+'.'+cpfCNPJFormatado.substr(3,3)+'.'+cpfCNPJFormatado.substr(6,3)+'-'+cpfCNPJFormatado.substr(9,3);
                return true;
            }else
                return cpfCNPJFormatado;
    }else{//Pessoa Jurídica
            if(cpfCNPJFormatado.length <= 14 && cpfCNPJFormatado.length> 0){
                if(cpfCNPJFormatado.length < 14){
                    while(cpfCNPJFormatado.length!=14){
                        cpfCNPJFormatado = '0'+cpfCNPJFormatado;
                    }
                }
                campo.value  = cpfCNPJFormatado.substr(0,2)+'.'+cpfCNPJFormatado.substr(2,3)+'.'+cpfCNPJFormatado.substr(5,3)+'/'+cpfCNPJFormatado.substr(8,4)+'-'+cpfCNPJFormatado.substr(12,2);

                return true;
            }else
                return cpfCNPJFormatado;
    }
}

/* Função utilizada pra formatar CPF ou CNPJ, utilizando a função onKeyPress,
   e de acordo com o parâmetro tipoPessoa:
   * PessoaFisica   = F
   * PessoaJuridica = J
*/
function formatarCPFCNPJ(campo, teclapres, tipoPessoa){
    var tecla = teclapres.keyCode;
    var vr = removeEspacos(campo);

    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace("/", "");
    vr = vr.replace("-", "");

    if(tipoPessoa =="F"){//Pessoa Física
        tam = vr.length + 1;
        if (tecla != 9 && tecla != 8){
            if (tam > 3 && tam < 7)
                    campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
            if (tam >= 7 && tam <10)
                    campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
            if (tam >= 10 && tam < 12)
                    campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
        }
    }else{//Pessoa Jurídica
        tam = vr.length + 1 ;
        if (tecla != 9 && tecla != 8){
            if (tam > 2 && tam < 6)
                campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
            if (tam >= 6 && tam < 9)
                campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
            if (tam >= 9 && tam < 13)
                campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
            if (tam >= 13 && tam < 15)
                campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
        }
    }
}

/* Somente para uso das classes formatarCPFCNPJ e formatarCPFCNPJOnBlur.*/
function removerDelimitadores(cpfCNPJ){
    var number = removeEspacos(cpfCNPJ); //seta number com o valor de cpfCNPJ
    tmp = number.substring(0,number.indexOf('.'));
    tmp += number.substring(number.indexOf('.')+1,number.length);
    number = tmp;
    while(number.indexOf('.')!=-1 || number.indexOf('/')!=-1 ||
          number.indexOf('-')!=-1){
        if(number.indexOf('.')!=-1){
            tmp = number.substring(0,number.indexOf('.'));
            tmp += number.substring(number.indexOf('.')+1,number.length);
            number = tmp;
        }else if(number.indexOf('/')!=-1){
            tmp = number.substring(0,number.indexOf('/'));
            tmp += number.substring(number.indexOf('/')+1,number.length);
            number = tmp;
        }else{
            tmp = number.substring(0,number.indexOf('-'));
            tmp += number.substring(number.indexOf('-')+1,number.length);
            number = tmp;
        }
    }
    return tmp;
}

/* Somente para uso das classes formatarCPFCNPJ e formatarCPFCNPJOnBlur.*/
function ENumero(campo){
    for (i = 0; i < campo.length; i++) {
      if (!fcDigitoNumerico(campo.charAt(i))) {
                //campo.focus();
          return false;
      }
    }
    return true;
}

/* Somente para uso das classes formatarCPFCNPJ e formatarCPFCNPJOnBlur.*/
function removeEspacos(item)
{
  var tmp = "";
  var item_length = item.value.length;
  var item_length_minus_1 = item.value.length - 1;
  for (index = 0; index < item_length; index++)
  {
    if (item.value.charAt(index) != ' ')
    {
      tmp += item.value.charAt(index);
    }
    else
    {
      if (tmp.length > 0)
      {
        if (item.value.charAt(index+1) != ' ' && index != item_length_minus_1)
        {
          tmp += item.value.charAt(index);
        }
      }
    }
  }
  return tmp;
}


function abrirNoCentro (url, width, height, windowName, featureString) {
  if (!windowName)
    windowName = '';
  if (!featureString)
    featureString = '';
  else
    featureString = ',' + featureString;

  var x = Math.round((screen.availWidth - width) / 2);
  var y = Math.round((screen.availHeight - height) / 2);

  featureString = 'left=' + x + ',top=' + y + ',width=' + width + ',height=' + height + featureString;
  return open(url, windowName, featureString);
}

/**
* Submete o formulário a partir de campo Enter Pressionado
* @author Vítor Júnior
* @source Ebook JavaScript & DHTML Cookbook
*/
function submitViaEnter(evt, funcao) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = target.form;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);

	if (charCode == 13 || charCode == 3) {
        // Submete o formulário
	    eval(funcao);
    }
return true;

}

/**
* Função para pegar variável passada via Query String (Método GET)
* @autor Vítor Jr
*/
function getVariavel( variavel ) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var par = vars[i].split("=");
    if (par[0] == variavel) {
      return par[1];
    }
  }
} // fim getVariavel


function chamaTelaOnCLick(nomeClasse, campo1, campo2, codg, descricao, largura, altura) {
	//(!isNaN(codg) &&
	if ((codg !="") && (descricao == "")) { // Busca por código
		abrirNoCentro('control?cmd=' + nomeClasse + '&acao=12&campo1=' + campo1 + '&campo2=' + campo2 + '&buscaPor=CODIGO&busca=' + codg, largura, altura, '', '');
	} else if ((descricao != "") && (codg=="")) { // Busca por Descrição
		abrirNoCentro('control?cmd=' + nomeClasse + '&acao=12&campo1=' + campo1 + '&campo2=' + campo2 + '&buscaPor=DESCRICAO&busca=' + descricao + '&buscaStatus=T&buscaTipo=APROXIMADA', largura, altura, '', '');
	} else { // Busca tudo
		abrirNoCentro('control?cmd=' + nomeClasse + '&acao=12&campo1=' + campo1 + '&campo2=' + campo2, largura, altura, '', '');
	}
    return false;
}

function chamaTelaOnCLickSemCampos(url, width, height, windowName, featureString) {
    if (!windowName)
        windowName = '';
    if (!featureString)
        featureString = '';
    else
        featureString = ',' + featureString;

    var x = Math.round((screen.availWidth - width) / 2);
    var y = Math.round((screen.availHeight - height) / 2);

    featureString = 'left=' + x + ',top=' + y + ',width=' + width + ',height=' + height + featureString;
    window.open(url+ '&opcao='+document.Navegacao.opcao.value, windowName, featureString);

}


function mascara_data(data){
     var mydata = '';
     mydata = mydata + data.value;

	if (mydata.length == 2){
       mydata = mydata + '/';
  		data.value= mydata;
    }

	if (mydata.length == 5){
       mydata = mydata + '/';
	   data.value = mydata;
    }
}


/*
* Função que captura a linha na qual determinado radiobutton está selecionado
* @author Vítor Nogueira da Silva Júnior
*/
function capturarInfoLinhaChecked ( idTabela ) {
	/*
	* O trecho de código abaixo é útil para se capturar informações da GRID
	* de acordo com a linha selecionada.
	*/

	/* Buscando a referência da tabela que contém as informações sobre Assunto */
	tbl = document.getElementById(idTabela);
	linhaDeDados = null;

	/* Percorrendo todas linhas e células para verificar se o elemento CHECKBOX da célula está marcado */
	for(i = 0; i<tbl.rows.length; i++) {
		for(j = 0; j<tbl.rows[i].cells.length; j++) {
			if(tbl.rows[i].cells[j].childNodes.item(0).checked) { // Campo CHECKBOX da célula
				linhaDeDados = tbl.rows[i]; // Refereciando a linha na qual o CheckBox está marcado
			}
		break;
		}
	}

	return linhaDeDados;
}


/**
*  Função para formatar CPF
* @author Vítor Júnior
*/
function formatarCPF( cpf ) {
	
	if (cpf.length == 10) {
		cpf = "0" + cpf;
	} else if (cpf.length == 9) {
		cpf = "00" + cpf;
	} 
	
	return (cpf.substring(0,3) + "." + cpf.substring(3,6) + "." + cpf.substring(6,9) + "-" + cpf.substring(9,11));	

}


function formatarDataAno( campo ) {
	if(campo.value.length == 8) {
	  fcn_dia = campo.value.substring(0,2);
      fcn_mes = campo.value.substring(3,5);
      fcn_ano = campo.value.substring(6,8);
	  campo.value = fcn_dia + "/" + fcn_mes + "/20" + fcn_ano;
	}
}


function diferencaDatas (dataFim, dataInicio ) {

	//var dataFinal = new Date(2006,1,09);    
	//var dataInicial = new Date(2006,1,15);  

    var difference = dataFim.getTime() - dataInicio.getTime();

    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24
    var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60
    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60
    var secondsDifference = Math.floor(difference/1000);

    return daysDifference;

}

function validarEmail(campo) {
	if(campo.value != "") {
		if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(campo.value))) {
			return false;
		}
	}
	return true;
}


function autotab(campoOrigem,campoDestino){
	if ((campoOrigem.getAttribute&&campoOrigem.value.length==campoOrigem.getAttribute("maxlength")))
		campoDestino.focus();
}


function mascaraHorario (horario) {
		var meuhorario = '';
		meuhorario	=	horario.value + meuhorario;
		
		if(meuhorario.length == 2) {
			horario.value = meuhorario + ":";
		} else if (meuhorario.length == 5) {
			hora = meuhorario.substring(0,2);
			minuto = meuhorario.substring(3,5);
			
			if((hora>24 || hora < 0) || ( minuto>60 || minuto < 0 )){
				window.alert('Horário inválido!');
				horario.value = "";
				horario.focus();
			}
			
		}		
}

function validarData( campo ) {
	var re = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
	
	if(campo.value != "") {
		if(!(re.test(campo.value))) {
			return false;
		}
		return true;
	}
	


}



function validarCPF(valor) {

        var i;
        s = valor;
        var c = s.substr(0,9);
        var dv = s.substr(9,2);
        var d1 = 0;
        for (i = 0; i < 9; i++)
        {
            d1 += c.charAt(i)*(10-i);
        }
            if (d1 == 0){
                return false;
            }
        d1 = 11 - (d1 % 11);
        if (d1 > 9) d1 = 0;
        if (dv.charAt(0) != d1)
        {
            return false;
        }

        d1 *= 2;
        for (i = 0; i < 9; i++)
        {
            d1 += c.charAt(i)*(11-i);
        }
        d1 = 11 - (d1 % 11);
        if (d1 > 9) d1 = 0;
        if (dv.charAt(1) != d1){
            return false;
        } 
		
		return true;
}


function formatar(src, mask) 
{
	  var i = src.value.length;
	  var saida = mask.substring(0,1);
	  var texto = mask.substring(i)
		
		if (texto.substring(0,1) != saida) 
		  {
			src.value += texto.substring(0,1);
		  }
}

function TrocarCSS (elem, css) {
	elem.className = css;
}



function SelecionarTodos(campo) {
		var f = document.f1;
		
		for(i=0; i < f.elements.length; i++) {
			if (f.elements[i].name == campo && (f.elements[i].disabled == false)) {
				f.elements[i].checked = true;
			}
		}		
	}
	

function DesmarcarTodos(campo) {
		var f = document.f1;
		
		for(i=0; i < f.elements.length; i++) {
			if (f.elements[i].name == campo && (f.elements[i].disabled == false)) {
				f.elements[i].checked = false;
			}
		}		
	}
	
	
	
function formatarValorMonetario(campooriginal,decimais)
{
  var posicaoPontoDecimal;
  var campo = '';
  var resultado = '';
  var pos,sep,dec;
	
	
	if(campooriginal.value == "" || campooriginal.value == " ") {
		return false;
	}
	
//Retira possiveis separadores de milhar
  for (pos=0; pos < campooriginal.value.length; pos ++)
  {
    if (campooriginal.value.charAt(pos)!='.')
        campo = campo + campooriginal.value.charAt(pos);
  }     

//Formata valor monetário com decimais
  posicaoPontoDecimal = campo.indexOf(',');
  if (posicaoPontoDecimal != -1)
   {
      sep = 0;
      for (pos=posicaoPontoDecimal-1;pos >= 0;pos--)
      {
        sep ++;
        if (sep > 3)
        {
           resultado = '.' + resultado;
           sep = 1;
        }

        resultado = campo.charAt(pos) + resultado;   
      }

      // Trata parte decimal
      if (parseInt(decimais) > 0 )
      {
         resultado = resultado + ',';
      
         pos=posicaoPontoDecimal+1;
         for (dec = 1;dec <= parseInt(decimais); dec++)
         {
           if (pos < campo.length)
           {
              resultado = resultado + campo.charAt(pos);
              pos++;
           }
           else
              resultado = resultado + '0';   
         }

      } // trata decimais
   }
   // Trata valor monetário sem decimais
   else
   {
      sep = 0;
      for (pos=campo.length-1;pos >= 0;pos--)
      {
        sep ++;
        if (sep > 3)
        {
           resultado = '.' + resultado;
           sep = 1;
        }
        resultado = campo.charAt(pos) + resultado;   
      }
      // Trata parte decimal
      if (parseInt(decimais) > 0 )
      {
         resultado = resultado + ',';
         for (dec = 1;dec <= parseInt(decimais); dec++)
         {
              resultado = resultado + '0';   
         }
      } // trata decimais
   }
   campooriginal.value = resultado;
}	

function SelecionarTodosSelect (obj_select ) {
	
		var obj = document.getElementById(obj_select);
		
		if(obj.options.length > 0 ) {
			
			for(i = 0; i<obj.options.length; i++) {
				obj.options[i].selected = true;
			} // fim for
		} // fim se		
	} // fim function
	



function isNumero(valor)
{
	var reDigits = /^\d+$/;
	if (reDigits.test(valor)) {
			return true;
		} else if (valor != null && valor != "") {
			return false;
		}
}




	function VText(campo, msg) {
		var c = document.getElementById(campo);
		if(c.value == "") {
			alert(msg);
			c.focus();
			return false;
		} 
		return true;
	}

	function VCbb(campo, msg) {
		var c = document.getElementById(campo);
		if(c.options[c.selectedIndex].value == "") {
			alert(msg);
			c.focus();
			return false;
		} 
		return true;
	}