<!-- //
//GLOBALS
var w3c = (document.getElementById) ? 1:0
var ns4 = (document.layers) ? 1:0  //browser detect for NS4 & W3C standards
var ns6=(navigator.userAgent.indexOf("Gecko")!=-1)?true:false;
var ns61=(parseInt(navigator.productSub)>=20010726)?true:false;
var hasCookies = false;
var sDisplayBlock = 'block';
if (ns6 || ns61) { var sDisplayBlock = ''; }

//Retirado a pedido do Luciano/Mazza
//Não funciona mais o null no mozilla
//if (ns6 || ns61) { var sDisplayBlock = null; }
var flashTimeOut = null;

var hasCookies = false;

// tests whether the user accepts cookies, and sets a flag.
if(document.cookie == '') {
  document.cookie = 'hasCookies=yes';
  if (document.cookie.indexOf('hasCookies=yes') != -1) hasCookies = true;
}
else hasCookies = true;

var modoCPFCNPJ = "CPF"; // Utilizado nos campos de CPF e CNPJ

/* write correct css info */
//  if (w3c) document.write("<link rel=\"stylesheet\" href=\"../imagens/ditech4.css\" type=\"text/css\">");
//  else if (ns4) document.write("<link rel=\"stylesheet\" href=\"../imagens/ditech_n4.css\" type=\"text/css\">");

function isNum( caractere ) {
  var strValidos = "0123456789";
  if (strValidos.indexOf(caractere) == -1)
    return false;
  return true;
}

function Salva_html() {
  return;
}

// Substitui o conteúdo de um campo pelo resultado da expressão matemática que ele representa.
// Operadores aceitos: +, -, *, /, % (percentual), parênteses
// Autor: Carlos Z. Mazzini
function analisaExpressao(campo, digit) {
  var valor = new String;
  valor = campo.value;
  var Numero = new Number;

  valor = valor.replace(/\s/g, "");
  valor = valor.replace(/[=]/g, "");
  iPos = valor.search(/[^0-9,\.\+\-\*\/\%\(\)]/);
  if (iPos >= 0) {
    alert("Expressão inválida. Utilize somente caracteres numéricos, vírgula ou ponto decimal, parênteses e os operadores +, -, *, /, %");
    campo.focus();
    return false;
  }
  iPos = valor.search(/[,\.\+\-\*\/\%]{2,}/g);
  if (iPos > -1) {
    alert("Expressão inválida. Não é permitida a repetição contígua de operadores");
    campo.focus();
    return false;
  }

  valor = valor.replace(/\%/g, "/100,0*");
  valor = valor.replace(/,/g, ".");
  try {
    campo.value = Math.round(eval(valor) * Math.pow(10, digit)) / Math.pow(10, digit);
  } catch (eW) {
    alert("Expressão inválida.");
    campo.focus();
    return false;
  }
  campo.value = campo.value.replace(/\./g, ",");

  return true;
}

// ************ Grupo de rotinas para tratamento da digitação de datas

// Verifica se a data está correta
function verifica_data(data, sMessage) {
  if (sMessage == undefined || sMessage == null) {
    sMessage = '';
  }

  var mydata = '';
  mydata = data.value.replace(' ', '');
  tam = mydata.length;

  situacao = "";

  if (tam == 7) {
    dia = "01";
    mes = (data.value.substring(0,2));
    ano = (data.value.substring(3,7));
  } else {
    if (tam < 8) { situacao = "falsa"; }
    dia = (data.value.substring(0,2));
    mes = (data.value.substring(3,5));
    ano = (data.value.substring(6,10));
  }

  // verifica o dia valido para cada mes
  if ((dia < 1) || (dia < 1 || dia > 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11 ) || dia > 31) {
    if (dia > 30) { // Supoe q o usuario quer digitar o ultimo dia do mes
      if (mes == 4 || mes == 6 || mes == 9 || mes == 11 ) {
        dia = 30;
      } else {
        dia = 31;
      }
      data.value = dia + '/' + mes + '/' + ano;
      verifica_data(data, sMessage);
      return;
    }
    situacao = "falsa";
  }

  // verifica se o mes e valido
  if (mes < 1 || mes > 12 ) {
    if (mes > 12) { // Se mes maior q 12, setar pra 12 ou setar pra 01
      mes = '12';
    } else {
      mes = '01';
    }
    if (tam == 7) {
      data.value = mes + '/' + ano;
    } else {
      data.value = dia + '/' + mes + '/' + ano;
    }
    verifica_data(data, sMessage);
    return;
//      situacao = "falsa";
  }

  // verifica se e ano bissexto
  if (mes == 2 && ( dia < 1 || dia > 29 || (dia > 28 && (parseInt(ano / 4) != ano / 4)))) {
    if (parseInt(ano / 4) != ano / 4) {// Forcando a data a ser valida
      dia = 28;
    } else {
      dia = 29;
    }
    if (tam == 7) {
      data.value = mes + '/' + ano;
    } else {
      data.value = dia + '/' + mes + '/' + ano;
    }
    verifica_data(data, sMessage);
    return;

//      situacao = "falsa";
  }

  if (data.value == "") {
    situacao = "falsa";
  }

  if (situacao == "falsa") {
    if (sMessage != '') {
      alert(sMessage);
    } else {
      alert("Data inválida!");
    }
    data.focus();
    data.select();
  }
}

// Datas em formato dd/mm/aaaa
// Para utilizá-las, devem ser associadas com os seguintes eventos:
//   onKeyDown  - trataDataBS(this, event)
//   onKeyPress - validaTeclaData(this, event)
//   onKeyUp    - mascara_data(this, event)
//   onBlur     - completa_ano(this)
function trataDataBS(campo, event) {
  var tecla;
  var BACKSPACE = 8;

  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla = event.which;
  else
    tecla = event.keyCode;

  if ((tecla == BACKSPACE) && ((campo.value.slice(-1) == '/') || (campo.value.slice(-1) == '-')))
    campo.value = campo.value.slice(0, -1);
}

function validaTeclaData(campo, event) {
  var ENTER = 13;
  var BACKSPACE = 8;
  var key;
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla= event.which;
  else
    tecla= event.keyCode;

  key = String.fromCharCode(tecla);

  // COMENTADO - Rodrigo - 29/07/2003
  // COMENTADO - Cícero - 07/07/2009
  //if (tecla == ENTER) {
  //  campo.blur();
  //  window.setTimeout("document." + campo.form.name + ".submit()", 500);
  //  return false;
  //}

  if (tecla == BACKSPACE) {
    if ((campo.value.slice(-1) == '/') || (campo.value.slice(-1) == '-'))
      campo.value = campo.value.slice(0, -1);
    return true;
  }

  if ((tecla == 0) || isNum(key))
    return true;

  return false;
}

function mascara_data(dataField, event) {
  var data = dataField.value;
  var mydata = '';
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla = event.which;
  else
    tecla = event.keyCode;
  if ((tecla == 9) || (tecla == 16))
    return true;

  data = data.replace(/[^0-9]/g, "");
  if (data.length > 0) {
    mydata = data.slice(0, 2);
    if (data.length > 1) {
      mydata = mydata + '/';
      if (data.length > 2) {
        mydata = mydata + data.slice(2, 4);
        if (data.length > 3) {
          mydata = mydata + '/';
          if (data.length > 4) {
            mydata = mydata + data.slice(4, 8);
          }
        }
      }
    }
  }
  dataField.value = mydata;
}

function completa_ano(dataField) {
  var data = dataField.value;
  var mydata = '';

  mydata = mydata + data;
  diames = (dataField.value.substring(0,6));

  if (mydata.length == 8) {
    ano = (dataField.value.substring(6,8));
    if (ano > 20) {
      dataField.value = diames + "19" + ano;
    } else {
      dataField.value = diames + "20" + ano;
    }
  } else if (mydata.length == 6) {
    ano = (dataField.value.substring(6,8));
    Today = new Date();
    dataField.value = diames + Today.getFullYear();
  }

  if (mydata.length != 0) {
    verifica_data(dataField);
  }
}

// Datas em formato mm/aa ou mm/aaaa
// Para utilizá-las, devem ser associadas com os seguintes eventos:
//   onKeyDown  - trataDataBS(this, event)
//   onKeyPress - validaTeclaData(this, event)
//   onKeyUp    - mascara_dataMeA(this, event)
//   onBlur     - completa_anoMeA(this)
function mascara_dataMeA(dataField, event) {
  var data = dataField.value;
  var mydata = '';
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla = event.which;
  else
    tecla = event.keyCode;
  if ((tecla == 9) || (tecla == 16))
    return true;

  data = data.replace(/[^0-9]/g, "");
  if (data.length > 0) {
    mydata = data.slice(0, 2);
    if (data.length > 1) {
      mydata = mydata + '/';
      if (data.length > 2) {
        mydata = mydata + data.slice(2, 6);
      }
    }
  }
  dataField.value = mydata;
}

function completa_anoMeA(dataField, sMessage) {
  if (sMessage == undefined || sMessage == null) {
    sMessage = '';
  }

  var data = dataField.value;
  var mydata = '';

  mydata = mydata + data;
  mes = (dataField.value.substring(0, 3));

  if (mydata.length == 5) {
    ano = (dataField.value.substring(3, 5));
    if (parseInt(ano) > 69) {
      dataField.value = mes + "19" + ano;
    } else {
      dataField.value = mes + "20" + ano;
    }
  } else if (mydata.length == 3) {
    //ano = (dataField.value.substring(6, 8));
    Today = new Date();
    dataField.value = mes + Today.getFullYear();
  }

  if (mydata.length != 0) {
    verifica_data(dataField, sMessage);
  }
}

// Datas em formato semana/aa ou semana/aaaa
// Para utilizá-las, devem ser associadas com os seguintes eventos:
//   onKeyDown  - trataDataBS(this, event)
//   onKeyPress - validaTeclaData(this, event)
//   onKeyUp    - mascara_dataSemA(this, event)
//   onBlur     - completa_anoSemA(this)

function mascara_dataSemA(dataField, event) {
  var data = dataField.value;
  var mydata = '';
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla = event.which;
  else
    tecla = event.keyCode;
  if ((tecla == 9) || (tecla == 16))
    return true;

  data = data.replace(/[^0-9]/g, "");
  if (data.length > 0) {
    mydata = data.slice(0, 2);
    if (data.length > 1) {
      mydata = mydata + '/';
      if (data.length > 2) {
        mydata = mydata + data.slice(2, 6);
      }
    }
  }
  dataField.value = mydata;
}

function completa_anoSemA(dataField) {
  if (dataField.length == 0)
    return false;

  semana = (dataField.value.substring(0, 2));
  ano    = (dataField.value.substring(3, 7));

  if (semana < 1) {
    semana = '01';
  } else if (semana > 53) {
    semana = '53';
  } else if (semana.length < 2) {
    semana = '0' + semana;
  }

  if (ano.length == 0) {
    dtHoje = new Date();
    ano    = dtHoje.getFullYear();
  } else if (ano.length < 4) {
    if (ano > 20) {
      ano = "19" + ano;
    } else {
      ano = "20" + ano;
    }
  }

  dataField.value = semana + '/' + ano;

  return verificaSemana(dataField);
}

// Verifica se uma data no formato semana/ano está correta
function verificaSemana(data) {
  var mydata = '';
  var DataCorreta = 't';

  mydata = data.value.replace(' ', '');
  tam    = mydata.length;

  if (tam != 7) {
    alert("Semana inválida!");
    data.focus();
    data.select();
    return false;
  }

  return true;
}

