<!-- saved from url=(0022)http://internet.e-mail -->
<!-- SCRIPT LANGUAGE = "JavaScript" -->
<!--SCRIPT -->

var aJanela = new Array(10);

/* --------------------------------------------------------------------------------------------------------- */
/* Descrição: Inicializa as n posições do array com as qtdes de dias correspondente a cada mes               */
var daysInMonth = makeArray(12);
daysInMonth[1]  = 31;
daysInMonth[2]  = 29;
daysInMonth[3]  = 31;
daysInMonth[4]  = 30;
daysInMonth[5]  = 31;
daysInMonth[6]  = 30;
daysInMonth[7]  = 31;
daysInMonth[8]  = 31;
daysInMonth[9]  = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

/* ----------------------------------------- InitJanela ---------------------------------------------------- */
/* Descrição: Inicializa as 10 posições do array com valor zero                                              */
function InitJanela()
{
   for (var i = 1; i <= 20; i++)
     aJanela[i] = 0;
}

/* ----------------------------------------- FechaJanela --------------------------------------------------- */
/* Descrição: Fecha as janelas filhas que estão abertas.                                                     */
function FechaJanela ()
{
    for ( var i = 1; i <= 20; i++ )
    {
        if ( aJanela[i] != 0 )
          if ( !aJanela[i].closed )
            aJanela[i].close();
    }
}

/* ----------------------------------------- makeArray ----------------------------------------------------- */
/* Descrição: Inicializa as n posições do array com valor zero                                               */
function makeArray(n)
{
   for (var i = 1; i <= n; i++)
     this[i] = 0
   return this
}

/* ----------------------------------- VerificaPeriodo ----------------------------------------------------- */
/* Descrição: Verifica a qtde de dias existente entre duas datas                                             */
function VerificaPeriodo(earlyDate,laterDate)
{
    var earlySecs = earlyDate.getTime();
    var laterSecs = laterDate.getTime();
    if (Math.floor((((((laterSecs-earlySecs)/1000)/60)/60)/24))>=0 && Math.floor((((((laterSecs-earlySecs)/1000)/60)/60)/24))<=31)
      return true;
    return false;
}


/* ------------------------------------------- isEmpty ----------------------------------------------------- */
/* Descrição: Verifica se o campo esta vazio                                                                 */
function isEmpty(s)
{
   return ((s == null) || (s.length == 0))
}

/* ------------------------------------------- isNonnegativeInteger ---------------------------------------- */
/* Descrição: Verifica se o campo foi preenchido somente com números e se este é um número inteiro           */
function isNonnegativeInteger (s)
{
   var refStr = "0123456789";
   for (i = 0;i < s.length;i++)
      if (refStr.indexOf(s.substring(i,i + 1),0) == -1)
        return(false);
   return(true);
}

/* -------------------------------------------------- isYear ----------------------------------------------- */
/* Descrição: Verifica se o campo Ano esta vazio, se foi preenchido somente com números e com quatro dígitos */
function isYear (s)
{
   if (isEmpty(s))
     return false;
   if (!isNonnegativeInteger(s))
     return false;
   return (s.length == 4);
}

/* ------------------------------------------------- isMonth ----------------------------------------------- */
/* Descrição: Verifica se o campo Mês esta vazio, se foi preenchido somente com números e esta compreendido  */
/* entre 1 e 12 meses                                                                                        */
function isMonth (s)
{
   if (isEmpty(s))
     return false;
   if (!isNonnegativeInteger(s))
     return false;
   return ((s >= 1) && (s <= 12));
}

/* ------------------------------------------------- isDay ------------------------------------------------- */
/* Descrição: Verifica se o campo Dia esta vazio, se foi preenchido somente com números e esta compreendido  */
/* entre 1 e 31 dias                                                                                         */
function isDay (s)
{
   if (isEmpty(s))
     return false;
   if (!isNonnegativeInteger(s))
     return false;
   return ((s >= 1) && (s <= 31));
}