// Sets a date field function. Works in together with calendar.php. The id parameter is the element id of the input field to be filled with a date. alex@ditech.com.br. 05/15/2004
function openCalendar(id) {
  var width = 130;
  var height = 160;
  var top = 400;
  var left = 400;
  aData = document.getElementById(id).value.split('/');
  iDia = aData[0];
  iMes = aData[1];
  iAno = aData[2];
  sData = iMes+'/'+iDia+'/'+iAno;

  oInput = document.getElementById(id);
  oDiv   = document.getElementById(id+'div');
  oFrame = document.getElementById(id+'frame');

  //document.getElementById(id+'frame').src = '../inc/calendar.php?dateField='+id+'&dateValue='+document.getElementById(id).value;
  oFrame.src = '../inc/calendar.php?dateField='+id+'&dateValue='+sData;
  oDiv.style.display = sDisplayBlock;

  iOffsetLeftInput = getOffsetLeft(oInput);
  iOffsetLeftDiv   = getOffsetLeft(oDiv);
  iOffsetTopInput  = getOffsetTop(oInput);
  iOffsetTopDiv    = getOffsetTop(oDiv);

  /*alert('Pagina ' + document.body.offsetWidth +'\n'
        + 'Input ' + oInput + '\n'
        + 'Div ' + oDiv + '\n'
        + 'FR ' + oFrame + '\n'
        + 'OffsetLeftInput ' + iOffsetLeftInput + '\n'
        + 'OffsetleftDiv ' + iOffsetLeftDiv + '\n'
        + 'OffsetTopInput ' + iOffsetTopInput + '\n'
        + 'OffsetTopDiv ' + iOffsetTopDiv + '\n'
        + 'Div offsetHeight ' + oDiv.offsetHeight + '\n'
        + 'Input offsetHeight ' + oInput.offsetHeight + '\n'
        + 'Div offsetWidth ' + oDiv.offsetWidth + '\n'
        );
  */
  if ((iOffsetLeftDiv + oDiv.offsetWidth) >= document.body.offsetWidth) { // sem espaco a direita
    //alert(document.body.offsetWidth + ' ' + iOffsetLeftDiv + ' ' + oDiv.offsetWidth);
    if (ns6) {
      oDiv.style.left = iOffsetLeftInput;
    } else {
      oDiv.style.left = document.body.offsetWidth - oDiv.offsetWidth - 20;
    }
    if ((iOffsetTopDiv + oDiv.offsetHeight) > document.body.offsetHeight) { // sem espaco embaixo, joga para cima
      oDiv.style.top = iOffsetTopInput - oDiv.offsetHeight;
    } else { // com espaco embaixo
      oDiv.style.top = iOffsetTopInput + oInput.offsetHeight;
    }
  } else { // com espaço a direita
    if ((iOffsetTopDiv + oDiv.offsetHeight) > document.body.offsetHeight) { // sem espaco embaixo, joga para cima
      oDiv.style.top = iOffsetTopInput - oDiv.offsetHeight;
    }
  }
}

// Hide flash calendar
function hideCalendar(id) {
  //document.getElementById(id).style.display = 'none';
}

// ******** Fim das rotinas de tratamento da digitação de datas *****************

// ************ Grupo de rotinas para tratamento da digitação de horas:minutos

// Verifica se a hora está correta
function verifyTime(sTime, sErrorMessage) {
  var myTime = '';
  myTime = sTime.value.replace(' ', '');
  tam = myTime.length;

  situacao = "";

  if (tam < 5) { situacao = "falsa"; }
  hour = (sTime.value.substring(0, 2));

  if (sTime.value.length > 4) {
    minute = (sTime.value.substring(3, 5));
  } else {
    minute = (sTime.value.substring(2, 4));
  }

  // verifica se a hora está correta
  if (hour < 0 || hour > 24) {
    sTime.value = '';
    sTime.focus();
    sTime.select();
    if (sErrorMessage) {
      alert(String.fromCharCode(10) + sErrorMessage + String.fromCharCode(10));
    } else {
      alert(String.fromCharCode(10) + 'Uma hora inválida foi especificada: ' + myTime + String.fromCharCode(10) + String.fromCharCode(10) + 'A hora deve estar no intervalo de 00:00 a 23:59 e formatada como HH:MM' + String.fromCharCode(10) + String.fromCharCode(10) + 'HH deve estar no intervado de 00 a 23. MM deve estar no intervalo de 00 a 59');
    }
    return false;
  }

  // verifica se o minuto é válido
  if (minute < 0 || minute > 59 || (hour == 24 && minute > 0)) {
    sTime.value = '';
    sTime.focus();
    sTime.select();
    if (sErrorMessage) {
      alert(String.fromCharCode(10) + sErrorMessage + String.fromCharCode(10));
    } else {
      alert(String.fromCharCode(10) + 'Um minuto inválida foi especificada: ' + myTime + String.fromCharCode(10) + String.fromCharCode(10) + 'A hora deve estar no intervalo de 00:00 a 23:59 e formatada como HH:MM' + String.fromCharCode(10) + String.fromCharCode(10) + 'HH deve estar no intervado de 00 a 23. MM deve estar no intervalo de 00 a 59');
    }
    return false;
  }

  if (sTime.value == "") {
    sTime.value = '';
    sTime.focus();
    sTime.select();
    if (sErrorMessage) {
      alert(String.fromCharCode(10) + sErrorMessage + String.fromCharCode(10));
    } else {
      alert(String.fromCharCode(10) + 'Uma hora inválida foi especificada: ' + myTime + String.fromCharCode(10) + String.fromCharCode(10) + 'A hora deve estar no intervalo de 00:00 a 23:59 e formatada como HH:MM' + String.fromCharCode(10) + String.fromCharCode(10) + 'HH deve estar no intervado de 00 a 23. MM deve estar no intervalo de 00 a 59');
    }
    return false;
  }

  return true;
}

function maskTime(timeField, event, bUseColon, iDigitosHora, sDirecao) {
  var sTime = timeField.value;
  var myTime = '';
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape") != -1)
    tecla = event.which;
  else
    tecla = event.keyCode;
  if ((tecla == 9) || (tecla == 16))
    return true;

  sTime = sTime.replace(/[^0-9]/g, "");
  if (sTime.length > 0) {
    //Se o preenchimento será da direita para a esquerda
    //Priorisando os minutos
    if (sDirecao == 'D') {
      myTime = sTime.slice(sTime.length - 2, sTime.length);
      if (sTime.length > 2) {
        if (bUseColon) {
          myTime = ':' + myTime;
        }
        if (sTime.length > 2) {
          myTime = sTime.slice(0, sTime.length - 2) + myTime;
        }
      }
    } else {
      //Se o preenchimento será da esquerda para a direita
      //Priorisando as horas
      myTime = sTime.slice(0, iDigitosHora);
      if (sTime.length + 1 > iDigitosHora) {
        if (bUseColon) {
          myTime = myTime + ':';
        }
        if (sTime.length + 1 > iDigitosHora) {
          myTime = myTime + sTime.slice(iDigitosHora, iDigitosHora + 2);
        }
      }
    }
  }
  timeField.value = myTime;
}

// Horas em formato hh:mm
// Para utilizá-las, devem ser associadas com os seguintes eventos:
//   onKeyDown  - treatTimeBS(this, event)
//   onKeyPress - validateKeyTime(this, event, bAcceptOnlyQuarterTime)
//   onKeyUp    - maskTime(this, event, bUseColon)
//   onBlur     - completeTime(this)
function treatTimeBS(field, event) {
  var tecla;
  var BACKSPACE = 8;

  if(navigator.appName.indexOf("Netscape") != -1)
    tecla = event.which;
  else
    tecla = event.keyCode;

  if ((tecla == BACKSPACE) && ((field.value.slice(-1) == ':')))
    field.value = field.value.slice(0, -1);
}

function validateKeyTime(field, event, bAcceptOnlyQuarterTime) {
  var ENTER = 13;
  var BACKSPACE = 8;
  var key;
  var tecla;

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape") != -1)
    tecla= event.which;
  else
    tecla= event.keyCode;

  key = String.fromCharCode(tecla);

  if (tecla == ENTER) {
    field.blur();
    //window.setTimeout("document." + field.form.name + ".submit()", 500);
    return false;
  }

  if (tecla == BACKSPACE) {
    if (field.value.slice(-1) == ':')
      field.value = field.value.slice(0, -1);
    return true;
  }

  if ((tecla == 0) || isNum(key)) {
    if (bAcceptOnlyQuarterTime && field.value.length >= 2) {
      if (field.value.substr(2, 1) == ':') {
        iPosMin1 = 3;
        iPosMin2 = 4;
      } else {
        iPosMin1 = 2;
        iPosMin2 = 3;
      }
      if (field.value.length == iPosMin1) {
        if (key == '0' || key == '1' || key == '3' || key == '4') {
          return true;
        } else {
          return false;
        }
      }
      if (field.value.length == iPosMin2) {
        if (key == '0' || key == '5') {
          if (key == '0' && (field.value.substr(iPosMin1, 1) == '0' || field.value.substr(iPosMin1, 1) == '3')) {
            return true;
          }
          if (key == '5' && (field.value.substr(iPosMin1, 1) == '1' || field.value.substr(iPosMin1, 1) == '4')) {
            return true;
          }
          return false;
        } else {
          return false;
        }
      }
    }
    return true;
  }

  return false;
}

/*
function checkTime(timeField, sErrorMessage, sDirecao) {
  var sTime = timeField.value;
  var myTime = '';

  myTime = myTime + sTime;

  if (myTime.length != 0) {
    verifyTime(timeField, sErrorMessage);
  }
}
*/
function checkTime(timeField, event, bUseColon, iDigitosHora, sDirecao) {
  var sTime = timeField.value;
  if (sDirecao == 'D') {
    /*if (sTime.length < iDigitosHora + 3) {
      for (i = sTime.length; i < (iDigitosHora + 2); i++) {
        sTime = '0' + sTime;
      }
    }  */
    if (sTime.length < 3) {
      for (i = sTime.length; i < 3; i++) {
        sTime = '0' + sTime;
      }
    }
  } else {
    if (sTime.length < iDigitosHora + 3) {
      for (i = sTime.length; i < (iDigitosHora + 3); i++) {
        sTime = sTime + '0';
      }
    }
  }
  timeField.value = sTime;
  maskTime(timeField, event, bUseColon, iDigitosHora, sDirecao);
  if (iDigitosHora <= 2) {
    if (verifyTime(timeField) == false) {
      timeField.value = '';
      timeField.focus();
      timeField.select();
    }
  } else {
    sTime = timeField.value;
    if (bUseColon) {
      aTime = sTime.split(':');
      iMinuto = parseInt(aTime[1]);
    } else {
      iMinuto = parseInt(sTime.slice(sTime.length - 2, sTime.length));
    }

    if (iMinuto > 59) {
      alert('Os minutos informados são maiores do que o permitido (60) : ' + iMinuto);
      timeField.value = '';
      timeField.focus();
      timeField.select();
    }
  }
}
// ******** Fim das rotinas de tratamento da digitação de horas:minutos *****************

function validaTecla(campo, event, sCharVal) {
  var BACKSPACE = 8;
  var VIRGULA = 44;
  var PONTO = 46;
  var MENOS = 45;
  var key;
  var tecla;

  CheckTAB=true;
  if (navigator.appName.indexOf("Netscape") != -1)
    tecla = event.which;
  else
    tecla = event.keyCode;
  key = String.fromCharCode(tecla);

  // COMENTADO - Cícero - 07/07/2009
  //if (tecla == 13) {
  //  campo.blur();
  //  if (campo.form.name) {
  //    window.setTimeout("document." + campo.form.name + ".submit()", 500);
  //  }
  //  return false;
  //}

  // Obtém o tamanho do texto selecionado
  if (document.getSelection) {
    iTamSel = campo.selectionEnd - campo.selectionStart;
  } else if (document.selection) {
    txt = document.selection.createRange().text;
    iTamSel = txt.length;
  }

  if ((key == '=') && (iTamSel == campo.value.length))
    return true;

  if (sCharVal == undefined) {
    sCharVal = '0-9,\\.';
  }

  if (campo.value.slice(0, 1) == '=') {

    // Tratamento de expressões
    if ((campo.TamanhoOriginal == null) || (campo.TamanhoOriginal == 0)) {
      campo.TamanhoOriginal = campo.maxLength;
      campo.maxLength = 200;
    }

    iPos = key.search(/[^0-9,\.\t\r\b\+\-\*\/\%\(\)\000]/);
    return (iPos < 0);

  } else {

    // Tratamento de números puros
    sMascChar = '/[^' + sCharVal + '\\t\\r\\b\\000]/';

    if (tecla == 0)
      return true;

    if ((tecla == VIRGULA) || (tecla == PONTO)) {
      return ((campo.value.indexOf(',') == -1) && (campo.value.indexOf('.') == -1) && (campo.value.length > 0));
    }

    if (tecla == MENOS)
      return ((campo.value.length == 0) || (iTamSel == campo.value.length));

    iPos = eval('key.search(' + sMascChar + ')');
    return (iPos < 0);

  }
}

// Não permite que sejam digitadas as TECLAS escolhidas num determinado campo
// Rodrigo Peixoto Reis - 11/07/2003
function validaTexto(campo, event) {
  var ENTER = 13;
  var BARRA_INVERTIDA = 92;

  tecla = (navigator.appName.indexOf("Netscape")!= -1) ? event.which : event.keyCode;
  key = String.fromCharCode(tecla);
  if (tecla == ENTER) {
    return false;
  }
  if (tecla == BARRA_INVERTIDA) { // cadastro de diretórios no GED
    return false;
  }
  return true;
}

function mascara_ciccnpj(data) {
  var mydata = '';
  mydata = data.value;
  mydata = mydata.replace(/\.|\/|-|/g,'');

  tam = mydata.length;

  if (tam < 1) return;

  if (!VerificaCPFCNPJ(mydata)) {
    alert ("CPF ou CNPJ Inválido!");
    data.focus();
    data.select();
    return;
  }

  if (tam == 11) {
    data.value = mydata.substr(0,3) + '.' + mydata.substr(3,3) + '.' + mydata.substr(6,3) + "-" + mydata.substr(9,2);
    modoCPFCNPJ = "CPF";
  }
  if (tam == 14) {
    data.value = mydata.substr(0,2) + '.' + mydata.substr(2,3) + '.' + mydata.substr(5,3) + "/" + mydata.substr(8,4) + "-" + mydata.substr(12,2);
    modoCPFCNPJ = "CNPJ";
  }
}

function remove_mascara_ciccnpj(data) {
  data.value = data.value.replace(/\.|\/|-|/g,'');
}

function ValidaTeclaCPF(campo, event, tamanho) {
  var ENTER = 13;
  var BACKSPACE = 8;
  var key;
  var tecla;

  if (tamanho != 14) { tamanho = 18; }

  CheckTAB=true;
  if(navigator.appName.indexOf("Netscape")!= -1)
    tecla = event.which;
  else
    tecla = event.keyCode;

  key = String.fromCharCode(tecla);

  if (tecla == BACKSPACE) {
    if ((campo.value.slice(-1) == '/') || (campo.value.slice(-1) == '-') || (campo.value.slice(-1) == '.'))
      campo.value = campo.value.slice(0, -1);
    return true;
  }

  if ((tecla != 0) && (!isNum(key))) {
    event.returnValue = false;
    return false;
  }

  modoValido = false;
  if(campo.value.length>14) { modoCPFCNPJ = "CNPJ"; }
  if(modoCPFCNPJ=="CPF") { modoValido = true; }
  if(modoCPFCNPJ=="CNPJ") { modoValido = true; }
  if(!modoValido) { modoCPFCNPJ = "CPF"; }
  if(tamanho == 14) { modoCPFCNPJ = "CPF"; }
  if(modoCPFCNPJ=="CPF") {
    // Considerando como um CPF
    if((campo.value.length==3)||(campo.value.length==7))
      campo.value=campo.value + ".";
    else {
      if(campo.value.length==11) { campo.value=campo.value + "-"; }
    }
    if(campo.value.length>=14) {
      if(tamanho != 14) {
        // Detectou que é um CNPJ
        modoCPFCNPJ = "CNPJ";
        CNPJ=campo.value + String.fromCharCode(tecla);
        re = /\./g;
        CNPJ=CNPJ.replace(re, "");
        re = /-/g;
        CNPJ=CNPJ.replace(re, "");
        CNPJaux=CNPJ.substr(0, 2) + ".";
        if(CNPJ.length>2) { CNPJaux=CNPJaux + CNPJ.substr(2, 3) + "."; }
        if(CNPJ.length>5) { CNPJaux=CNPJaux + CNPJ.substr(5, 3) + "/"; }
        if(CNPJ.length>8) { CNPJaux=CNPJaux + CNPJ.substr(8, 4) + "-"; }
        if(CNPJ.length>12) { CNPJaux=CNPJaux + CNPJ.substr(12, 2); }
        campo.value=CNPJaux;
        event.returnValue = false;
      }
    }
  } else {
    // Considerando como um CNPJ
    if((campo.value.length==2)||(campo.value.length==6)) {
      campo.value=campo.value + ".";
    } else {
      if(campo.value.length==10) { campo.value=campo.value + "/"; }
      if(campo.value.length==15) { campo.value=campo.value + "-"; }
    }
  }
}

function mascara_valor(num) {
  num = num.toString().replace(/\$|\./g,'');
  num = num.toString().replace(/\$|\,/g,'.');

  if(isNaN(num))
    num = "0";

  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;

  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+'.'+ num.substring(num.length-(4*i+3));

  return (((sign)?'':'-') + num + ',' + cents);
}

function setVariables() {
  if (document.layers) {
    v=".top=";
    dS="document.";
    sD="";
    y="window.pageYOffset + 50";
  } else if (document.all) {
    v=".pixelTop=";
    dS="";
    sD=".style";
    y="document.body.scrollTop + 50";
  } else if (document.getElementById) {
    y="window.pageYOffset + 50";
  }
}

function checkLocation() {
  objectName="calcula";
  yy=eval(y);
  if (document.getElementById) {
    document.getElementById(objectName).style.top=yy;
  } else {
    eval(dS+objectName+sD+v+yy);
  }
  setTimeout("checkLocation()",10);
}

// returns an object reference.
function getObject(obj) {
  if (w3c)
    var theObj = document.getElementById(obj);
  else
    if (ns4)
      var theObj = eval("document." + obj);
  return theObj;
}

// swaps text in a layer.
function swapText(text, divID, innerDivID) {
  //var content = "<span class=\"commandDesc\">" + text + "</span>";

  // MODIFICAÇÃO BY RODRIGO
  // 12/08/2003
  // não usa o DIV, agora usa um textBox

  var objTXT = getObject(divID+'TXTbox');
  if (objTXT != undefined) {
    objTXT.value = text;
  }
  /*
  if (w3c) {
    var theObj = getObject(divID);
    if (theObj) theObj.innerHTML = text;
  } else if (ns4) {
    var innerObj = divID + ".document." + innerDivID;
    var theObj = getObject(innerObj);
    if (theObj) {
      theObj.document.open();
      theObj.document.write(content);
      theObj.document.close();
    }
  }
  */
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;
  if(!d) d=document;
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document;
    n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n];
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n);
  return x;
}

// sets a cookie in the browser.
function setCookie (name, value, hours, path) {
  if (hasCookies) {
    if(hours) {
      if ( (typeof(hours) == 'string') && Date.parse(hours) ) var numHours = hours;
      else if (typeof(hours) == 'number') var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
    }
  document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'');
  }
}

// reads a cookie from the browser
function readCookie(name) {
  if (document.cookie == '') return '';
  else {
    var firstChar, lastChar;
    var theBigCookie = document.cookie;
    firstChar = theBigCookie.indexOf(name);
    if (firstChar != -1) {
        firstChar += name.length + 1;
        lastChar = theBigCookie.indexOf(';', firstChar);
        if (lastChar == -1) lastChar = theBigCookie.length;
        return unescape(theBigCookie.substring(firstChar, lastChar));
    }
    else return '';
  }
}

function toggleFoldyPersistState(divID) {
  var theCookie = readCookie(divID);
  var state="e";
  if ((theCookie == "e") || (theCookie == "")) {
    state="c";
  }
  setCookie(divID,state,'Wed 01 Jan 2020 00:00:00 GMT','/');
  return state;
}

function showHideModule(divID) {
  //var state = toggleFoldyPersistState(divID);
  var ok=false;
  if(w3c) {
    var divIDobj = MM_findObj(divID);
    //var tlobj = MM_findObj(divID+"Tl");
    var toggleobj = MM_findObj(divID+"Toggle");
    //if(divIDobj != null && tlobj != null && toggleobj != null)
    if(divIDobj != null && toggleobj != null) {
      ok=true;

      if (toggleobj.src.indexOf("fechada") == -1) {
        //tlobj.src = "../imagens/pixel_16_g.gif";
        toggleobj.src = "../imagens/tabela_fechada.gif";
        divIDobj.style.display = "none";
      }
      else {
        //tlobj.src = "../imagens/spacer.gif";
        toggleobj.src = "../imagens/tabela_aberta.gif";
        divIDobj.style.display = "";
      }
    }
  }
  if(!ok) {
    document.location = document.location;
  }
  window.focus();
}

function showHideModulePrime(divID) {
  var state = readCookie(divID);
  var ok=false;
  if(w3c) {
    var divIDobj = MM_findObj(divID);
    var tlobj = MM_findObj(divID+"Tl");
    var toggleobj = MM_findObj(divID+"Toggle");
    if(divIDobj != null && tlobj != null && toggleobj != null) {
      ok=true;
      if(state=="c") {
        tlobj.src = "../imagens/pixel_16_g.gif";
        toggleobj.src = "../imagens/tabela_fechada.gif";
        divIDobj.style.display = "none";
      }
      else {
        tlobj.src = "../imagens/spacer.gif";
        toggleobj.src = "../imagens/tabela_aberta.gif";
        divIDobj.style.display = "";
      }
    }
  }
  if(!ok) {
    document.location = document.location;
  }
}

function MM_doButtonAction(frm, action, selectedItems) {
  // THESE MUST BE IN SYNC WITH ListModuleTagBase.java
  var SELECTIONPARAMNAME = 'id';
  var SELECTIONPARAMDELIMITER = '**';
  var params = new String();

  // If the action is a javascript action (starts with 'javascript')
  // then execute it immediately.

  if ((action.indexOf('javascript') == 0) || (action.indexOf('Javascript') == 0)) {
    if (selectedItems) {
      for (i = 0; i < selectedItems.length; i++) {
        if (i > 0)
          params = params.concat("**");

        params = params.concat(selectedItems[i]);
      }
      eval("frm."+frm.name+"ID.value = '"+params+"';");
    }
    eval(action);
  }
  else {
    var okay = true;
    // if action starts with "function:" call the function on the selection to see
    // if we can continue
    if ((action.indexOf('function:') == 0)) {
      okay = false;
      var idx = action.indexOf(":");
      if(idx + 1 < action.length) {
        action = action.substr(idx+1);
        idx = action.indexOf(",");
        if(idx + 1 < action.length) {
          var fxn = action.substr(0, idx);
          action = action.substr(idx+1);
          fxn = eval(fxn);
          if(typeof(fxn) == "function") {
            okay = fxn(selectedItems);
          }
        }
      }
    }

    if(okay) {
      if (selectedItems) {
        for (i = 0; i < selectedItems.length; i++) {
          if (i > 0)
            params = params.concat("**");

          params = params.concat(selectedItems[i]);
        }
      }

      var url = action;

      if (params.length > 0) {
        if (url.indexOf('?') == -1)
          url = url + '?';
        else
          url = url + '&';

        url = url + 'id=' + params;
      }

      window.location = url;
    }
  }
}