/* ---------------------------------------------- daysInFebruary ------------------------------------------- */
/* Descrição: Verifica se o Mês de fevereiro possui 28 ou 29 dias (ano bissexto)                             */
function daysInFebruary (year)
{
   return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

/* ---------------------------------------------- isDate --------------------------------------------------- */
/* Descrição: Verifica se a data esta correta                                                                */
function isDate (year, month, day)
{
   if (! (isYear(year) && isMonth(month) && isDay(day)))
     return false;
   var intYear  = parseInt(year);
   var intMonth = parseInt(month);
   var intDay   = parseInt(day);
   if (intDay > daysInMonth[intMonth])
     return false;
   if ((intMonth == 2) && (intDay > daysInFebruary(intYear)))
     return false;
   return true;
}

/* ---------------------------------------------- IsValidTime ---------------------------------------------- */
/* Descrição: Verifica se a hora esta no formato correto                                                     */
function IsValidTime(timeStr) {
    // Checks if time is in HH:MM:SS AM/PM format.
    // The seconds and AM/PM are optional.

    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

    var matchArray = timeStr.match(timePat);

    if (matchArray == null) {
        alert("Formato de hora inválido");
        return false;
    }

    hour = matchArray[1];
    minute = matchArray[2];
    second = matchArray[4];
    ampm = matchArray[6];

    if (second=="") { second = null; }
    if (ampm=="") { ampm = null }

    if (hour < 0  || hour > 23) {
        alert("Hora deve estar entre 0 e 23");
        return false;
    }
    if (minute<0 || minute > 59) {
        alert ("Minuto deve estar entre 0 e 59.");
        return false;
    }
    if (second != null && (second < 0 || second > 59)) {
        alert ("Segundo deve estar entre 0 e 59.");
        return false;
    }
    return true;
}

/* ---------------------------------- CampoObrigatorio ----------------------------------------------------- */
/* Descrição: Verifica se o dado campo foi preenchido                                                        */

function CampoObrigatorio(pCampo,pMsg)
{
  if (pCampo.value == "")
  {
     if (pMsg!="")
       alert(pMsg);
     return(false);
  }
  return(true);
}

/* ------------------------------- CampoValor ------------------------------- */
/* Descrição: Verifica se o dado campo foi preenchido somente com números     */

function CampoValor(pCampo, pMsg) {
    var i;
    var refStr = "0123456789.,+-";

    for (i = 0; i < pCampo.value.length; i++) {
        if (refStr.indexOf(pCampo.value.substring(i, i + 1), 0) == -1) {
            if (pMsg != "") {
                alert(pMsg);
            }
            return false;
        }
    }
    return true;
}

/* ----------------------------------------- CampoNumerico ------------------------------------------------- */
/* Descrição: Verifica se o dado campo foi preenchido somente com números                                    */

function CampoNumerico(pCampo,pMsg)
{
   var i;
   var refStr = "0123456789";
   for (i = 0;i < pCampo.value.length;i++)
   {
      if (refStr.indexOf(pCampo.value.substring(i,i + 1),0) == -1)
      {
         if (pMsg!="")
           alert(pMsg);
         /*pCampo.value = "";*/
         return false;
      }
   }
   return true;
}

/* ------------------------------------------- QtdeDigitos ------------------------------------------------- */
/* Descrição: Verifica se o dado campo foi preenchido somente com números e se possui o formato (tamanho)    */
/*            especificado.                                                                                  */

function QtdeDigitos ( pCampo, pTam, pMsg )
{
    var i;
    var refStr = "0123456789";

    if ( pCampo.value.length != pTam )
    {
        alert( "Atenção: Campo numérico de " + pTam + " dígitos.\nPor favor, digite apenas números nesse campo." );
        return false;
    }

    for ( i = 0; i < pCampo.value.length; i++ )
    {
        if ( refStr.indexOf ( pCampo.value.substring( i, i + 1 ), 0 ) == -1 )
        {
            if ( pMsg != "" )
              alert ( pMsg );
            return false;
        }
    }
    return true;
}

/* ----------------------------------------- Verifica CNPJ e CPF -------------------------------------------- */
/* Descrição: Verifica CNPJ e CPF.                                                                            */

function checkCPF(pCampo) {
    if (!pCampo || !pCampo.value) {
        return null;
    } else if (pCampo.value != "0") {
        var digits = extractNumbers(pCampo.value);
        var result = internalCheckCNPJCPF(digits);
        if (result != null && result != "CPF") {
            alert('"' + pCampo.value + '" não é um CPF válido');
            pCampo.select();
        } else {
            pCampo.value = formatCNPJCPF(digits);
        }
    }
}

function checkCNPJ(pCampo) {
    if (!pCampo || !pCampo.value) {
        return null;
    } else if (pCampo.value != "0") {
        var digits = extractNumbers(pCampo.value);
        var result = internalCheckCNPJCPF(digits);
        if (result != null && result != "CNPJ") {
            alert('"' + pCampo.value + '" não é um CNPJ válido');
            pCampo.select();
        } else {
            pCampo.value = formatCNPJCPF(digits);
        }
    }
}

function checkCNPJCPF(pCampo) {
    if (!pCampo || !pCampo.value) {
        return null;
    } else if (pCampo.value != "0") {
        var digits = extractNumbers(pCampo.value);
        var result = internalCheckCNPJCPF(digits);
        if (result == "INVALID") {
            alert('"' + pCampo.value + '" não é um CNPJ ou CPF válido');
            pCampo.select();
        } else {
            pCampo.value = formatCNPJCPF(digits);
        }
    }
}

function internalCheckCNPJCPF(digits) {
    if (!digits || !digits.length) {
        return "INVALID";
    } else if (digits.length == 11) {
        return mod11(digits, 9, true) && mod11(digits, 10, true)
            ? "CPF"
            : "INVALID";
    } else if (digits.length == 14) {
        return mod11(digits, 12, false) && mod11(digits, 13, false)
            ? "CNPJ"
            : "INVALID";
    } else if (digits.length == 15) {
        return mod11(digits, 13, false) && mod11(digits, 14, false)
            ? "CNPJ"
            : "INVALID";
    } else {
        return "INVALID";
    }
}

function extractNumbers(code) {
    var numbers = new Array();

    for(var i = 0; i < code.length; i++) {
        var c = code.charAt(i);
        if (c >= '0' && c <= '9') {
            numbers[numbers.length] = parseInt(c);
        } else if (c == "." || c == "/" || c == "-" || c == " ") {
            // ignorar caracteres da máscara e brancos
            ;
        } else {
            return null;
        }
    }

    return numbers;
}

function mod11(digits, n, isCPF) {
    var mod = 0;
    var mult = isCPF ? 2 : 9;

    for (var i = n - 1; i >= 0; i--) {
        mod += digits[i] * mult;
        mult = isCPF
            ? (mult > n ? n - 6 : mult + 1)
            : (mult == 2 ? 9 : mult - 1);
    }

    mod %= 11;
    if (isCPF) {
        mod = 11 - mod;
    }
    if (mod > 9) {
        mod = 0;
    }

    return digits[n] == mod;
}

function formatCNPJCPF(digits) {
    var temp = arrayToString(digits);
    if (temp.length == 11) {
        return temp.substring(0, 3) + "." + temp.substring(3, 6) + "." +
            temp.substring(6, 9) + "-" + temp.substring(9);
    } else if (temp.length == 14) {
        return temp.substring(0, 2) + "." + temp.substring(2, 5) + "." +
            temp.substring(5, 8) + "/" + temp.substring(8, 12) + "-" +
            temp.substring(12);
    } else if (temp.length == 15) {
        return temp.substring(0, 3) + "." + temp.substring(3, 6) + "." +
            temp.substring(6, 9) + "/" + temp.substring(9, 13) + "-" +
            temp.substring(13);
    } else {
        return temp;
    }
}

function arrayToString(array) {
    var temp = "";
    for (var i = 0; i < array.length; i++) {
        temp += String(array[i]);
    }
    return temp;
}

/* ----------------------------------------- Verifica numero ----------------------------------------------- */
/* Descrição: Verifica máscara do numero                                                                     */

function CheckInteger (pCampo)
{
    if (isEmpty(pCampo.value))
        return true;

    if (!isNonnegativeInteger(pCampo.value))
    {
        alert( "Valor invalido. Por favor, corrija-o." );
        pCampo.focus();
        pCampo.select();
        return false;
    }

    return true;
}

/* ----------------------------------------- Verifica Valor ------------------------------------------------ */
/* Descrição: Verifica máscara do valor.                                                                     */

function CheckValor (pCampo)
{
    if (isEmpty(pCampo.value))
        return true;

    if (!CampoValor(pCampo,""))
    {
        alert( "Valor invalido. Por favor, corrija-o." );
        pCampo.focus();
        pCampo.select();
        return false;
    }

    data = pCampo.value;
    data.replace(".", "");
    data.replace(",", ".");
    pCampo.value = data;

    return true;
}

/* ----------------------------------------- Verifica CEP -------------------------------------------------- */
/* Descrição: Verifica máscara do CEP.                                                                       */

function CheckCEP (pCampo)
{
    if (pCampo.value.length == 8 || pCampo.value.length == 10)
    {
        if (pCampo.value.length == 10)
        {
            var paux = pCampo.value;
            pCampo.value = paux.substring(0,2) + paux.substring(3,6) + paux.substring(7,10);
        }

        if (!CampoNumerico(pCampo,""))

        {
            alert( "Numero de CEP invalido. Por favor, corrija o valor do CEP no formato '99.999-99'." );
            pCampo.focus();
            pCampo.select();
            pCampo.value = paux;
            return false;
        }

        paux = pCampo.value;
        pCampo.value = paux.substring(0,2) + "." + paux.substring(2,5) + "-" + paux.substring(5,8);
        return true;
    }

    else
    {
        alert( "Numero de CEP invalido. Por favor, corrija o valor do CEP no formato '99.999-99'." );
        pCampo.focus();
        pCampo.select();
        return false;
    }
}

/* ----------------------------------------- Valida Data ------------------------------------------------- */
/* Descrição: Verifica máscara da Data.                                                                    */
function validaData(pCampo, nomeCampo)
{
        if (pCampo.value=="") {
          return true;
        }

        //  Versao GNU
        var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;
        var matchArray = pCampo.value.match(datePat); // is the format ok?
        if (matchArray == null)
        {
                alert("Por favor, coloque a data no seguinte formato: dd/mm/aaaa.")
                pCampo.focus();
                pCampo.select();
                return false;
        }
        day = matchArray[1]; // parse date into variables
        month = matchArray[3];
        year = matchArray[4];
        if (month < 1 || month > 12) // check month range
        {
                alert(nomeCampo + " possui uma data inválida (mês inválido)");
                pCampo.focus();
                pCampo.select();
                return false;
        }
        if (day < 1 || day > 31)
        {
                alert(nomeCampo + " possui uma data inválida (dia inválido)");
                pCampo.focus();
                pCampo.select();
                return false;
        }
        if ((month==4 || month==6 || month==9 || month==11) && day==31)
        {
                alert(nomeCampo + " possui uma data inválida (dia 31 não existe neste mês)");
                pCampo.focus();
                pCampo.select();
                return false;
        }
        if (month == 2)  // check for february 29th
        {
                var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
                if (day>29 || (day==29 && !isleap))
                {
                        alert(nomeCampo + " possui uma data inválida (ano não é bissexto)");
                        pCampo.focus();
                        pCampo.select();
                        return false;
                }
        }
        return true;  // date is valid
}

/* ----------------------------------------- Verifica Data ------------------------------------------------- */
/* Descrição: Verifica máscara da Data.                                                                      */

function CheckData (pCampo)
{
    if (pCampo.value.length == 8 || pCampo.value.length == 10)
    {
        if (pCampo.value.length == 10)
          var paux = pCampo.value.substring(0,2) + pCampo.value.substring(3,5) + pCampo.value.substring(6,10);

        else
        {
            if (!CampoNumerico(pCampo,""))
            {
                alert( "Data invalida. Por favor, corrija a data no formato '99/99/9999'." );
                pCampo.focus();
                pCampo.select();
                return false;
            }
           var paux = pCampo.value;
        }

        if (!isDate(paux.substring(4,8),paux.substring(2,4),paux.substring(0,2)))
        {
            alert( "Data invalida. Por favor, corrija a data no formato '99/99/9999'." );
            pCampo.focus();
            pCampo.select();
            return false;
        }

        pCampo.value = paux.substring(0,2) + "/" + paux.substring(2,4) + "/" + paux.substring(4,8);
        return true;
    }

    else
    {
        if (isEmpty(pCampo.value))
        {
                return true;
        }
        else
        {
            alert( "Data invalida. Por favor, corrija a data no formato '99/99/9999'." );
            pCampo.focus();
            pCampo.select();
            return false;
        }
    }
}

/* ----------------------------------------- Verifica Hora (hh:mm) ------------------------------------------------- */
/* Descrição: Verifica máscara da Hora (Formato hh:mm).                                                                      */

function CheckHoraHHMM (pCampo)
{
    if (pCampo.value.length == 4 || pCampo.value.length == 5)
    {
        var paux = pCampo.value;
        if (paux.length == 5) {
            if (paux.substring(2,3) != ":"){
                alert( "Hora invalida. Por favor, corrija a hora no formato '99:99'." );
                pCampo.focus();
                pCampo.select();
                return false;
            }

            paux = pCampo.value.substring(0,2) + pCampo.value.substring(3,5);
        }

        else if (!CampoNumerico(pCampo,""))
        {
            alert( "Hora invalida. Por favor, corrija a hora no formato '99:99'." );
            pCampo.focus();
            pCampo.select();
            return false;
        }

        paux = paux.substring(0,2) + ":" + paux.substring(2,4);

        if (!IsValidTime(paux))
        {
            //alert( "Hora invalida. Por favor, corrija a hora no formato '99:99'." );
            pCampo.focus();
            pCampo.select();
            return false;
        }

        pCampo.value = paux;
        return true;
    }

    else
    {
        if (isEmpty(pCampo.value))
        {
                return true;
        }
        else
        {
            alert( "Hora invalida. Por favor, corrija a hora no formato '99:99'." );
            pCampo.focus();
            pCampo.select();
            return false;
        }
    }
}

/* --------------------------- Notify Field Error ------------------------- */
/* Frequently used when the value of an input is invalid.                   */

function notifyFieldError(pCampo, pMsg) {

    alert(pMsg);
    pCampo.focus();
    pCampo.select();
    return false;
}

/* ----------------------------- Check Data/Hora -------------------------- */
/* Descrição: Verifica máscara da Data/Hora.                                */

function CheckDataHora(pCampo) {

    var msg = "Data invalida. Por favor, corrija a data para o formato '99/99/9999 99:99:99'.";

    // Ok. The field is empty.
    if (isEmpty(pCampo.value)) {
        return true;

    // Check the fields length for validity.
    } else if (pCampo.value.length != 14 && pCampo.value.length != 19) {
        return notifyFieldError(pCampo, msg);

    // Field's length is ok. Now check the values.
    } else {
        var dateAux = "";
        var timeAux = "";

        // Get date in "ddMMyyyy" format and time in "hh:mm:ss" format.
        if (pCampo.value.length == 14) {
            dateAux = pCampo.value.substring(0,8);
            timeAux = pCampo.value.substring(8,10) + ":"
                    + pCampo.value.substring(10,12) + ":"
                    + pCampo.value.substring(12,14);
        } else {
            dateAux = pCampo.value.substring(0,2)
                    + pCampo.value.substring(3,5)
                    + pCampo.value.substring(6,10);
            timeAux = pCampo.value.substring(11,19);
        }

        // Check if the values are valid.
        if (!isDate(dateAux.substring(4,8), dateAux.substring(2,4), dateAux.substring(0,2)) ||
            !IsValidTime(timeAux)) {
            return notifyFieldError(pCampo, msg);
        }

        // Set the value in the right format.
        pCampo.value = dateAux.substring(0,2) + "/"
                     + dateAux.substring(2,4) + "/"
                     + dateAux.substring(4,8) + " "
                     + timeAux;
        return true;
    }
}

/* ----------------------------- Check Hora -------------------------- */
/* Descrição: Verifica máscara da Hora.                                */

function CheckHora(pCampo) {

    var msg = "Hora invalida. Por favor, corrija a data para o formato '99:99:99'.";

    // Ok. The field is empty.
    if (isEmpty(pCampo.value)) {
        return true;

    // Check the fields length for validity.
    } else if (pCampo.value.length != 6 && pCampo.value.length != 8) {
        return notifyFieldError(pCampo, msg);

    // Field's length is ok. Now check the values.
    } else {
        var timeAux = "";

        // Get time in "hh:mm:ss" format.
        if (pCampo.value.length == 6) {
            timeAux = pCampo.value.substring(0,2) + ":"
                    + pCampo.value.substring(2,4) + ":"
                    + pCampo.value.substring(4,6);
        } else {
            timeAux = pCampo.value;
        }

        // Check if the values are valid.
        if (!IsValidTime(timeAux)) {
            return notifyFieldError(pCampo, msg);
        }

        // Set the value in the right format.
        pCampo.value = timeAux;

        return true;
    }
}

/* ---------------------------- CheckControle ----------------------------- */
/* Descrição: Verifica se o campo do tipo "controle" é válido.              */

function CheckControle(pCampo) {

    var msg = "Codigo de controle invalido. Por favor, corrija-o para o formato 'XXXyyyyMMddNNNNNNNNN'.";

    // Ok. The field is empty.
    if (isEmpty(pCampo.value)) {
        return true;

    // Check the fields length for validity.
    } else if (pCampo.value.length != 20) {
        return notifyFieldError(pCampo, msg);

    // Field's length is ok. Now check the values.
    } else if (!isNonnegativeInteger(pCampo.value.substring(11, 20)) ||
        !isDate(pCampo.value.substring(7, 11), pCampo.value.substring(5, 7), pCampo.value.substring(3, 5))) {
        return notifyFieldError(pCampo, msg);
    }
    return true;
}

/* ------------------------- VerificaObrigatorio -------------------------- */
/* Descrição: Verifica se o campo obrigatorio foi preenchido corretamente   */

function VerificaObrigatorio(pCampo)
{
   if (pCampo.type == "text")
   {
      if (!CampoObrigatorio(pCampo,"") ||
          !CampoNumerico(pCampo,""))
      {
         alert("Por favor, preencha o campo obrigatório.");
         pCampo.focus();
         return false;
      }
   }
   else
     if (pCampo.selectedIndex == 0)
     {
        alert("Por favor, preencha o campo obrigatório.");
        pCampo.focus();
        return false;
     }
   return true;
}

/* -------------------------------------------- AbreJanelaI ------------------------------------------------ */
/* Descrição: Abre uma janela no canto superior esquerdo.                                                    */

function AbreJanelaI ( pURL, pLargura, pAltura )
{
    var pos    = pURL.indexOf(".html");
    var posi   = pos - 4;
    var indice = pos - 4;
        indice = pURL.substring(indice,pos);

    if ( ( indice >= "a" && indice <= "z" ) || ( indice >= "A" && indice <= "Z" ) )
    {
        indice = pos - 5;
        indice = pURL.substring(indice,indice+1);
    }

    for ( var i = 0; i < indice.length; i++ )
       if ( indice.substring ( i, i + 1 ) != 0 )
          break;

    indice = indice.substring ( i, indice.length );

    aJanela[indice] = open ( pURL, pURL.substring(posi,pos), "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+pLargura+",height="+pAltura);
    aJanela[indice].moveTo ( 0, 0 );
}

/* ------------------------------------------- AbreJanelaII ------------------------------------------------ */
/* Descrição: Abre uma janela de busca no canto superior esquerdo, somente se o campo obrigatório estiver    */
/* preenchido.                                                                                               */

function AbreJanelaII ( pURL, pObrigatorio, pLargura, pAltura )
{
    if ( VerificaObrigatorio ( document.forms[0].elements[pObrigatorio] ) )
    {
        var pos    = pURL.indexOf(".html");
        var posi   = pos - 4;
        var indice = pos - 4;
        indice = pURL.substring(indice,pos);

        for ( var i = 0; i < indice.length; i++ )
           if ( indice.substring ( i, i + 1 ) != 0 )
             break;

        indice = indice.substring ( i, indice.length );

        aJanela[indice] = open ( pURL, pURL.substring(posi,pos), "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width="+pLargura+",height="+pAltura);
        aJanela[indice].moveTo ( 0, 0 );
    }
}

/* ------------------------------------------- JanelaImpressao --------------------------------------------- */
/* Descrição: Abre janela de Impressão de Guia.                                                              */

function JanelaImpressao(pURL,pLargura,pAltura)
{
    var pos = pURL.indexOf(".html");
    var posi   = pos - 5;
    var janela = open (pURL,pURL.substring(posi,pos),"toolbar=1,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width="+pLargura+",height="+pAltura);
    janela.moveTo ( 0, 0 );
}

/* ---------------------------------------------- RetornaI ------------------------------------------------ */
/* Descrição: Retorna um valor da busca para um dado campo da janela pai.                                   */

function RetornaI ( pValor, pCampo )
{
   opener.document.forms[0].elements[pCampo].value = pValor;
   self.close ();
}

/* ------------------------------------------- RetornaII --------------------------------------------------- */
/* Descrição: Retorna dois valores da busca para dois dados campos da janela pai.                            */
function RetornaII ( pValor1, pValor2, pCampo1, pCampo2 )
{
    opener.document.forms[0].elements[pCampo1].value = pValor1;

    var nome_aux = "";

    for ( var i=0; i<=pValor2.length; i++ )
    {
        if (pValor2.substring (i,i+1) == "+")
           nome_aux = nome_aux + " ";
        else nome_aux = nome_aux + pValor2.substring (i,i+1);
    }

    opener.document.forms[0].elements[pCampo2].value = nome_aux;
    self.close();
}

/* ------------------------------------------- RetornaIII -------------------------------------------------- */
/* Descrição: Retorna tres valores da busca para tres dados campos da janela pai.                            */
function RetornaIII ( pValor1, pValor2, pValor3, pCampo1, pCampo2, pCampo3 )
{
    opener.document.forms[0].elements[pCampo1].value = pValor1;
    opener.document.forms[0].elements[pCampo3].value = pValor3;

    var nome_aux = "";

    for ( var i=0; i<=pValor2.length; i++ )
    {
        if (pValor2.substring (i,i+1) == "+")
           nome_aux = nome_aux + " ";
        else nome_aux = nome_aux + pValor2.substring (i,i+1);
    }

    opener.document.forms[0].elements[pCampo2].value = nome_aux;
    self.close();
}

/* ------------------------------------------- Limpa ------------------------------------------------------ */
/* Descrição: Limpa os campos do dado formulário.                                                           */

function Limpa(f)
{
    tl = f.elements.length -1;

    for ( x = 0; x <= tl; x++ )
    {
        if ( f.elements[x].type != "hidden" )
        {
            if (f.elements[x].name == "pCd_Unimed")
              f.elements[x].value = "0022";

            else  f.elements[x].value = "";
        }
    }

    return;
}

/* ------------------------------------------- VerificaSobrenome ------------------------------------------ */
/* Descrição: Verifica se foi digitado pelo menos um sobrenome no campo.                                    */

function VerificaSobrenome(pCampo)
{
   for (i = 0;i < pCampo.value.length;i++)
     if(pCampo.value.substring(i,i + 1) == " ")
       break;
   if (i >= (pCampo.value.length - 1))
   {
      alert("Por favor, preencha este campo com pelo menos um sobrenome");
      pCampo.focus();
      return false;
   }
   else if (pCampo.value.substring(i+1,i+2) == " ")
        {
           alert("Por favor, preencha este campo com pelo menos um sobrenome");
           pCampo.focus();
           return false;
        }
   return true;
 }

/* ------------------------------------------- Le Maquina ------------------------------------------------- */
/* Descrição: Le as informações de código da máquia e volume do HD via atributos de uma applet Java.        */

function LeMaquina(pCampoMaq, pCampoVol)
{
  pCampoMaq.value = document.Leitor.serial;
  pCampoVol.value = document.Leitor.volume;
}

/* ----------------------------- currenyFormat ---------------------------- */
/* Descricao: faz a leitura de um campo, ja formatando o seu conteudo como  */
/*            dinheiro.                                                     */
/* uso =  ... onKeyPress="return(currencyFormat(this,',','.',event,8))"...  */

function currencyFormat(field, milSep, decSep, e, decPlaces) {

    var numbers = '0123456789';

    // Get the code and the matching key.
    var whichCode = window.Event ? e.which : e.keyCode;
    var key = String.fromCharCode(whichCode);

    // Check if the Enter was keypressed.
    if (whichCode == 13) {
        return true;

    // Check if it's not a valid key (not a number).
    } else if (numbers.indexOf(key) == -1) {
        return false;

    // Process the new number.
    } else {
        var result = '', i = 0;

        // Get only the numbers.
        for (i = 0; i < field.value.length; i++) {
            if (numbers.indexOf(field.value.charAt(i)) != -1) {
                result += field.value.charAt(i);
            }
        }

        // Put off the left zeros.
        for (i = 0; i < result.length && result.charAt(i) == '0'; i++);
        result = result.substr(i, result.length);

        // Check for available space.
        if (result.length < field.maxLength - 1) {

            // Append the new caracter.
            result += key;

            // Copy the formatted decimal part (from right to left).
            for (i = result.length; i <= decPlaces; i++) {
                result = '0' + result;
            }

            i = result.length - decPlaces;
            field.value = ',' + result.substr(i, result.length);

            // Copy the formatted integer part (from right to left).
            var count = 1;
            for (i -= 1; i >= 0; i--) {
                field.value = result.charAt(i) + field.value;
                if (count == 3 && i > 0) {
                    field.value = '.' + field.value;
                    count = 1;
                } else {
                    count++;
                }
            }
        }

        return false;
    }
}

/* ----------------------------- numericFormat ------------------------------ */
/* Description: Formats a number with custom thousand separator, decimal      */
/*              separator and number of decimal places.                       */
/* Parameters:                                                                */
/* - field     - input to be formatted                                        */
/* - thSep     - thousand separator character. If null, no separator is put.  */
/* - decSep    - decimal separator character. If null, no separator is put.   */
/* - decPlaces - number of decimal places. Makes no sense if decSep is null.  */
/* - signed    - if true, '-' and '+' are not ignored.                        */
/* -------------------------------------------------------------------------- */
function numericFormat(field, thSep, decSep, e, decPlaces, signed) {

	if (field.readonly) {
		return true;
	}
	    
    var numbers = '0123456789';
    var signals = '+-';

    // Get the code and the matching key.
    var whichCode = window.Event ? e.which : e.keyCode;
    var key = String.fromCharCode(whichCode);
    var signal = '';

    // Check if the Enter was keypressed.
    if (whichCode == 13) {
        return true;

    // Check if it's not a valid key (not a number).
    } else if (numbers.indexOf(key) == -1 && signals.indexOf(key) == -1) {
        return false;
    }

    // Gets the signal to append, if any.
    if (signals.indexOf(key) != -1) {
        if (!signed) {
            return false;
        } else {
            signal = key;
            key = (field.value == '') ? '0' : '';
        }
    } else if (field.value.length > 0 && signals.indexOf(field.value.charAt(0)) != -1) {
        signal = field.value.charAt(0);
        field.value = field.value.substr(1, field.value.length - 1);
    }

    // Process the new number.
    var result = '', i = 0;

    // Get only the numeric digits.
    for (i = 0; i < field.value.length; i++) {
        if (numbers.indexOf(field.value.charAt(i)) != -1) {
            result += field.value.charAt(i);
        }
    }

    // Put off the left zeros if the number accepts decimal places.
    if (decPlaces > 0) {
        for (i = 0; i < result.length && result.charAt(i) == '0'; i++);
        result = result.substr(i, result.length);
    }

    // Check for available space.
    if (result.length < field.maxLength || key == '') {

        // Append the new caracter.
        result += key;

        // Copy the formatted decimal part (from right to left), if any.
        i = result.length;
        field.value = '';

        if (decSep != null && decPlaces > 0) {
            for (; i <= decPlaces; i++) {
                result = '0' + result;
            }

            i = result.length - decPlaces;
            field.value = decSep + result.substr(i, result.length);
        }

        // Copy the formatted integer part (from right to left).
        if (thSep == null) {
            field.value = result.substr(0, i) + field.value;
        } else {
            var count = 1;
            for (i -= 1; i >= 0; i--) {
                field.value = result.charAt(i) + field.value;
                if (count == 3 && i > 0) {
                    field.value = thSep + field.value;
                    count = 1;
                } else {
                    count++;
                }
            }
        }
    }

    // Appends the signal, if any.
    if (signal != '') {
        field.value = signal + field.value;
    }

    return false;
}


/* ------------------------------------------- QtdeDigitos ------------------------------------------------- */
/* Descrição: Verifica se o dado campo foi preenchido somente com números e se possui o formato (tamanho)    */
/*            especificado.                                                                                  */

function QtdeDigitos ( pCampo, pTam, pMsg )
{
    var i;
    var refStr = "0123456789";

    if ( pCampo.value.length != pTam )
    {
        alert( "Atenção: Campo numérico de " + pTam + " dígitos.\nPor favor, digite apenas números nesse campo." );
        return false;
    }

    for ( i = 0; i < pCampo.value.length; i++ )
    {
        if ( refStr.indexOf ( pCampo.value.substring( i, i + 1 ), 0 ) == -1 )
        {
            if ( pMsg != "" )
              alert ( pMsg );
            return false;
        }
    }
    return true;
}


/* ----------------------------------------- Verifica CGC e CPF -------------------------------------------- */
/* Descrição: Verifica CGC e CPF.                                                                            */

function Modulo11( pNumero, pCalculo, pN )
{
  var i, j, aux, vResto;

  i = 1;
  aux = 0;
  if ( pCalculo == "CGC" ) {
    while (i < pN) {
      if (i >= 9) {
        j = i - 9 + 2;
      } else {
        j = i + 1;
      }
      aux = aux + eval( pNumero.charAt(pN - i - 1) ) * j;
      i = i + 1;
    }
  }
  else if (pCalculo == "CPF") {
    while ( i < pN ) {
      j = eval( pNumero.charAt( pN - i - 1 ) );
      aux = aux + j * (i + 1);
      i = i + 1;
    }
  } else
    return false;

  vResto = aux % 11;

  if ( ( ( 11 - vResto ) >= 10) || ( ( 11 - vResto ) == 0 ) )
    return false;
  else
    return( 11 - vResto );
}


function VerificaValidade( pNumero, pCalculo )
{
  var vN=0;

  if ( pCalculo == "CGC" ) {
    if ( pNumero.length != 14 && pNumero.length != 15)
      return false;
    vN = 13;
    while ( vN <= 14 ) {
      j = eval( pNumero.charAt( vN - 1 ) );
      if ( j != Modulo11( pNumero, "CGC", vN ) )
        return false;
      vN = vN + 1;
    }
  }
  else if (pCalculo == "CPF" ) {
    if ( pNumero.length != 11 )
      return false;
    vN = 10;
    while ( vN <= 11 ) {
     j = eval( pNumero.charAt( vN - 1 ) );
      if ( j != Modulo11(pNumero, "CPF", vN) )
        return false;
      vN = vN + 1;
    }
  }
  return true;
}

function CheckCGC (pCampo)
{
    if (isEmpty(pCampo.value))
        return true;

    if (pCampo.value.length == 15 || pCampo.value.length == 19 ||
        pCampo.value.length == 14 || pCampo.value.length == 18)
    {
        if (pCampo.value.length == 19)
        {
            var paux = pCampo.value;
            pCampo.value = paux.substring(0,3) + paux.substring(4,7) + paux.substring(8,11) + paux.substring(12,16) + paux.substring(17,19);
        }

        if (pCampo.value.length == 18)
        {
            var paux = pCampo.value;
            pCampo.value = paux.substring(0,2) + paux.substring(3,6) + paux.substring(7,10) + paux.substring(11,15) + paux.substring(16,18);
        }

        if (!CampoNumerico(pCampo,"") ||
            ! VerificaValidade( pCampo.value, "CGC" ))
        {
            alert( "Numero de CGC invalido. Por favor, corrija o valor do CGC no formato '999.999.999/9999-99'." );
            pCampo.focus();
            pCampo.select();
            pCampo.value = paux;
            return false;
        }

        paux = pCampo.value;
        pauxsize = paux.length;
        pCampo.value = paux.substring(0,pauxsize-12) + "." + paux.substring(pauxsize-12,pauxsize-9) + "." + paux.substring(pauxsize-9,pauxsize-6) + "/" + paux.substring(pauxsize-6,pauxsize-2) + "-" + paux.substring(pauxsize-2,pauxsize);
        return true;
    }

    else
    {
        alert( "Numero de CGC invalido. Por favor, corrija o valor do CGC no formato '999.999.999/9999-99'." );
        pCampo.focus();
        pCampo.select();
        return false;
    }
}

/* ------------------------------------------- currenyFormatPU ------------------------------------------------- */
/* Descrição: faz a leitura de um campo, ja formatando o seu conteudo como dinheiro                            */
/* uso =  ...  onKeyPress="return(currencyFormat(this,',','.',event))" ...                                     */

/*
function currencyFormatPU(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
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 (strCheck.indexOf(key) == -1) return false;  // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0000000' + aux;
if (len == 2) fld.value = '0'+ decSep + '000000' + aux;
if (len == 3) fld.value = '0'+ decSep + '00000' + aux;
if (len == 4) fld.value = '0'+ decSep + '0000' + aux;
if (len == 5) fld.value = '0'+ decSep + '000' + aux;
if (len == 6) fld.value = '0'+ decSep + '00' + aux;
if (len == 7) fld.value = '0'+ decSep + '0' + aux;
if (len == 8) fld.value = '0'+ decSep + aux;
if (len > 8) {
aux2 = '';
for (j = 0, i = len - 9; i >= 0; i--) {
if (j == 9) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 8, len);
}
return false;
}
*/


/* ----------------------------- numericFormat ------------------------------ */
/* Description: Formats a number with custom thousand separator, decimal      */
/*              separator and number of decimal places.                       */
/* Parameters:                                                                */
/* - field     - input to be formatted                                        */
/* - thSep     - thousand separator character. If null, no separator is put.  */
/* - decSep    - decimal separator character. If null, no separator is put.   */
/* - decPlaces - number of decimal places. Makes no sense if decSep is null.  */
/* -------------------------------------------------------------------------- */
function numericFormat(field, thSep, decSep, e, decPlaces) {

    if (field.readonly) {
    	return true;
    }
    
    var numbers = '0123456789';

    // Get the code and the matching key.
    var whichCode = window.Event ? e.which : e.keyCode;
    var key = String.fromCharCode(whichCode);

    // Check if the Enter was keypressed.
    if (whichCode == 13) {
        return true;

    // Check if it's not a valid key (not a number).
    } else if (numbers.indexOf(key) == -1) {
        return false;

    // Process the new number.
    } else {
        var result = '', i = 0;

        // Get only the numeric digits.
        for (i = 0; i < field.value.length; i++) {
            if (numbers.indexOf(field.value.charAt(i)) != -1) {
                result += field.value.charAt(i);
            }
        }

        // Put off the left zeros if the number accepts decimal places.
        if (decPlaces > 0) {
            for (i = 0; i < result.length && result.charAt(i) == '0'; i++);
            result = result.substr(i, result.length);
        }

        // Check for available space.
        if (result.length < field.maxLength) {

            // Append the new caracter.
            result += key;

            // Copy the formatted decimal part (from right to left), if any.
            i = result.length;
            field.value = '';

            if (decSep != null && decPlaces > 0) {
                for (; i <= decPlaces; i++) {
                    result = '0' + result;
                }

                i = result.length - decPlaces;
                field.value = decSep + result.substr(i, result.length);
            }

            // Copy the formatted integer part (from right to left).
            if (thSep == null) {
                field.value = result.substr(0, i) + field.value;
            } else {
                var count = 1;
                for (i -= 1; i >= 0; i--) {
                    field.value = result.charAt(i) + field.value;
                    if (count == 3 && i > 0) {
                        field.value = thSep + field.value;
                        count = 1;
                    } else {
                        count++;
                    }
                }
            }
        }

        return false;
    }
}

//  End -->
<!--/SCRIPT -->