function MMCommandButton_update(selectedItems) {
  if (this.mEnableOn == true) {
    if (selectedItems.length == 0) {
      if (this.mEnableOnNoSelection == true) {
        document[this.mName].src = this.mEnabledImage;
        this.mEnabled = true;
      }
      else {
        document[this.mName].src = this.mDisabledImage;
        this.mEnabled = false;
      }
    }

    if (selectedItems.length == 1) {
      if (this.mEnableOnSingleSelection == true) {
        document[this.mName].src = this.mEnabledImage;
        this.mEnabled = true;
      }
      else {
        document[this.mName].src = this.mDisabledImage;
        this.mEnabled = false;
      }
    }

    if (selectedItems.length > 1) {
      if (this.mEnableOnMultipleSelection == true) {
        document[this.mName].src = this.mEnabledImage;
        this.mEnabled = true;
      }
      else {
        document[this.mName].src = this.mDisabledImage;
        this.mEnabled = false;
      }
    }
  }
  else {
    document[this.mName].src = this.mDisabledImage;
    this.mEnabled = false;
  }
}

function MMCommandButton_over() {

  if (this.mEnabled) {
    document[this.mName].src = this.mOverImage;
  }
  swapText(this.mAltText, this.mForm.tt, this.mForm.tt + "i");
}

function MMCommandButton_out() {

  if (this.mEnabled) {
    document[this.mName].src = this.mEnabledImage;
  }
  swapText('', this.mForm.tt, this.mForm.tt + "i");
}

function MMCommandButton_click() {
  if (this.mEnabled) {
    MM_doButtonAction(this.mForm, this.mAction, this.mForm.selectedItems);
  }
  swapText('', this.mForm.tt, this.mForm.tt + "i");
}

function MMCommandButton(name,
                         form,
                         action,
                         enabledImage,
                         overImage,
                         disabledImage,
                         enableOn,
                         enableOnNoSelection,
                         enableOnSingleSelection,
                         enableOnMultipleSelection,
                         altText) {
  this.mName                      = name;                      // Name of the image
  this.mForm                      = form;                      // The form object enclosing this button (to retrieve selections)
  this.mAction                    = action;                    // Action to perform when clicking
  this.mEnabledImage              = enabledImage;              // enabled image (String)
  this.mOverImage                 = overImage;                 // over image (String)
  this.mDisabledImage             = disabledImage;             // disabled image (String)
  this.mEnableOn                  = enableOn;                  // função autorizada ou não
  this.mEnableOnNoSelection       = enableOnNoSelection;
  this.mEnableOnSingleSelection   = enableOnSingleSelection;
  this.mEnableOnMultipleSelection = enableOnMultipleSelection;
  this.mAltText                   = altText;
  this.mEnabled                   = false;

  this.update = MMCommandButton_update;
  this.over   = MMCommandButton_over;
  this.out    = MMCommandButton_out;
  this.click  = MMCommandButton_click;
}

function MM_getButtonWithName(form, buttonName) {
  if (form.buttons) {
    var buttonCount = form.buttons.length;

    for (i = 0; i < buttonCount; i++) {
      var button = form.buttons[i];
      if (button.mName == buttonName) {
        return button;
      }
    }
  }
  return null;
}

function MM_updateButtons2(form, selectedItems) {
  if (form.buttons) {
    var buttonCount = form.buttons.length;

    for (i = 0; i < buttonCount; i++) {
      var button = form.buttons[i];
      if (button) {
        button.update(selectedItems);
      }
    }
  }
}

function MM_updateButtons(form) {
  var dummy = new Array();
  MM_updateButtons2(form, dummy);
}


function MMCheckbox(name, form, imageName) {
  // The mName is the name of the checkbox that is passed on via POST
  this.mName = name;
  this.mForm = form;
  this.mImageName = imageName;
}

/**
* Seleciona todos os itens de uma lista de registro (marca os checkbox associados).
*
* @param form Form que contem os registros.
* @param ckBoxAll Id do checkbox no cabecalho da lista.
*/
function MM_selectAllItems(form, ckBoxAll) {
  imgCkBoxOn = new Image(16,14)
  imgCkBoxOn.src = '../imagens/checkbox_on.gif'
  form.selectedItems = new Array();

  if (form.checkboxes) {
    var checkboxCount = form.checkboxes.length;
    for (i = 0; i < checkboxCount; i++) {
      var checkbox = form.checkboxes[i];
      form.selectedItems[form.selectedItems.length] = checkbox.mName;
      if(document[checkbox.mImageName]) document[checkbox.mImageName].src = imgCkBoxOn.src
    }
  }

  if(ckBoxAll != null) {
    ckBoxAllImg = document.getElementById(ckBoxAll)
    if(ckBoxAllImg) {
      ckBoxAllImg.src = imgCkBoxOn.src
    } else {
      alert('Warning: Invalid identifier for checkbox ALL: ' + ckBoxAll)
    }
  } else if (document[form.tt + "cb"]) {
    document[form.tt + "cb"].src = imgCkBoxOn.src
  }

  MM_updateButtons2(form, form.selectedItems);
}

/**
* Deseleciona todos os itens de uma lista de registros (desmarca os checkbox associados).
*
* @param Form que contem os registros.
* @param string ckBoxAll Id do checkbox no cabecalho da lista.
*/
function MM_deselectAllItems(form, ckBoxAll) {
  imgCkBoxOff = new Image(16,14)
  imgCkBoxOff.src = '../imagens/checkbox_off.gif'
  form.selectedItems = new Array();

  if (form.checkboxes) {
    var checkboxCount = form.checkboxes.length;
    for (i = 0; i < checkboxCount; i++) {
      var checkbox = form.checkboxes[i];
      if (document[checkbox.mImageName]) document[checkbox.mImageName].src = imgCkBoxOff.src;
    }
  }

  if(ckBoxAll != null) {
    ckBoxAllImg = document.getElementById(ckBoxAll)
    if(ckBoxAllImg) {
      ckBoxAllImg.src = imgCkBoxOff.src
    } else {
      alert('Warning: Invalid identifier for checkbox ALL: ' + ckBoxAll)
    }
  } else if (document[form.tt + "cb"]) {
    document[form.tt + "cb"].src = imgCkBoxOff.src;
  }

  MM_updateButtons2(form, form.selectedItems);
}

/**
* If all items are selected, deselect all. Otherwise select all.
*
* @param form Form object that hold the list checkboxes to select/deselect.
* @param string ckBoxAll Checkbox select/deselect image id. This param is used to change the checkbox image on list header.
*/
function MM_toggleSelectedItems(form, ckBoxAll) {
  if (!form.selectedItems)
    form.selectedItems = new Array();

  if (form.checkboxes) {
    if (form.selectedItems.length == form.checkboxes.length)
      MM_deselectAllItems(form, ckBoxAll);
    else
      MM_selectAllItems(form, ckBoxAll);
  }
}

function MM_removeNthArrayItem(array, n) {
  var lhs = new Array();

  if (n > 0)
    lhs = array.slice(0, n);

  var rhs = new Array();

  if (n < array.length)
    rhs = array.slice(n + 1);

  var result = lhs.concat(rhs);

  return result;
}

function MM_arrayContainsString(array, item) {
  if (array == null)
    return false;

  var count = array.length;
  for (i = 0; i < count; i++) {
    if (array[i] == item)
      return true;
  }
  return false;
}

// remove the given string from the array of strings

function MM_removeStringFromArray(array, item) {
  if (array == null)
    return null;

  var count = array.length;
  for (i = 0; i < count; i++) {
    if (array[i] == item)
      return MM_removeNthArrayItem(array, i);
  }
  return array;
}

function AtualizaToolBar(itens){
  if(itens ==1){
    document.getElementById('Adiciona/Edita').style.display ="block";
    document.getElementById('Renovar').style.display ="none";
  }
  if(itens >1 ||itens <1 ){
    document.getElementById('Adiciona/Edita').style.display ="none";
    document.getElementById('Renovar').style.display ="block";
  }
}


function MM_toggleItem(form, itemName, imageName) {
  if (form.selectedItems == null)
    form.selectedItems = new Array();

  if (MM_arrayContainsString(form.selectedItems, itemName)) {
    form.selectedItems = MM_removeStringFromArray(form.selectedItems, itemName);
    if (imageName != '') document[imageName].src = '../imagens/checkbox_off.gif';
  }
  else {
    form.selectedItems[form.selectedItems.length] = itemName;
    if (imageName != '') document[imageName].src = '../imagens/checkbox_on.gif';
  }
  if (document[form.tt + "cb"] != null) {
    document[form.tt + "cb"].src = '../imagens/checkbox_off.gif';
  }
  MM_updateButtons2(form, form.selectedItems);
}

function validaform(x) {
  return true;
}

function enviar(frm,oper) {
  frm.funcao.value = frm.name+"@"+oper;

  if (oper == 'cancelar') {
    frm.reset();
    frm.reset();  // O segundo evento reset é utilizado na tela de definição
    //               de direitos de acesso de perfis e usuários, para que sejam
    //               ajustadas as imagens relacionadas a cada INPUT HIDDEN
    return;
  }

  if (oper == 'salvar') {
    if (validaform(frm)==false) {
      return;
    }
    Salva_html();
  }
  /*
  for(var i = 0; i < frm.elements.length; i++) {
    alert(frm.elements[i].name+' = '+frm.elements[i].value);
  }*/
  frm.submit();
}

function incluir(pagina) {
  document.form[0].action = pagina + '.php';
  document.form[0].submit();
  return;
}

// Rodrigo P. Reis
function checkMenuItem(oForm, itemPrefix) {
  var checkInc = document.getElementById('INC'+itemPrefix);
  var checkAlt = document.getElementById('ALT'+itemPrefix);
  var checkExc = document.getElementById('EXC'+itemPrefix);
  var checkCon = document.getElementById('CON'+itemPrefix);
  valorAtual = checkInc.value;
  if (valorAtual == 'P') { checkitens(checkCon.form, checkCon, false, valorAtual); }
  checkitens(checkInc.form, checkInc, false, valorAtual);
  checkitens(checkAlt.form, checkAlt, false, valorAtual);
  checkitens(checkExc.form, checkExc, false, valorAtual);
  if (valorAtual != 'P') { checkitens(checkCon.form, checkCon, false, valorAtual); }
}

function checkitens(frm, item, marca_todos, valorAtual) {
  opc = new String(item.name);
  staNovo = 'N';
  if (valorAtual == 'N') { staNovo = 'S'; }
  if (valorAtual == 'S') { staNovo = 'P'; }
  if (valorAtual == 'P') { staNovo = 'N'; }

  for (var i = 0; i < frm.elements.length; i=i+1) {
    if (frm.elements[i].tagName == 'INPUT') {
      ctl = new String(frm.elements[i].name);
      if (ctl.substring(0,3) == 'INC' || ctl.substring(0,3) == 'ALT' || ctl.substring(0,3) == 'EXC' || ctl.substring(0,3) == 'CON') {
        if (marca_todos || ctl.substring(0,opc.length) == opc) {
          staAplicar = staNovo;
          if (!marca_todos) {
            if (ctl.substring(0,3) == 'CON') {
              if (staNovo == 'P') {
                tmp = ctl.substring(3,ctl.length);
                sta1 = (eval('frm.INC'+tmp+'.value == "S"') || eval('frm.ALT'+tmp+'.value == "S"') || eval('frm.EXC'+tmp+'.value == "S"'));
                if (sta1) {
                  checkitens_apply(eval('frm.INC'+tmp), 'P');
                  checkitens_apply(eval('frm.ALT'+tmp), 'P');
                  checkitens_apply(eval('frm.EXC'+tmp), 'P');
                }
              }
            }
            if (ctl.substring(0,3) == 'INC' || ctl.substring(0,3) == 'ALT' || ctl.substring(0,3) == 'EXC') {
              if (staNovo == 'N') {
                tmp = ctl.substring(3,ctl.length);
                sta1 = (eval('frm.CON'+tmp+'.value == "P"'));
                if (sta1) {
                  staAplicar = 'S';
                  checkitens_apply(eval('frm.CON'+tmp), 'S');
                }
              }
            }
          }
          checkitens_apply(frm.elements[i], staAplicar);
        }
      }
    }
  }
  while (opc.length > 6) {
    posi = opc.lastIndexOf("_");
    tmp = opc.substring(0, posi);
    opc = tmp;
    if (tmp.length > 6) {
      //if (filhoscheck(frm, tmp) == false || valorAtual == 'S') {
      if (filhoscheck(frm, tmp) == false) {
        checkitens_apply(eval("frm."+tmp), staNovo);
      }
    }
  }
  for (var j = 0; j < frm.elements.length; j=j+1) {
    if (frm.elements[j].name.substring(0,3) != 'CON') { continue; }
    modu = frm.elements[j].name.substring(3,5);
    posi = frm.elements[j].name.indexOf("_");
    tmp  = frm.elements[j].name.substring(posi + 1, frm.elements[j].name.length);
    sta1 = false;
    sta1 = (eval('frm.INC'+modu+'_'+tmp+'.value == "S"') || eval('frm.ALT'+modu+'_'+tmp+'.value == "S"') || eval('frm.EXC'+modu+'_'+tmp+'.value == "S"'));
    sta2 = eval('frm.CON'+modu+'_'+tmp+'.value == "S"')
    if (item.name.substring(0,3) == 'CON') { sta1 = (sta1 || sta2); }
    if (sta1) {
      checkitens_apply(frm.elements[j], 'S');
    }
    sta1 = false;
    sta1 = eval('frm.CON'+modu+'_'+tmp+'.value == "P"')
    if (sta1) {
      checkitens_apply(eval('frm.INC'+modu+'_'+tmp), 'P');
      checkitens_apply(eval('frm.ALT'+modu+'_'+tmp), 'P');
      checkitens_apply(eval('frm.EXC'+modu+'_'+tmp), 'P');
    }
  }
  oculta_MsgDireitos();
}
function checkitens_apply(qitem, qvalor) {
  qopc = new String(qitem.name);
  sImagem = 'indefinido.gif';
  sTitle = 'Acesso negado (indefinido)';
  if (qvalor == 'S') {
    sImagem = 'autorizado.gif';
    sTitle = 'Acesso autorizado';
  }
  if (qvalor == 'P') {
    sImagem = 'proibido.gif';
    sTitle = 'Acesso terminantemente proibido';
  }
  qitem.value = qvalor;
  document.getElementById('td'+qopc).title = sTitle;
  document.getElementById('img'+qopc).src = '../imagens/'+sImagem;
}
function filhoscheck(frm,item) {
  return;
  for (var i = 0; i < frm.elements.length; i=i+1) {
    if (frm.elements[i].name == item) { continue; }
    if (frm.elements[i].name.substring(0,item.length) == item && frm.elements[i].checked) {
      return true;
    }
  }
  return false;
}

// extract front part of string prior to searchString
function getFront(mainStr,searchStr){
  foundOffset = mainStr.indexOf(searchStr)
  if (foundOffset == -1) {
    return mainStr
  }
  return mainStr.substring(0,foundOffset)
}
// extract back end of string after searchString
function getEnd(mainStr,searchStr) {
  foundOffset = mainStr.indexOf(searchStr)
  if (foundOffset == -1) {
    return mainStr
  }
  return mainStr.substring(foundOffset+searchStr.length,mainStr.length)
}

// Funcao formataNumeroUS()
// Formata o número no padrão americano (para cálculo)
// Parâmetros:
//   num - número a ser formatado
// edelmar@ditech.com.br
function formataNumeroUS(num) {
  if (!num) {
    return '0';
  }

  if (arguments[1] != undefined) {
    var bForcaRemovePonto = arguments[1];
  } else {
    var bForcaRemovePonto = false;
  }

  // Tem virgula, está em formato brasileiro, precisa remover os pontos
  if (bForcaRemovePonto || num.toString().indexOf(',') != -1) {
    num = num.toString().replace(/\$|\./g,'');
  }
  // e colocar ponto no lugar da virgula
  return num.toString().replace(/\$|\,/g,'.');
}


// Funcao mascaraDinheiro()
// Faz a separação de milhar e decimal em campos de dinheiro
// Parâmetros:
//   campo - campo a mascarar
//   digit - número de dígitos decimais no número de saída
// mazzini@ditech.com.br
function mascaraDinheiro(campo, digit) {
  if (campo.value == '=') {
    campo.value = '0,00';
    return true;
  }
  if (campo.value.slice(0, 1) == '=') {
    if (! analisaExpressao(campo, digit)) {
      campo.focus();
      return campo.value;
    } else {
      campo.maxLength = campo.TamanhoOriginal;
    }
    campo.TamanhoOriginal = 0;
  }

  var num = campo.value;

  if (num == "") { return false; }
  if (isNaN(digit)) { digit = "2"; }

  num = formataNumeroUS(num);

  // Verifica se o número é negativo
  var bNegativo = num < 0;

  num = num.replace(/[\.]/g, ",");

  var inicio = getFront(num, ',') * 1;
  if (num != inicio) {
    var fim = getEnd(num, ',');
    fim = fim + '';
  } else var fim = '';

  if (isNaN(inicio)) inicio = '0';
  if (isNaN(fim)) fim = '';
  if (digit > 0) while (fim.length < digit) fim = fim + '0';
  if (fim.length > digit) fim = fim.substring(0,digit);

  // Inclui pontos separadores de milhar
  for (i = inicio.toString().length - 3; i > 0; i = i - 3) {
    inicio = inicio.toString().substr(0, i) + '.' + inicio.toString().substr(i);
  }

  if (inicio.toString().substr(0, 2) == "-.") {
    inicio = "-" + inicio.toString().substr(2);
  } else if (bNegativo && inicio.toString().substr(0, 1) != "-") {
    inicio = "-" + inicio.toString();
  }

  if (digit > 0) {
    campo.value = inicio.toString() + ',' + fim;
  } else {
    campo.value = inicio.toString();
  }

/*
  var num = campo.value;

  num = num.replace(",",".");
  while (num.indexOf(".") != -1){
    num = num.replace(".","");
  }

  if (num == 0) return '';

  // Completa valor com zeros à esquerda
  var tam = num.length;
  if (tam <= digit + 1) {
    for(i = 0; i < ((digit + 1) - tam); i++) {
      num = "0" + num;
    }
  }

  // Retorna valor com vírgula e decimais completos
  var contr    = -1;
  var moneyVal = "";
  var intNum   = num.substring(0, (num.length - digit));
  var floatNum = num.substring((num.length - digit), num.length);

  // Retira zeros da frente do inteiro
  intNum = intNum * 1;

  // Acerta o tamanho se foi digitado zero na frente
  tam = intNum + floatNum;

  for(i = (tam.length - digit); i > -1; i-- ){
      moneyVal = intNum.toString().substr(i, 1) + moneyVal;
      contr++;
      if (contr > 2 && i != 0) {
        moneyVal = "." + moneyVal;
        contr = 0;
      }
  }

  moneyVal = moneyVal + "," + floatNum;

  if (moneyVal.length > campo.maxLength) {
    moneyVal = "0,";
    for(i = 0; i < digit; i++) {
      moneyVal = moneyVal + "0";
    }
  }

  campo.value = moneyVal;
*/
  return;
}

//Funcao validaDinheiro()
//Impede que o usuário entre com duas virgulas (,) no mesmo campo
//Utiliza função validaTecla()
//cardoso@ditech.com.br
function validaDinheiro(campo, event) {
  return validaTecla(campo, event);
}

// Funcao focaNumero(campo)
// Prepara o conteúdo de um campo de valor para edição, removendo os pontos de separação de milhar
// parametro -> campo a preparar
// mazzini@ditech.com.br
function focaNumero(campo) {
  var num = campo.value;

  if (num != "") {
    num = num.replace(/[\.]/g, "");
    campo.value = num;
  }

  campo.select();
}

//Function goTo - Cardoso
function goTo(url){
  document.location.href = url;
}

function VerificaCPFCNPJ(valor) {
  valor.replace(/ /, '');
  primeiro=valor.substr(1,1);
  falso=true;
  size=valor.length;
  if (size!=11 && size!=14) {
    return false;
  }
  size--;
  for (i=2; i<size-1; ++i) {
    proximo=(valor.substr(i,1));
    if (primeiro!=proximo) {
      falso=false;
    }
  }
  if (falso) {
    return false;
  }

  if(modulo(valor.substring(0,valor.length - 2)) + "" + modulo(valor.substring(0,valor.length - 1)) != valor.substring(valor.length - 2,valor.length)) {
    //alert ("digito correto= " + modulo(valor.substring(0,valor.length - 2)) + "" + modulo(valor.substring(0,valor.length - 1)));
    return false;
  }
  return true;
}

function modulo(str) {
  soma=0;
  ind=2;
  for(pos=str.length-1;pos>-1;pos=pos-1) {
    soma = soma + (parseInt(str.charAt(pos)) * ind);
    ind++;
    if(str.length>11) {
      if(ind>9) ind=2;
    }
  }
  resto = soma - (Math.floor(soma / 11) * 11);
  if(resto < 2) {
    return 0;
  }
  else {
    return 11 - resto;
  }
}

function getPosToWindow(w, h){
    //built by cardoso@ditech.com.br

    PosW = (screen.width/2) - (w/2);
    PosH = (screen.height/2) - (h/2);

    var pos = new Array();
    pos[0]  = PosW;
    pos[1]  = PosH;

    return pos;
}//

function PaginaManual(NomeArq) {
  //built by mazzini@ditech.com.br

  var Chamada = new String(NomeArq);

  Inicio  = Chamada.lastIndexOf('/');
  Chamada = "./manual/index.php?locmanual=Hlp_" + NomeArq.substr(Inicio + 1);

  return Chamada;
}//

function toInt(obj){
  var value = obj.value;
  //Require Function mascaraDinheiro
  //Built by cardoso@ditech.com.br
  //Modified by mazzini@ditech.com.br
  value = value.replace(/\,/g,"");
  obj.value = value;
}
function toNumber(valor) {
  // Alterado por Edelmar@ditech em 11/03/2005
  return formataNumeroUS(valor);

  valor = valor.replace(/\./g,"");
  valor = valor.replace(",",".");
  return valor * 1;
}

function verifyRange(elField, minValue, maxValue) {
  // Modified by mazzini@ditech.com.br
  var valor = elField.value;

  if(valor == ""){
    return false;
  }

  valor = toNumber(valor);
  valor = valor * 1;

  if ((valor < minValue || valor > maxValue)) {
    alert("Este valor está fora da faixa para este campo, os valores possíveis devem estar entre " + minValue + " e " + maxValue + ".");
    elField.value = "";
    elField.focus();

    return false;
  } else {
    return true;
  }
}

function dataValida (data) {
  var mydata = '';

  mydata = data.value.replace(' ', '');
  tam    = mydata.length;

  if (tam == 7) {
    dia = "01";
    mes = (data.value.substring(0, 2));
    ano = (data.value.substring(3, 7));
  } else {
    if (tam < 8) {
      return false;
    }
    dia = data.value.substring(0, 2);
    mes = data.value.substring(3, 5);
    ano = data.value.substring(6, 10);
  }

  // Verifica o dia válido para cada mês
  if (dia < 1) { return false; }
  if (mes == 2) {
    if ((ano % 4) == 0) {
      if (dia > 29) { dia = 29; }
    } else {
      if (dia > 28) { dia = 28; }
    }
  }
  if ((dia > 30) && (mes == 4 || mes == 6 || mes == 9 || mes == 11)) { dia = 30; }
  if (dia > 31) { dia = 31; }

  // verifica se o mes e valido
  if (mes > 12) { mes = '12'; }
  if (mes < 1) { mes = '01'; }

  return true;
}

function popupObject(sDump) {
  winObj = window.open("", "JSobjectdump", "width=600,height=500,resizable=yes,scrollbars=yes,directories=no,location=no,menubar=no,status=no,toolbar=no");
  winObj.document.open();
  winObj.document.writeln(sDump);
  winObj.document.close();
}

function showProperty(obj, showView) {
  var output = '';
  for(var prop in obj) {
    if (prop!="outerHTML" && prop!="innerHTML") {
      output += obj['name']+"."+prop+" = "+obj[prop];
      if (obj[prop] == "[object]" && showView==true) {
        output += '&nbsp;&nbsp;<input type="button" style="font-size:6pt" value="view" onclick="popupObject(showProperty(document.'+obj['name']+"."+prop+',false))">&nbsp;&nbsp;';
      }
      output += "<br>";
    }
  }
  return output;
}

// Devolve o nome do mês, no formato longo ou abreviado
// Parâmetros:
//   iMes - número do mês (1-12)
//   cFmt - formato ('A' = abreviado, 'E' = extenso)
function nomeMes(iMes, cFormato) {
  var aNomeMes = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho',
                  'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];

  if ((iMes < 1) || (iMes > 12))
    return 'Inválido';
  if (cFormato == 'A') {
    sNome = aNomeMes[iMes - 1];
    sNome = sNome.substr(0, 3);
  } else {
    sNome = aNomeMes[iMes - 1];
  }
  return sNome;
}

// Testa o tamanho do campo digitado, retornando false quando for maior do que o limite informado
//   oObj       - objeto (text ou textarea)
//   event      - evento (geralmente no onKeyPress)
//   iTam       - tamanho máximo admissível
//   bSemEnter  - permite a impressao da tecla "Enter" num textArea
function testaTamanho(oObj, event, iTam, bSemEnter) {
  var tecla;
  var BACKSPACE = 8;
  var ENTER = 13;

  if (navigator.appName.indexOf("Netscape") != -1)
    tecla = event.which;
  else
    tecla = event.keyCode;

  if ((tecla == ENTER) && (bSemEnter)) {
    return false;
  }

  // Obtém o tamanho do texto selecionado
  if (document.getSelection) {
    iTamSel = oObj.selectionEnd - oObj.selectionStart;
  } else if (document.selection) {
    txt = document.selection.createRange().text;
    iTamSel = txt.length;
  }

  return (oObj.value.length < iTam) || (tecla == BACKSPACE) || (tecla == 0) || (iTamSel > 0);
}

/**
  * insereCombo()
  *
  * Move os itens selecionados de um combo select para outro
  *
  * @author Edelmar Cabral Ziegler - <edelmar@ditech.com.br
  * @param inName     object - Combo que recebe os novos options
  * @param outName    object - Combo de onde saem os options
  *
  * @return void
  **/
function insereCombo(inName, outName) {
  var objOUT = document.getElementById(outName);
  var objIN  = document.getElementById(inName);

  for (i=objOUT.length-1; i>=0; i--) {
    if (objOUT.options[i].selected) {
      newOpt = document.createElement("OPTION")
      newOpt.text = objOUT.options[i].text;
      newOpt.value = objOUT.options[i].value;
      objIN.options.add(newOpt);
      objOUT.options[i] = null;
    }
  }
}

function removeCombo(inName, outName) {
  var objOUT = document.getElementById(outName);
  var objIN  = document.getElementById(inName);

  for (i=objIN.length-1; i>=0; i--) {
    if (objIN.options[i].selected) {
      newOpt = document.createElement("OPTION");
      newOpt.text = objIN.options[i].text;
      newOpt.value = objIN.options[i].value;
      objOUT.options.add(newOpt);
      objIN.options[i] = null;
    }
  }
}

function openClieSaldosWindow(iCD_CLI) {
  window.open('../AP/APcliesaldos.php?FRMcd_cli='+iCD_CLI,'','status=yes,scrollbars=yes,toolbar=no,resizable=yes,menubar=no,width=720,height=420,top=20,left=20');
}
function openWindowAllDocs(iCNPJ) {
  window.open('APdocsged.php?FRMcnpj='+iCNPJ,'docsged', 'status=no,scrollbars=yes,toolbar=no,resizable=yes,menubar=no,width=750,height=550');
}

function openWindowGenerica(sURL, sNome) {
  window.open(sURL,sNome,'status=yes,scrollbars=yes,toolbar=no,resizable=no,menubar=no,width=650,height=400,top=20,left=20');
}


// rodrigo@ditech - 05/05/2004
// evita que o backspace seja usado como BACK do browser
function escapeBackSpace() {
  if (event) {
    if (event.keyCode == 8) { //backspace
      var sType = document.activeElement.getAttribute("type");
      if (sType != "text" && sType != "textarea") {
        event.returnValue = false;
      }
    }
  }
}
// rodrigo@ditech - 02/04/2004
// prepara itens selecionados (toolbar checkboxes) concatenando com ** para submit sem POST ou GET
function prepareSelectedItems(oForm) {
  var params = '';
  if (oForm.selectedItems) {
    var params = new String();
    for (i = 0; i < oForm.selectedItems.length; i++) {
      if (i > 0) { params = params + "**"; }
      params = params + oForm.selectedItems[i];
    }
  }
  return params;
}

// alex@ditech - 23/10/2004
// Serve para abrir e fechar as áreas das telas.
// Deve vir a substituir o método anterior de fazer a mesma tarefa.
// As linhas comentadas fazem o mesmo trabalho de um jeito diferente; usando sDivImage só troca a imagem de fundo, enquanto que sDivClass troca a classe do div.
// O método da classe do div parece requerer mais recursos e, inclusive, mostra a barra de status carregando entre troca e troca.
function showHideArea(sDivID) {
  if(document.getElementById(sDivID+"Titulo").title == 'Minimizar'){
    sDivDisplay = 'none';
    sDivImage = 'url("../imagens/tabela_fechada.gif")';
    //sDivClass = 'headerAberto';
    sDivTitle = 'Maximizar';
  } else {
    sDivDisplay = 'block';
    sDivImage = 'url("../imagens/tabela_aberta.gif")';
    //sDivClass = 'headerFechado';
    sDivTitle = 'Minimizar';
  }
  document.getElementById(sDivID).style.display = sDivDisplay;
  document.getElementById(sDivID+"Titulo").style.backgroundImage = sDivImage;
  //document.getElementById(sDivID+"Titulo").className = sDivClass;
  document.getElementById(sDivID+"Titulo").title = sDivTitle;
}

// mateus@ditech - 12/11/2004
// Serve para mostrar o emulador de title (hint) para que
// possa ser visualizado em outros browsers como o mozila
// utiliza um div e eum iframe que está no masterfooter
var iTimeOutHtmlTitle = false;
var iTimeOutInHtmlTitle = false;
var iMouseHtmlTitleX = 0;
var iMouseHtmlTitleY = 0;
var oElForHtmlTitle = null;
var sTextForHtmlTitle= '';
var iDivLarguraForHtmlTitle = null;
if (ns6 || ns61) {
  window.captureEvents(Event.MOUSEMOVE);
  window.onmousemove = getMozillaMousePos;
  window.releaseEvents(Event.MOUSEMOVE);
}
function showDivForHtmlTitle(){
  var aArgs = showDivForHtmlTitle.arguments;
  oElForHtmlTitle = aArgs[0];
  sTextForHtmlTitle = aArgs[1];
  iDivLarguraForHtmlTitle = aArgs[2];
  if (!ns6 && !ns61) {
    iMouseHtmlTitleX = window.event.x;
    iMouseHtmlTitleY = window.event.y;
  }
  iTimeOutInHtmlTitle = window.setTimeout("__showDivForHtmlTitle();", 500);
}
function __showDivForHtmlTitle() {
  //var aArgs = __showDivForHtmlTitle.arguments;
  var oEl = oElForHtmlTitle;
  var sText = sTextForHtmlTitle;
  var iDivLargura = iDivLarguraForHtmlTitle;// se não mandar a largura, usar a padrão: 550px

  var oDivForHtmlTitle     = document.getElementById('divForHtmlTitle');
  var oDivTextForHtmlTitle = document.getElementById('divTextForHtmlTitle');
  var oIframeForHtmlTitle  = document.getElementById('iframeForHtmlTitle');
  var oElParent            = oEl.offsetParent;

  oDivForHtmlTitle.style.overflow = '';

  if (ns6 || ns61) {
    window.captureEvents(Event.MOUSEMOVE);
    oEl.onmousemove = getMozillaMousePos;
    window.releaseEvents(Event.MOUSEMOVE);
  } else {
    oDivTextForHtmlTitle.style.width = 1;
    oDivTextForHtmlTitle.style.height = 1;
  }

  var iTopAux = 3;
  var iExtraTopIncrement   = iMouseHtmlTitleY + 5 + document.body.scrollTop + oEl.offsetHeight;
  var iExtraLeftIncrement  = iMouseHtmlTitleX + 5;

  oDivForHtmlTitle.style.display = sDisplayBlock;
  oDivForHtmlTitle.style.top     = 0;
  oDivForHtmlTitle.style.left    = 0;
  oDivTextForHtmlTitle.innerHTML = sText;

  if (iDivLargura) {
    oDivForHtmlTitle.style.width = iDivLargura;
  } else if (oDivTextForHtmlTitle.offsetWidth) {
    oDivForHtmlTitle.style.width = oDivTextForHtmlTitle.offsetWidth;
  }
  if (oDivTextForHtmlTitle.offsetHeight) {
    oDivForHtmlTitle.style.height = oDivTextForHtmlTitle.offsetHeight;
  }

  // teste para ver se não irá passar do fim da página
  // se passar, coloca acima do objeto
  var iPosOrig      = parseInt(iExtraTopIncrement);
  var iDesloca      = parseInt(oDivForHtmlTitle.offsetHeight);
  if ((iPosOrig + iDesloca) > (document.body.clientHeight + document.body.scrollTop)) {
    iExtraTopIncrement = (iExtraTopIncrement - oDivForHtmlTitle.offsetHeight - iTopAux - oEl.offsetHeight) - 18;//-18 para o mouse não ficar encima
  }

  // teste para ver se estora na direita da tela
  var iLarguraTela = document.body.offsetWidth - 25//por causa da barra de rolagem e margem da ditech;
  var iLarguraDiv  = iExtraLeftIncrement + parseInt(oDivForHtmlTitle.offsetWidth);
  if (iLarguraDiv > iLarguraTela) {
    // É para a margem usada nos sistemas da ditech;
    var iMargemDireita = 24;
    if (ns6 || ns61) {
      iMargemDireita = 24;
    }
    iDesloca = (document.body.scrollLeft + document.body.offsetWidth - oDivForHtmlTitle.offsetWidth) - iMargemDireita
    if (iDesloca < 0) {
      iDesloca = 5;
      oDivForHtmlTitle.style.overflow = 'auto';
    }
    iExtraLeftIncrement = iDesloca;
  } else {
    iExtraLeftIncrement = iExtraLeftIncrement;
  }

  // teste para ver se o div é mais comprido que a página

  if (oDivForHtmlTitle.offsetWidth > document.body.clientWidth) {
    oDivForHtmlTitle.style.width = document.body.clientWidth - 50;
    oDivForHtmlTitle.style.overflow = 'auto';
    if (oDivForHtmlTitle.clientHeight < oDivForHtmlTitle.offsetHeight) {
      oDivForHtmlTitle.style.height = oDivForHtmlTitle.offsetHeight + (oDivForHtmlTitle.offsetHeight - oDivForHtmlTitle.clientHeight);
    }
  }

  var iPosOrig = parseInt(iExtraTopIncrement);
  if (iPosOrig < 0) {
    iExtraTopIncrement  = document.body.scrollTop + 20;
    if (oDivForHtmlTitle.offsetHeight > document.body.clientHeight) {
      oDivForHtmlTitle.style.height = document.body.clientHeight - 50;
      oDivForHtmlTitle.style.width = oDivForHtmlTitle.clientWidth + 20;
      oDivForHtmlTitle.style.overflow = 'auto';
    }
  }

  //Problema do overflow no IE
  iMargemDiv = 20;
  if (ns6 || ns61 || oDivForHtmlTitle.style.overflow != 'auto') {
    iMargemDiv = 0;
  }
  if (oDivForHtmlTitle.clientWidth < oDivForHtmlTitle.offsetWidth) {
    iMargemDiv = 0;
  }
  oDivForHtmlTitle.style.display    = sDisplayBlock;
  oDivForHtmlTitle.style.top        = iExtraTopIncrement;
  oDivForHtmlTitle.style.left       = iExtraLeftIncrement;
  oDivForHtmlTitle.style.zIndex     = 10000; // para ficar sobre de qualquer coisa
  oIframeForHtmlTitle.style.width   = oDivForHtmlTitle.offsetWidth + iMargemDiv;
  oIframeForHtmlTitle.style.height  = oDivForHtmlTitle.offsetHeight;
  oIframeForHtmlTitle.style.top     = oDivForHtmlTitle.style.top;
  oIframeForHtmlTitle.style.left    = oDivForHtmlTitle.style.left;
  oIframeForHtmlTitle.style.zIndex  = oDivForHtmlTitle.style.zIndex - 1;
  oIframeForHtmlTitle.style.display = sDisplayBlock;
}

// mateus@ditech - 02/80/2005
// Serve para capturar a posição do mouse no mozilla
function getMozillaMousePos(oEvent) {
  iMouseHtmlTitleX = oEvent.pageX;
  iMouseHtmlTitleY = oEvent.pageY;
}

// mateus@ditech - 12/11/2004
// Serve para esconder o emulador de title (hint) para que
// possa ser visualizado em outros browsers como o mozila
function hideDivForHtmlTitle(s) {
  try {
    clearTimeout(iTimeOutInHtmlTitle);
  } catch(e) {
    //não faz nada
  }

  oDivForHtmlTitle = document.getElementById('divForHtmlTitle');
  if (oDivForHtmlTitle.style.overflow == 'auto') {
    oDivForHtmlTitle.onmouseout = new Function("iTimeOutHtmlTitle = setTimeout('__hideDivForHtmlTitleComOverFlow();', 500);");
  } else {
    document.getElementById('divForHtmlTitle').style.width      = null;
    document.getElementById('iframeForHtmlTitle').style.width   = null;
    document.getElementById('divForHtmlTitle').style.display    = 'none';
    document.getElementById('iframeForHtmlTitle').style.display = 'none';
  }
}

// mateus@ditech - 16/02/2005
// Serve para esconder o emulador de title (hint) para que
// possa ser visualizado em outros browsers como o mozila
// quando o conteúdo do html passar do tamanho visível da tela
function __hideDivForHtmlTitleComOverFlow() {
  limpaTimeOutHtmlTitle();
  document.getElementById('divForHtmlTitle').style.width      = null;
  document.getElementById('iframeForHtmlTitle').style.width   = null;
  document.getElementById('divForHtmlTitle').style.overflow   = '';
  document.getElementById('divForHtmlTitle').style.display    = 'none';
  document.getElementById('iframeForHtmlTitle').style.display = 'none';
}

// leandro@ditech - 16/02/2005
function limpaTimeOutHtmlTitle() {
  try {
    clearTimeout(iTimeOutHtmlTitle);
  } catch(e) {
    //não faz nada
  }
}

// leandro@ditech - 16/12/2004
// Recarrega a página atual com os mesmos parâmetros, mas alterando o idioma
function trocaIdioma(sLangId) {
  if (document.getElementById('FRMhiddenFields') && document.getElementById('FRMhiddenFieldsForm')) {
    sInputHiddenFields = '<input type="hidden" name="sNovoIdiomaSessao" value="' + sLangId + '">' + "\n";
    if (aRequestDataHidden) {
      for (sChave in aRequestDataHidden) {
        sInputHiddenFields += aRequestDataHidden[sChave] + "\n";
      }
    }
    document.getElementById('FRMhiddenFields').innerHTML = sInputHiddenFields;
    document.getElementById('FRMhiddenFieldsForm').submit();
  }
}

/**
 * Mateus Delfim 08/04/2005
 * As funções abaixo são usadas para que um combo
 * respeite as teclas e faça a busca das letras
 * digitadas pelos valores do select.
 *
 * Uso:
 * onkeyUp="aceleraBuscaCombo(this, event)"
 */
var sTextoAceleraBuscaCombo   = '';
var iTimeOutAceleraBuscaCombo = 0;
function aceleraBuscaCombo(oCombo, hEvent, bEnviaForm) {

  limpaTimeOutAceleraBuscaCombo();

  if (navigator.appName.indexOf("Netscape") != -1) {
    sTecla = hEvent.which;
  } else {
    sTecla = hEvent.keyCode;
  }

  //as teclas de setas e backspace
  if (sTecla == 40 ||sTecla == 38 || sTecla == 37 || sTecla == 39 || sTecla == 8) {
    return false;
  }


  if (sTecla == 13) {
    if (bEnviaForm == true) {
      window.setTimeout("document." + oCombo.form.name + ".submit()", 500);
    }
    return false;
  }

  skey = String.fromCharCode(sTecla);
  sTextoAceleraBuscaCombo += skey;

  for (i = 0; i < oCombo.length; i++) {
    oCombo.options[i].selected = false;
  }

  bLimparTexto = true;
  for (i = 0; i < oCombo.length; i++) {
    if (oCombo.options[i].text.substr(0, sTextoAceleraBuscaCombo.length).toUpperCase() == sTextoAceleraBuscaCombo.toUpperCase()) {
      //oCombo.selectedIndex = i;
      oCombo.options[i].selected = true;
      iTimeOutAceleraBuscaCombo = setTimeout("sTextoAceleraBuscaCombo = '';", 1000);
      bLimparTexto = false;
      break;
    }
  }
  if (bLimparTexto == true) {
    sTextoAceleraBuscaCombo = '';
  }
}

function limpaTimeOutAceleraBuscaCombo() {
  try {
    clearTimeout(iTimeOutAceleraBuscaCombo);
  } catch(e) {
    //não faz nada
  }
}
// Fim das funções de busca dentro de um combo

// leandro@ditech - 28/04/2005
var oDebugWindow;
function dumpJavascriptArray(aArray) {
  if (typeof(aArray) == 'object') {
    oDebugWindow = window.open("", "DitechDebugWindow");
    oDebugWindow.document.open();
    oDebugWindow.document.writeln('<pre>Javascript Array Dump:');
    oDebugWindow.document.writeln('');
    oDebugWindow.document.writeln('Array');
    oDebugWindow.document.writeln('{');
    __dumpJavascriptArray(aArray, 1);
    oDebugWindow.document.writeln('}');
  } else {
    alert('dumpJavascriptArray: A variável fornecida não é um array !');
  }
}

// leandro@ditech - 28/04/2005
function __dumpJavascriptArray(aArray, iLevel) {
  if (typeof(aArray) == 'object') {
    sIdent = '';
    for (i = 0; i < iLevel; i++) {
      sIdent += '    ';
    }
    if (iLevel > 1) {
      oDebugWindow.document.writeln(sIdent + '{');
    }
    for (sIndex in aArray) {
      if (typeof(aArray[sIndex]) == 'object') {
        oDebugWindow.document.writeln(sIdent + '[' + sIndex + '] => Array');
        __dumpJavascriptArray(aArray[sIndex], iLevel + 1)
      } else {
        oDebugWindow.document.writeln(sIdent + '    [' + sIndex + '] => ' + aArray[sIndex]);
      }
    }
    if (iLevel > 1) {
      oDebugWindow.document.writeln(sIdent + '}');
    }
  }
}

function removeChars(sValor) {
  return sValor.toString().replace(/[^0-9]/g, "");
}

function redirecionaParaURL() {
  var i, sHTML;
  var sURL = '';
  var sTarget = '';

  //Esconde a tela antes de submeter para parecer rápido
  document.body.style.display = 'none';

  // Testando os argumentos da função
  iArgs = redirecionaParaURL.arguments.length;
  if (iArgs < 1) {
    alert('Número insuficiente de argumentos passado para a função redirecionaParaURL()');
    return;
  } else if (iArgs <= 2) {
    sURL = redirecionaParaURL.arguments[0];
    if (iArgs == 2) {
      if (typeof(redirecionaParaURL.arguments[1]) == "object") {
        evt = redirecionaParaURL.arguments[1];
        if (evt.ctrlKey || evt.shiftKey && !evt.altKey) {
          sTarget = '_blank';
          //Se é em uma nova janela, não pode ser escondido
          document.body.style.display = sDisplayBlock;
        }
      } else {
        sTarget = redirecionaParaURL.arguments[1];
      }
    }
  } else {
    alert('Ultrapassado o número de argumentos passado para a função redirecionaParaURL()');
    return;
  }

  aPostInfo = sURL.split('?');
  sAction = aPostInfo[0];
  sInputs = '<input type="submit" style="display:none">';
  if (aPostInfo[1] != undefined) {
    aPostInfo = aPostInfo[1].split('&');
    for (i = 0; i < aPostInfo.length; i++) {
      aVarInfo = aPostInfo[i].split('=');
      if (aVarInfo[0] != undefined) {
        aVarInfo[1] = (aVarInfo[1] != undefined ? aVarInfo[1] : '');
        sInputs += '<input type="hidden" name="'+aVarInfo[0]+'" value="'+aVarInfo[1]+'">\n';
      }
    }
  }
  sHTML = sInputs;

  document.getElementById("FRMhiddenFieldsForm").action = sAction;
  document.getElementById("FRMhiddenFieldsForm").target = sTarget;
  document.getElementById("FRMhiddenFields").innerHTML = sInputs;
  document.getElementById("FRMhiddenFieldsForm").submit();
}

/*Funções usuadas nos calendários*/
var aClasses = new Array();
aClasses[0] = new Array();
aClasses[0]["dayHighlightON"] = "DateGUI_dayHighlightON";
aClasses[0]["dayHighlightOFF"] = "DateGUI_dayHighlightOFF";
aClasses[0]["weekHighlightON"] = "DateGUI_weekHighlightON";
aClasses[0]["weekHighlightOFF"] = "DateGUI_weekHighlightOFF";
aClasses[0]["tableClass"] = "DateGUI_tableClassSmall";
aClasses[0]["dayWithDate"] = "DateGUI_dayWithDate";
aClasses[0]["dayWithoutDate"] = "DateGUI_dayWithoutDate";
aClasses[0]["today"] = "DateGUI_today";
aClasses[1] = new Array();
aClasses[1]["dayHighlightON"] = "DateGUI_dayHighlightONBig";
aClasses[1]["dayHighlightOFF"] = "DateGUI_dayHighlightOFFBig";
aClasses[1]["weekHighlightON"] = "DateGUI_weekHighlightONBig";
aClasses[1]["weekHighlightOFF"] = "DateGUI_weekHighlightOFFBig";
aClasses[1]["tableClass"] = "DateGUI_tableClassSmallBig";
aClasses[1]["dayWithDate"] = "DateGUI_dayWithDateBig";
aClasses[1]["dayWithoutDate"] = "DateGUI_dayWithoutDateBig";
aClasses[1]["today"] = "DateGUI_todayBig";

function onmouseoverSemana (iWeek, iType, sID) {
  sTrId = 'trDateWeek' + iType + iWeek + sID;
  if (document.getElementById(sTrId)) {
  document.getElementById(sTrId).className = aClasses[iType]["weekHighlightON"];
  }
}

function onmouseoutSemana (iWeek, iType, sID) {
  sTrId = 'trDateWeek' + iType + iWeek + sID;
  if (document.getElementById(sTrId)) {
     document.getElementById(sTrId).className = aClasses[iType]["weekHighlightOFF"];
  }
}

function onmouseoverDia (obj, iType) {
    if (obj.className != aClasses[iType]["dayWithDate"] && obj.className != aClasses[iType]["today"]) {
    obj.className = aClasses[iType]["dayHighlightON"];
  }
}

function onmouseoutDia (obj, iType) {
  if (obj.className != aClasses[iType]["dayWithDate"] && obj.className != aClasses[iType]["today"]) {
    obj.className = aClasses[iType]["dayHighlightOFF"];
  }
}
/*FIM das Funções usuadas nos calendários*/

function getOffsetTop(element) {
  iIncrement = element.offsetTop;
  if (element.offsetParent) {
    oElParent = element;
    while (oElParent.offsetParent) {
      iIncrement += oElParent.offsetParent.offsetTop;
      oElParent = oElParent.offsetParent;
    }
  }
  return iIncrement;
}

function getOffsetLeft(element) {
  iIncrement = element.offsetLeft;
  if (element.offsetParent) {
    oElParent = element;
    while (oElParent.offsetParent) {
      iIncrement += oElParent.offsetParent.offsetLeft;
      oElParent = oElParent.offsetParent;
    }
  }
  return iIncrement;
}

// Funções úteis para AJAX
function getNewXMLHttpRequest() {
  var obj;
    try {
      // For Internet Explorer.
      obj = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch(e) {
      try {
        // Gecko-based browsers, Safari, and Opera.
        obj = new XMLHttpRequest();
      }
      catch (e) {
        // Browser supports Javascript but not XMLHttpRequest.
        obj = false;
      }
    }
    return obj;
}

// Funções úteis para AJAX
function getNewXMLHttpRequest2() {
  var obj;
    try {
      // For Internet Explorer.
      obj = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch(e) {
      try {
        // Gecko-based browsers, Safari, and Opera.
        obj = new XMLHttpRequest();
      }
      catch (e) {
        // Browser supports Javascript but not XMLHttpRequest.
        obj = false;
      }
    }
    return obj;
}


// RF 200602 - Função para exibir uma aba e esconder as outras
function activateFolderTab(sFolderTab,sNmVar, sPai, sSelecionado) {
  iTam = sNmVar.length;
  for(i=0; i<iTam; i++) {
    sFirst = '';
    if(sNmVar[i] != sFolderTab) {
      document.getElementById('divFolderTabs'+i+'Left').className = 'folderTabUnSelectedLeft';
      document.getElementById('divFolderTabs'+i+'Center').className = 'folderTabUnSelected';
      document.getElementById('divFolderTabs'+i+'Right').className = 'folderTabUnSelectedRight';
      document.getElementById(sNmVar[i]).style.display = 'none';
    } else {
      if (sFolderTab == 1 ) { sFirst = 'First'; }
      document.getElementById('divFolderTabs'+i+'Left').className = 'folderTabSelected'+sFirst+'Left';
      document.getElementById('divFolderTabs'+i+'Center').className = 'folderTabSelected';
      document.getElementById('divFolderTabs'+i+'Right').className = 'folderTabSelectedRight';
      document.getElementById(sNmVar[i]).style.display = '';
    }
  }
}

function limpaForm(oForm) {
  var oElementos = oForm.elements;

  for ( i = 0; i < oElementos.length; i++ ) {
    if ( oElementos[i].type.length > 0 ) {
      switch ( oElementos[i].type ) {
        case "text" :
        case "textarea" :
        case "password" :
          oElementos[i].value = '';
        break;
        case "checkbox" :
        case "radio" :
          oElementos[i].checked = false;
        break;
        case "select-one" :
        case "select-multiple" :
          oElementos[i].selectedIndex = 0;
        break;
     }
   }
  }
  return;
}


function limpaHTML(html) {
  var bIgnoreFont = false;
  var bRemoveStyles = true;

  //Removendo os possíveis erros de javascript
  html = html.replace(/<input[\s\S]*?\>/gi, "") ;
  html = html.replace(/<form[\s\S]*?\>/gi, "") ;
  html = html.replace(/<script[\s\S]*?\/script>/gi, "") ;
  html = html.replace( /\s*href="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*href=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmouseover="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmouseover=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmouseout="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmouseout=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onclick="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onclick=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onblur="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onblur=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onclick="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onclick=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*ondblclick="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*ondblclick=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*ondragstart="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*ondragstart=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onerrorupdate="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onerrorupdate=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onfilterchange="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onfilterchange=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onfocus="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onfocus=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onHelp="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onHelp=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onkeydown="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onkeydown=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onkeypress="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onkeypress=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onkeyup="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onkeyup=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmousedown="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmousedown=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmousemove="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmousemove=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmouseout="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmouseout=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmouseover="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmouseover=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onmouseup="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onmouseup=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*onselectstart="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*onselectstart=[^ >]*/gi, "" ) ;
  html = html.replace(/<a[\s\S]*?\>/gi, "<span>") ;
  html = html.replace(/<\/a>/gi, "</span>") ;

  html = html.replace( /\s*width="[^"]*"/gi, "" ) ;
  html = html.replace( /\s*width=[^ >]*/gi, "" ) ;
  html = html.replace( /\s*width:[^"]*;/gi, "" ) ;

  html = html.replace(/<o:p>\s*<\/o:p>/g, "") ;
  html = html.replace(/<o:p>.*?<\/o:p>/g, "&nbsp;") ;

  // Remove mso-xxx styles.
  html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, "" ) ;

  // Remove margin styles.
  //html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, "" ) ;
  //html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;

  //html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, "" ) ;
  //html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;

  //html = html.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;

  //html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;

  //html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;

  html = html.replace( /\s*tab-stops:[^;"]*;?/gi, "" ) ;
  html = html.replace( /\s*tab-stops:[^"]*/gi, "" ) ;

  // Remove FONT face attributes.
  //if ( bIgnoreFont )
  //{
  //  html = html.replace( /\s*face="[^"]*"/gi, "" ) ;
  //  html = html.replace( /\s*face=[^ >]*/gi, "" ) ;
  //
  //  html = html.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, "" ) ;
  //}

  // Remove Class attributes
  //html = html.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;

  // Remove styles.
  //if ( bRemoveStyles )
  //  html = html.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;
  //
  // Remove empty styles.
  //html =  html.replace( /\s*style="\s*"/gi, '' ) ;

  //html = html.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ;

  //html = html.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ;

  // Remove Lang attributes
  //html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;

  //html = html.replace( /<SPAN\s*>(.*?)<\/SPAN>/gi, '$1' ) ;

  //html = html.replace( /<FONT\s*>(.*?)<\/FONT>/gi, '$1' ) ;

  // Remove XML elements and declarations
  html = html.replace(/<\\?\?xml[^>]*>/gi, "") ;

  // Remove Tags with XML namespace declarations: <o:p></o:p>
  html = html.replace(/<\/?\w+:[^>]*>/gi, "") ;

  //html = html.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;

  //html = html.replace( /<H1([^>]*)>/gi, '<div$1><b><font size="6">' ) ;
  //html = html.replace( /<H2([^>]*)>/gi, '<div$1><b><font size="5">' ) ;
  //html = html.replace( /<H3([^>]*)>/gi, '<div$1><b><font size="4">' ) ;
  //html = html.replace( /<H4([^>]*)>/gi, '<div$1><b><font size="3">' ) ;
  //html = html.replace( /<H5([^>]*)>/gi, '<div$1><b><font size="2">' ) ;
  //html = html.replace( /<H6([^>]*)>/gi, '<div$1><b><font size="1">' ) ;

  //html = html.replace( /<\/H\d>/gi, '</font></b></div>' ) ;

  //html = html.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;

  // Remove empty tags (three times, just to be sure).
  //html = html.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
  //html = html.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;
  //html = html.replace( /<([^\s>]+)[^>]*>\s*<\/\1>/g, '' ) ;

  // Transform <P> to <DIV>
  var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ;  // Different because of a IE 5.0 error
  html = html.replace( re, "<div$2</div>" ) ;

  return html ;
}

function Trim(str){
  while (str.charAt(0) == " " || str.charAt(0) == String.fromCharCode(160)) {
    if (str.length > 0) {
      str = str.substr(1, str.length - 1);
    }
  }

  while (str.charAt(str.length - 1) == " " || str.charAt(str.length - 1) == String.fromCharCode(160)) {
    if (str.length > 0) {
      str = str.substr(0, str.length - 1);
    }
  }
  return str;
}

/**
* abreFormPopup()
*
* Submete formulários para um popup
*
* @author Edelmar Cabral Ziegler <edelmar@ditech.com.br>
* @access public
* @param oForm object Formulário sendo submetido. Tudo que importa para a geração está dentro dele e não interessa a esta função.
* @param sParams string Parâmetros da janela
* @return void Abre uma janela executando o script correspondente ao relatório selecionado.
**/
function abreFormPopup(oForm, sParams) {
  if (!oForm) return false;                               // Sem form, nada feito.
  if(!sParams) {                                          // Se não houver parâmetros, usa o default
    sParams = 'toolbar=no,resizable=yes,menubar=no,scrollbars=no,width=650,height=450';
  }
  var sJanela = oForm.name + new Date().getTime();        // Gera um nome único para a janela
  window.open('', sJanela, sParams);                      // Abrindo a janela onde o relatório vai ser gerado
  oForm.target = sJanela;                                 // Aponta a saída do formulário para a janela recém aberta
  oForm.submit();                                         // Envia o formulário
}

/**
* inArray()
*
* Pesquisa um valor no array, semelhante ao inArray do php
*
* @author Diego Sampaio <diego@ditech.com.br>
* @access public
* @param string sPesquisa Valor a ser pesquisado
* @param array aArray Array onde consultar o valor
* @return boolean true/false
**/
function inArray(sPesquisa, aArray) {
  if  (aArray.length == 0) return false;

  for (sInd in aArray) {
    if (aArray[sInd] == sPesquisa) {
      return true;
    }
  }
  return false;
};

/**
* searchArray(sPesquisa)
*
* Pesquisa um valor no array e se encontrar retorna o indice do array
*
* @author Diego Sampaio <diego@ditech.com.br>
* @access public
* @param string sPesquisa Valor a ser pesquisado
* @param array aArray Array onde consultar o valor
* @return mixed Chave do array ou false
**/
function searchArray(sPesquisa, aArray) {
  if  (aArray.length == 0) return false;

  for (sInd in aArray) {
    if (aArray[sInd] == sPesquisa) {
      return sInd;
    }
  }
  return false;
};

/**
 * Abre a tela de ajuda dos sistemas
 *
 * @author Diego Sampaio <diego@ditech.com.br>
 * @param string sModulo Módulo que será exibido o ajuda.
 * @param intenger iTopico ID do tópico que será aberto inicialmente (opcional)
 * @param string sAmbiente Ambiente
 * @return object Objeto da janela aberta.
 **/
function abreAjuda(sModulo) {
  var iTopico = '';
  var sAmbiente = 'P';

  // Segundo argumento define o tópico inicial a ser exibido
  if (arguments[1] != undefined && parseInt(arguments[1]) > 0) {
    iTopico = arguments[1];
  }

  // Terceiro parâmetro define se são arquivos de teste ou produção
  if (arguments[2] != undefined) {
    sAmbiente = arguments[2];
  }

  var iTop  = screen.height / 2 - 300;
  var iLeft = screen.width  / 2 - 400;

  return window.open('../inc/Ajuda.php?sModulo='+sModulo+'&iTopico='+iTopico+'&sAmbiente='+sAmbiente, 'telaAjuda', 'status=no, menubar=no, toolbar=no, resizable=yes, width=800, height=600, top='+iTop+', left='+iLeft+', scrollbars=yes');
}

/**
 * in_array()
 * Verifica se o valor existe no Array
 *
 * Modificado do original de Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 *
 * @author Marcelo Schmidt <marcelo@ditech.com.br>
 * @param string sValor - Valor a ser verificado
 * @param array aArray - Array a ser verificado
 * @return boolean
 */
function in_array(sValor, aArray) {
  for (sChave in aArray) {
    if (aArray[sChave] == sValor) {
      return true;
    }
  }
  return false;
}

/**
 * Algumas tela do DN e GC tem essa mesma função,
 * se alguma correção foi feita devera ser replicada em tais telas *
 **/
function formatNum(fNum, sTipo) {
  switch(sTipo) {
    case "PR":
      var bNegativo = fNum < 0;
      var sValor = number_format((bNegativo ? Math.abs(fNum) : fNum), 2, ",", ".");
      return (bNegativo ? '-' + sValor : sValor);
    break;
    case "DB":
      fNum = fNum.toString().replace(/\./g, '');
      fNum = fNum.replace(',', '.');
      return parseFloat(fNum);
    break;
  }
}

/* Made by Mathias Bynens <http://mathiasbynens.be/> */
function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 var e = a + '';
 var f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  var g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  var h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   var i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  var j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

//-->
