/* Rotina para confirmação de exclusão, sendo necessário passar os seguintes
 * parâmetros:
 * id --> código identificador do registro a ser excluído.
 *            Exemplo: 10
 * url -> endereço complementar da lógica de exclusão.
 *            Exemplo: "pais.remove.logic?pais.id="
 */
var key_backspace = 8;
    key_tab       = 9;
    key_enter     = 13;
    key_delete    = 46;
    key_X         = 88;
    key_left      = 37;
    key_right     = 39;
    key_control   = 17;
    key_home      = 36;
    key_end       = 35;
    key_ponto     = 190;
    vezes         = 106;
    mais          = 107;
    menos         = 109;
    virgula       = 110;
    divide        = 111;
    ponto         = 194;
    ok            = false;
    
var groupCache = {};

/* -------------------------------------------------------------------------- */

function showWaiting() {
    var divLayer   = $("divLayer");
    divLayer.style.visibility = "visible";
    divLayer.innerHTML = "<b><img src='img/loading11.gif' alt='Aguarde...' title='Aguarde...' align='center' valign='middle' border='0'>&nbsp;&nbsp;<br>Processando requisição.</img></b>";
}

function getElementsById(id){
    if (!groupCache[id]){
        groupCache[id] = [];
    }
    var nodes = groupCache[id];
    for(var x=0; x<nodes .length; x++){
        if (nodes[x].id != ""){
        nodes.splice(x, 1);
        x--;
        }
    }
    var tmpNode = document.getElementById(id);
    while(tmpNode){
        nodes.push(tmpNode);
        tmpNode.id = "";
        tmpNode = document.getElementById(id);
    }
    return nodes;
}    

/* -------------------------------------------------------------------------- */

function setFocus() {
    var inputs = document.getElementsByTagName('input');
    if (inputs != null) {
        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i] != null && inputs[i].getAttribute('type') == "text" && !inputs[i].disabled) {
                inputs[i].focus();
                inputs[i].select();
                break;
            }
        }
    }
    return true;
}

/* -------------------------------------------------------------------------- */

function unFormatNumber(value, removeAllMask) {
    // return String(pNum).replace(/\D/g, "").replace(/^0+/, "");

    value = value.toString();

    if (removeAllMask == null) {
        removeAllMask = false;
    }

    if (value.indexOf(',') > 0) {
        value = value.replace(/\./g, '');
        value = value.replace(/\,/g, '.');
    }
    if ((value.indexOf('.') > 0) && (value.substring(value.indexOf('.')+1, 2)).length <= 1) {
        value = value + '0';
    }

    if (removeAllMask) {
        value = value.replace(/\./g, '').replace(/\,/g, '');
    }

    return value;
}

function formatNumber(value, thousandSeparator, decimalSeparator) {

    // check for missing parameters and use defaults if so
    if (thousandSeparator == null) {
        thousandSeparator = ".";
    }
    if (decimalSeparator == null) {
        ecimalSeparator = ",";
    }

    // need a string for operations
    value = value.toString();
    value = value.replace(thousandSeparator, decimalSeparator);

    // separate the whole number and the fraction if possible
    a = value.split(decimalSeparator);
    x = a[0]; // decimal
    y = a[1]; // fraction
    z = "";

    if (typeof(x) != "undefined") {
        // reverse the digits. regexp works from left to right.
        for (i=x.length-1; i>=0; i--)
            z += x.charAt(i);

        // add seperators. but undo the trailing one, if there
        z = z.replace(/(\d{3})/g, "$1" + thousandSeparator);
        if (z.slice(-thousandSeparator.length) == thousandSeparator)
            z = z.slice(0, -thousandSeparator.length);
        x = "";

        // reverse again to get back the number
        for (i=z.length-1; i>=0; i--)
            x += z.charAt(i);

        // add the fraction back in, if it was there
        if ((typeof(y) != "undefined") && (y.length > 0))
            x += decimalSeparator + y;
    }
    return x;
}

/* -------------------------------------------------------------------------- */

function trim(value) {
    return value.toString().replace(/^\s*|\s*$/g, '');
}

/* -------------------------------------------------------------------------- */

function arredondaValor(valor , casas) {
return parseFloat(Math.round(valor * Math.pow(10, casas)) / Math.pow(10, casas));
}

/* -------------------------------------------------------------------------- */

function somarHoras(horaInicial, horaFinal, formatarHora) {
    var date1 = new Date(); // new Date(ano, mes, dia, hora, minutos, segundos);
    var date2 = new Date(); // new Date(1970, 0, 1);

    date1.setHours(parseInt(horaInicial.split(":")[0].toString(), 10));  
    date1.setMinutes(parseInt(horaInicial.split(":")[1].toString(), 10));  

    date2.setHours(parseInt(horaFinal.split(":")[0].toString(), 10));  
    date2.setMinutes(parseInt(horaFinal.split(":")[1].toString(), 10));  
    
    var time = date2.getTime() - date1.getTime();  
    var horas = time / 3600000;  
    if (formatarHora == null || formatarHora == false) 
        var resultado = parseInt(horas, 10) + parseInt(((time % 3600000) / 60000), 10);
    else     
        var resultado = parseInt(horas, 10) + ":" +  parseInt(((time % 3600000) / 60000), 10);
    return resultado;
}

/* -------------------------------------------------------------------------- */

function obterFaixaEtaria(input, idElement) {
    var dtNascimento = input.value;
    var dtAtual      = formatDate(new Date(), "dd/MM/yyyy");

    dtNascimento     = dtNascimento.split("/");
    dtAtual             = dtAtual.split("/");

    if (dtNascimento[0] > 31 || dtNascimento[1] > 12 || dtNascimento[2] > dtAtual[2]) {
        alert("Data de Nascimento invalida!");
        return false;
    } else {
        var resultado   = dtAtual[2] - dtNascimento[2];
        var faixaEtaria = -1;

        if ((dtAtual[1] < dtNascimento[1]) || ((dtAtual[1]==dtNascimento[1]) && (dtAtual[0] < dtNascimento[0]))) {
            resultado -= 1;
        }

        // Sempre verificar o enumerador TipoDeFaixaEtaria.java

        if (resultado >= 1 && resultado <= 17) { // ATE_17
            faixaEtaria = 0;
        } else if (resultado >= 18 && resultado <= 24) { // ENTRE_18_24
            faixaEtaria = 1;
        } else if (resultado >= 25 && resultado <= 45) { // ENTRE_25_45
            faixaEtaria = 2;
        } else if (resultado >= 46 && resultado <= 64) { // ENTRE_46_64
            faixaEtaria = 3;
        } else if (resultado >= 65) { // ACIMA_65
            faixaEtaria = 4;
        } else { // NAO_DECLARADA
            faixaEtaria = 5;
        }

        document.getElementById(idElement).selectedIndex = faixaEtaria;
        return true;
    }
}

/* -------------------------------------------------------------------------- */

function retornaLabelDoCombo(combobox) {
    if (document.getElementById(combobox).selectedIndex >= 0)
        return document.getElementById(combobox).options[document.getElementById(combobox).selectedIndex].label;
    else
        return null;
}

/* -------------------------------------------------------------------------- */

function retornaTextoDoCombo(combobox) {
    if (document.getElementById(combobox).selectedIndex >= 0)
        return document.getElementById(combobox).options[document.getElementById(combobox).selectedIndex].text;
    else
        return null;
}

/* -------------------------------------------------------------------------- */

function retornaIdDoCombo(combobox) {
    if (document.getElementById(combobox).selectedIndex >= 0)
        return document.getElementById(combobox).options[document.getElementById(combobox).selectedIndex].value;
    else
        return null;
}

/* -------------------------------------------------------------------------- */

function ConfirmarExclsao(id, url)
{
    if (!id) return;
    var opt = confirm("Confirma a exclusão do registro?");

    if (opt==true)
        window.location = url+id;
}

function ConfirmarCopia(id, url)
{
    if (!id) return;
    var opt = confirm("Confirma a cópia deste registro?");

    if (opt==true)
        window.location = url+id;
}

/* -------------------------------------------------------------------------- */

function FormatarData(input, teclapres, bValidadeDate, bValidadeYear)
{
    var tammax = 10;
    var    tam = 0;
        
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    if (bValidadeYear == null || bValidadeYear == "") {
        bValidadeYear = false;
    }
    if (bValidadeDate == null || bValidadeDate == "") {
        bValidadeDate = false;
    }

    if ((input.value.length < tammax) &&
    (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (input.value.length == 2 || input.value.length == 5) 
            input.value = input.value + "/";
    } else if ((input.value.length = tammax) &&
               (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        teclapres.returnValue = true;           
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    tam = input.value.length;
    if (tecla==key_backspace)
        tam = tam - 1;
    if (tam >= tammax && bValidadeDate)
        teclapres.returnValue = ValidarData(input, bValidadeYear);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function ValidarData(input, bValidate)
{
    var reDate      = /^((0[1-9]|[12]\d)\/(0[1-9]|1[0-2])|30\/(0[13-9]|1[0-2])|31\/(0[13578]|1[02]))\/\d{4}$/;
    var currentDate = new Date();
    var bReturn     = false;

    if (input == null || input.value == null || input.value == "") {
        bReturn = true;
    } else {
        if (reDate.test(input.value))    {
            if (bValidate==true || bValidate==null) {
                var inputDate = new Date(input.value);
                bReturn = (inputDate.getFullYear() >= currentDate.getFullYear());
            } else {
                bReturn = true;
            }
        } else if (input.value != null && input.value != "") {
            bReturn = false;
        }
    }
    if (!bReturn) {
        alert("ATENÇÃO! "+ input.value +" não é uma data válida ou permitida.");
        input.value = "";
        input.focus();
    }
    return(bReturn);
}

/* -------------------------------------------------------------------------- */

function FormatarHora(input, teclapres)
{
    var tammax = (parseInt(input.getAttribute('maxlength')) >= 10 ? 10 : parseInt(input.getAttribute('maxlength')))-1;
    var    tam = 0;
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    if ((input.value.length < tammax) &&
    (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (input.value.length == 2 || input.value.length == 5) 
            input.value = input.value + ":";
    } else if ((input.value.length = tammax) &&
               (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
           teclapres.returnValue = true;
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    tam = input.value.length;
    if (tecla==key_backspace)
        tam = tam - 1;
    if (tam >= tammax)
        teclapres.returnValue = ValidarHora(input);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarNumeroRG(input, teclapres)
{
    // input.value = input.value.toUpperCase();
    
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    // alert(tecla);

    var returnValue = false;

    if (somenteNumeros(tecla) || 
        somenteLetras(tecla) || 
        (tecla==key_backspace) || 
        (tecla==key_tab) || 
        (tecla==key_enter) || 
        (tecla==key_delete) ||
        (tecla==key_left) || 
        (tecla==key_right) || 
        (tecla==key_home) || 
        (tecla==key_end)) {
    // if ((eval(fromKeyCodeToNumber(tecla)) >= 0 &&
    // eval(fromKeyCodeToNumber(tecla)) <= 9) ||
    // (tecla >= 65 && tecla <= 90) ||
    // (tecla >= 96 && tecla <= 105) ||
    // (tecla==key_backspace) || (tecla==key_tab) || (tecla==key_enter) ||
    // (tecla==key_delete)) {
        returnValue = true;
    } else {
        returnValue = false;
    }

    // if (returnValue)
    // input.value = input.value.toUpperCase();

    teclapres.returnValue = returnValue;
    return(returnValue);
}

// Utilizado internamente.
function somenteNumeros(keyCode) {
    return (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105); // 0..9
}

// Utilizado internamente.
function somenteLetras(keyCode) {
    return (keyCode >= 65 && keyCode <= 90); // A..Z
            
}

/* -------------------------------------------------------------------------- */

function limpaCampo(field) {
    var t_field = '';

    for (i=0; i<field.length; i++) {
        if ( (field.charAt(i) != ".") && (field.charAt(i) != "-") && (field.charAt(i) != "/") && (field.charAt(i) != ",") && (field.charAt(i) != ":")) {
            t_field = t_field + field.charAt(i);
        }
    }

    return t_field;
}

function ValidarHora(cHora)
{
    var hora = limpaCampo(cHora.value)+"000000";
        hora = hora.substr(0, 6);

    var tam = hora.length;

    if (tam != 6)
    {
        alert('A hora está incorreta');
        cHora.value = "";
        cHora.focus();
        return(false);
    }

    var hr = hora.substr(0,2);
    var min = hora.substr (2,2);
    var seg = hora.substr (4,2);

    if (hr > 23 || min > 59 || seg > 59)
    {
        alert('A hora está incorreta');
        cHora.value = "";
        cHora.focus();
        return(false);
    } else
        return true;
}

/* -------------------------------------------------------------------------- */

function FormatarTelefone(input, teclapres) {
    var tammax = 15;
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    // alert(tecla);

    if ((input.value.length < tammax) &&
        (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        /*
        if (input.value.length==1)
            input.value = input.value + "xx"
        else if (input.value.length==5)
            input.value = input.value + " "
        else if (input.value.length==10)
            input.value = input.value + "-";
         */
        if (input.value.length==2)
            input.value = input.value + " "
        else if (input.value.length==7)
            input.value = input.value + "-";
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete || tecla==key_left || tecla==key_right);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function getCursorPosition(input) {
    var iCaretPos = 0;
    if (document.selection) { // IE Support
        input.focus();
        var oSel = document.selection.createRange();
        oSel.moveStart('character', -input.value.length);
        iCaretPos = oSel.text.length;
    } else if (input.selectionStart || input.selectionStart == '0') // Firefox support
        iCaretPos = input.selectionStart;

    return iCaretPos;
}

/* -------------------------------------------------------------------------- */

function setCursorPosition(input, iCaretPos) {
    if (document.selection) { // Internet Explorer Support
        input.focus();
        var range = input.createTextRange();
        range.collapse(true);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.selectionStart /*|| input.selectionStart == '0'*/) { // Firefox, Opera, Safari support
        input.focus();
        input.setSelectionRange(iCaretPos, iCaretPos);
    }
}

/* -------------------------------------------------------------------------- */

function setSelectionRange(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) { // Firefox, Opera, Safari
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    } else if (input.createTextRange) { // Internet Explorer
        var range = input.createTextRange();
        range.collapse(true);
        range.moveStart('character', selectionStart);
        range.moveEnd('character', selectionEnd);
        range.select();
    }
}

/* -------------------------------------------------------------------------- */

function UpperCase(input, event) {
    if (input.setSelectionRange) // Firefox, Opera, Safari
        var sel = input.selectionStart;
    else 
        var sel = getCursorPosition(input);
    
    input.value = input.value.toUpperCase();
    setCursorPosition(input, sel);
    
    return true;
}

/* -------------------------------------------------------------------------- */

function LowerCase(input, event) {
    if (input.setSelectionRange) // Firefox, Opera, Safari
        var sel = input.selectionStart;
    else 
        var sel = getCursorPosition(input);
    
    input.value = input.value.toLowerCase();
    setCursorPosition(input, sel);

    return true;
}

/* -------------------------------------------------------------------------- */

function replaceAll(string, token, newtoken) {
    var minha_er = new RegExp("/"+ token +"/gi");
    var string_retorno = string.replace(minha_er, newtoken);
    return string_retorno;
    
// while (string.indexOf(token) != -1) {
// string = string.replace(token, newtoken);
// }
// return string;
}

/* -------------------------------------------------------------------------- */

function RetirarAcentos(input)
{
    var val = input.value;
    var comAcento = '"';
    var semAcento = "'";
    var retorno   = "";
    retorno = replaceAll(val, comAcento, semAcento);
    
   /* Por ordem do Dr. Sérgio, não deverá mais remover as acentuações. */
// var comAcento =
// '¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ"';
// var semAcento =
// 'YuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy''';
// var pos;
// for (var i=0; i < val.length; i++) {
// pos = comAcento.indexOf(val.charAt(i));
// if (pos > -1)
// retorno += semAcento.charAt(pos);
// else
// retorno += val.charAt(i);
// }
    return (retorno);
}

/* -------------------------------------------------------------------------- */

function LimparCampo(valor, validos) {
    // retira caracteres invalidos da string
    var result = "";
    var aux;
    for (var i=0; i < valor.length; i++) {
        aux = validos.indexOf(valor.substring(i, i+1));
        if (aux>=0)
            result += aux;
    }
    return result;
}

/* -------------------------------------------------------------------------- */

function ArredondaValor(valor) // esta função arredonda valor com 2 casa
                                // decimais
{
    valor  = valor.toString();                // transforma em strings
    valor  = valor.replace(",","");              // transforma em strings
    var nponto = valor.indexOf(".");          // pega a posição do ponto

    if (nponto==-1)
    nfinal=valor.substring(0,valor.length-2)+"."+valor.substring(valor.length - 2,valor.length)
    else
    nfinal = valor.substring(0,nponto+3);  // retorna valor arredondado
    return nfinal;
}

/* -------------------------------------------------------------------------- */

function FormatarValor(input, tammax, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    // input.value = LimparCampo(input.value, "0123456789");

    vr = input.value;
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace(",", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");

    tam = vr.length;
    len = input.value.length;

    if ((len+1 > tammax) && tecla != key_backspace) {
        teclapres.returnValue = false;
        return(teclapres.returnValue);
    }

    if (tam < tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((len <= tammax) &&
        (tecla==key_backspace || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (tam <= 2)
            input.value = vr
        else if (tam > 2 && tam <= 5)
            input.value = vr.substr(0, tam - 2) + ',' + vr.substr(tam - 2, tam)
        else if (tam >= 6 && tam <= 8)
            input.value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam)
        else if (tam >= 9 && tam <= 11)
            input.value = vr.substr(0, tam - 8) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam)
        else if (tam >= 12 && tam <= 14)
            input.value = vr.substr(0, tam - 11) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam)
        else if (tam >= 15 && tam <= 17)
            input.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + ',' + vr.substr(tam - 2, tam);
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarPercentual(input, tammax, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    vr = input.value;
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace(",", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    tam = vr.length;

    if (tam < tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((input.value.length < tammax) &&
        (tecla==key_backspace || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105))
    {
        if (tam <= 3)
            input.value = vr
        else if (tam > 3 && tam <= 6)
            input.value = vr.substr(0, tam - 3) + ',' + vr.substr(tam - 3, tam);
    }
    else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarQuantidade(input, tammax, teclapres)
{
    return FormatarPercentual(input, tammax, teclapres);
}

/* -------------------------------------------------------------------------- */

function FormatarNumero(input, tammax, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    vr = input.value;
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace(",", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    tam = vr.length;
    len = input.value.length;

    if ((len+1 > tammax) && tecla != key_backspace) {
        teclapres.returnValue = false;
        return(teclapres.returnValue);
    }

    if (tam < tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((len <= tammax) &&
        (tecla==key_backspace || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (tam <= 3)
            input.value = vr
        else if (tam > 3 && tam <= 6)
            input.value = vr.substr(0, tam - 3) + '.' + vr.substr(tam - 3, tam)
        else if (tam >= 7 && tam <= 9)
            input.value = vr.substr(0, tam - 6) + '.' + vr.substr(tam - 6, 3) + '.' + vr.substr(tam - 3, tam)
        else if (tam >= 10 && tam <= 12)
            input.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '.' + vr.substr(tam - 6, 3) + '.' + vr.substr(tam - 3, tam)
        else if (tam >= 13 && tam <= 15)
            input.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '.' + vr.substr(tam - 6, 3) + '.' + vr.substr(tam - 3, tam)
        else if (tam >= 16 && tam <= 18)
            input.value = vr.substr(0, tam - 15) + '.' + vr.substr(tam - 15, 3) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '.' + vr.substr(tam - 6, 3) + '.' + vr.substr(tam - 3, tam);
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarCNPF(input, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;
    var tammax = 14;

    teclapres.returnValue = true;

    vr = input.value;
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace(",", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    tam = vr.length;
    len = input.value.length;

    // if ((len+1 > tammax) && (tecla!=key_backspace || tecla!=key_tab ||
    // tecla!=key_delete)) {
    // teclapres.returnValue = false;
    // return(teclapres.returnValue);
    // }

    if (tam < tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((len <= tammax) && (tecla==key_backspace || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (tam <= 2)
            input.value = vr
        else if (tam > 2 && tam <= 5)
            input.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 6 && tam <= 8)
            input.value = vr.substr(0, tam - 5) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 9 && tam <= 11)
            input.value = vr.substr(0, tam - 8) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 12 && tam <= 14)
            input.value = vr.substr(0, tam - 11) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 15 && tam <= 17)
            input.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarCNPJ(input, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;
    var tammax = 18;

    teclapres.returnValue = true;

    vr = input.value;
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    vr = vr.replace(",", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    vr = vr.replace("-", "");
    tam = vr.length;
    len = input.value.length;

    if ((len+1 > tammax) && tecla != key_backspace) {
        teclapres.returnValue = false;
        return(teclapres.returnValue);
    }

    if (tam < tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((len <= tammax) &&
    (tecla==key_backspace || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (tam <= 2)
            input.value = vr
        else if (tam > 2 && tam <= 6)
            input.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 7 && tam <= 9)
            input.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 10 && tam <= 12)
            input.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 13 && tam <= 14)
            input.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam)
        else if (tam >= 15 && tam <= 17)
            input.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function validarCNPJ(input) {
var CNPJ = input.value;
var a = new Array();
var b = new Number;
var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
for (i=0; i<12; i++) {
a[i] = CNPJ.charAt(i);
b += a[i] * c[i+1];
}
if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
b = 0;
for (y=0; y<13; y++) {
b += (a[y] * c[y]);
}
if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
return false;
}
return true;
}

/* -------------------------------------------------------------------------- */

function FormatarCEP(input, teclapres)
{
    var tammax = 9;
        tam = 0;
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    if ((input.value.length < tammax) &&
        (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)) {
        if (input.value.length==5)
            input.value = input.value + "-";
    } else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    tam = input.value.length;
    if (tecla==key_backspace)
        tam = tam - 1;

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function ValidarAgenciaConta(input, tammax, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    if (tammax > 0 && input.value.length >= tammax)
        teclapres.returnValue = false
    else
        teclapres.returnValue = (tecla==45 || tecla >= 48 && tecla <= 57);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarNrAgenciaConta(input, tammax, pos, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    vr = input.value;
    vr = vr.replace("-", "");
    vr = vr.replace(".", "");
    vr = vr.replace("/", "");
    tam = vr.length ;

    if (tam <= tammax && tecla != key_backspace)
        tam = vr.length + 1;

    if (tecla==key_backspace)
        tam = tam - 1;

    if ((input.value.length < tammax) &&
        (tecla==key_backspace || tecla==key_backspace8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105))
    {
        if (tam <= 2)
            input.value = vr
        else if (tam > pos && tam <= tammax)
            input.value = vr.substr(0, tam - pos) + '-' + vr.substr(tam - pos, tam);
    }
    if (tammax > 0 && tam >= (tammax+1))
        teclapres.returnValue = false
    else
        teclapres.returnValue = (tecla==key_backspace || tecla==key_tab || tecla==key_delete);

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function FormatarMesAno(Input, teclapres)
{
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    teclapres.returnValue = true;

    vr = Input.value;
    vr = vr.replace(".", "");
    vr = vr.replace("-", "");
    vr = vr.replace("/", "");
    vr = vr.replace("/", "");
    tam = vr.length + 1;

    if ((tecla != 9 && tecla != key_backspace) && (tam > 2 && tam < 7))
        Input.value = vr.substr(0, 2) + '/' + vr.substr(2, tam)
    else
        teclapres.returnValue = false;

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function ValidarEmail(input)
{
    var reEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}) {3}\])$/;
    if (reEmail.test(input.value))
    {
        // alert(input.value + " é um endereço de e-mail válido.");
        return true;
    }
    else if (input.value != null && input.value != "")
    {
        alert(input.value + " NÃO é um endereço de e-mail válido.");
        input.focus();
        return(false);
    }
}

/* -------------------------------------------------------------------------- */

function ValidarNumero(input, teclapres, adicional)
{
    if (adicional==null)
        adicional = false;

    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
        var tecla = teclapres.which;
    else // Outros browser´s
        var tecla = teclapres.keyCode;

    //alert(tecla);
    teclapres.returnValue = ((tecla==key_backspace || tecla==key_tab || tecla==key_delete) || (tecla==key_enter) ||
                             somenteNumeros(tecla) ||
                            (adicional && (tecla==ponto || tecla==key_ponto || tecla==divide || tecla==menos || tecla==key_X)));

    return(teclapres.returnValue);
}

/* -------------------------------------------------------------------------- */

function formatarNumeroProjeto(input, teclapres) {
    if (document.all) // Internet Explorer
        var tecla = teclapres.keyCode;
    else if (document.layers) // Nestcape
    var tecla = teclapres.which;
    else // Outros browser´s
    var tecla = teclapres.keyCode;

teclapres.returnValue = ((tecla==key_backspace || tecla==key_tab || tecla==key_delete || tecla == key_control) || (tecla==key_enter) ||
                          somenteNumeros(tecla) ||
                          (tecla==menos && input.value.indexOf('-') < 0));
/*
    if (teclapres.returnValue) {
        if (input.value.length == 4 && tecla != key_backspace) {
            input.value = input.value + "-";
        } else if (input.value.length == 6 && tecla == key_backspace) {
            input.value = input.value.substr(0, 5);
        }
    }
*/
    return teclapres.returnValue;
}

/* --------------------------------------------------------------------------
    Util para receber o char correto do bloco de numeros
    ao lado esquerdo do teclado.
*/

function fromKeyCodeToNumber(keyCode) {

    switch(keyCode) {
        case 96, 48: return "0"; break;
        case 97, 49: return "1"; break;
        case 98, 50: return "2"; break;
        case 99, 51: return "3"; break;
        case 100, 52: return "4"; break;
        case 101, 53: return "5"; break;
        case 102, 54: return "6"; break;
        case 103, 55: return "7"; break;
        case 104, 56: return "8"; break;
        case 105, 57: return "9"; break;
        default: return String.fromCharCode(keyCode);
        break;
    }
}

/* -------------------------------------------------------------------------- */

function key_backspaceCampos() {
    if (document.form && document.form.elements.length > 0)
    for (i = 0; i < document.form.elements.length; i++) {
        // if (document.form[i].name=="senha")
            document.form.form[i].value="";  }
}

/* -------------------------------------------------------------------------- */

function CheckAll() {
    if (!ok) {
        for (var i = 0; i < document.form1.elements.length; i++) {
            var x = document.form1.elements[i];
            if (x.name=='UIDL') {
                x.checked = true;
                ok=true;
            }
        }
    } else {
        for (var i = 0 ; i < document.form1.elements.length; i++) {
            var x = document.form1.elements[i];
            if (x.name=='UIDL') {
                x.checked = false;
                ok=false;
            }
        }
    }
}

/* -------------------------------------------------------------------------- */

function TabOnEnter(e) {
    if (document.all) {
        var key = event.keyCode;
        var inp = event.srcElement.name;
        var idx = parseInt(event.srcElement.getAttribute("tabindex"));
        var element = event.srcElement;
    } else {
        var key = e.which;
        var inp = e.target.name;
        var idx = parseInt(e.target.getAttribute("tabindex"));
        var element = e.target;
    }

    if ((""+element.type != "textarea") && (key == 13 /*|| (element.value.length >= element.maxLength && key != 9)*/)) {
        if (document.all)
            event.cancelBubble = true;
        else
            e.stopPropagation();
        var coll = document.forms[0].elements;
        var nextel = 0;
        var nextElement = document.forms[0].elements[coll.length-1]; // Obtem
                                                                        // o
                                                                        // último
                                                                        // elemento
                                                                        // HTML
                                                                        // do
                                                                        // form.

        // Se o campo atual for justamente o último coloca o Foco no primeiro
        // campo.
        if (idx == parseInt(nextElement.getAttribute("tabindex"))) {
            for (i = 0; i < coll.length; i++) {
                if (!coll[i].disabled) {
                    coll[i].focus();
                    return true;
                }
            }
        }

        for (i = 0; i < coll.length; i++) {
            if (coll[i] == null) continue;
            if (idx != "" && parseInt(coll[i].getAttribute("tabindex")) == idx+1) {
                if (coll[i].disabled) {
                    // Pega o próximo elemento que não esteja DESABILITADO
                    idx = idx+1;
                    continue;
                }
                coll[i].focus();
                return true;
            } else {
                if (idx == parseInt(coll[i].getAttribute("tabindex"))) {
                    nextel = i+1;
                    if (coll[nextel]) {
                        if (coll[nextel].disabled) {
                            // Pega o próximo elemento que não esteja
                            // DESABILITADO
                            idx = idx+1;
                            continue;
                        }
                        coll[nextel].focus();
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

/* -------------------------------------------------------------------------- */
// Seta cookies
function setCookie(c_name,value,expiredays)
{
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";path=/aapf/";
}

/* -------------------------------------------------------------------------- */
// Recupera cookies
function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
    c_start=document.cookie.indexOf(c_name + "=")
    if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1) c_end=document.cookie.length
        return unescape(document.cookie.substring(c_start,c_end))
        }
    }
    return ""
}

/* -------------------------------------------------------------------------- */

// Reseta o o cookie para abrir o menu no Acesso Rápido
function iniciaAcessoRapido() {
    setCookie("idSubMenu","4",1);
    setCookie("idSubMenuTrans","1",1);
}

/* -------------------------------------------------------------------------- */

function getMensagemErro()
{
    return mensagemErro;
}

/* -------------------------------------------------------------------------- */
// Redireciona o cliente para URL do banner
// Caso URL = https, mantenho-o na mesma janela;
// Caso URL = http, abro nova janela chamada Portal.
function redirecionamentoInteligente() {
    url = document.getElementById('bannerLinkId').href;
    if (url.indexOf("https")>-1) {
        location.href = url;
    } else {
        window.open( url , 'Portal');
    }
}

/* -------------------------------------------------------------------------- */

// Javascript para impedir duplo clique
var submeteuFormulario = 0;
function controleDuploClique() {
    if (submeteuFormulario=="1") {
        return false;
    }
    submeteuFormulario = "1";
    return true;
}

/* -------------------------------------------------------------------------- */

// Abre janela de ajuda
function janelaAjuda(url)
{
    janela = window.open( url , 'Ajuda', 'height=500,width=600,status=yes,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=yes');
    if (window.focus) {
        janela.focus();
    }
}

/* -------------------------------------------------------------------------- */
// Script que mostra ou esconde um elemento
function mostraEsconde(layer) {
    if (document.getElementById(layer).style.display != "none") {
        document.getElementById(layer).style.display = "none";
    } else {
        document.getElementById(layer).style.display = "";
    }
}

/* -------------------------------------------------------------------------- */
// Script que esconde um elemento
function escondeLayer(layer) {
    document.getElementById(layer).style.display="none";
}

/* -------------------------------------------------------------------------- */
// Script que mostra um elemento
function mostraLayer(layer) {
    document.getElementById(layer).style.display="";
}

/* -------------------------------------------------------------------------- */
// Script que abre popup
var janela;
function popup(url, target, features) {
    newwindow = window.open(url, target, features);
    if (window.focus) {
        newwindow.focus();
    }
    return false;
}

/* -------------------------------------------------------------------------- */
// Formata o campo CEP
function formataCEP(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 3)
        campo.value = vr;
    if ( tam > 3)
        campo.value = vr.substr(0, tam-3) + '-' + vr.substr(tam-3, tam);
}

/* -------------------------------------------------------------------------- */
// Limpa os campos da tela
function limpa() {
    var elements = document.forms.aapf.elements;
    for (i = 0; i < elements.length; i++) {
        if (elements[i].type=='text' || elements[i].type=='text-area'
                || elements[i].type=='select-one' || elements[i].type=='radio'
                || elements[i].type=='checkbox' || elements[i].type=='password'
                || elements[i].type=='textarea') {
            elements[i].value='';
        }
    }
    if (document.tclJava)
    {
        document.tclJava.limpa();
    }
}

/* -------------------------------------------------------------------------- */
// Limpa os campos da tela
function limpaTodosMenos(nome1, nome2, nome3) {
    var elements = document.forms.aapf.elements;
    for (i = 0; i < elements.length; i++) {
        if (elements[i].name != nome1 && elements[i].name != nome2 && elements[i].name != nome3) {
            if (elements[i].type=='text' || elements[i].type=='text-area'
                    || elements[i].type=='select-one' || elements[i].type=='radio'
                    || elements[i].type=='checkbox' || elements[i].type=='password'
                    || elements[i].type=='textarea') {
                elements[i].value='';
            }
        }
    }
    if (document.tclJava)
    {
        document.tclJava.limpa();
    }
}

/* -------------------------------------------------------------------------- */

function limpaEspecifico(text,textarea,selectone,radio,checkbox,password,submit) {

    var elements = document.forms.aapf.elements;

    for (i = 0; i < elements.length; i++) {
        if (text=='true') {
            if (elements[i].type=='text') {
                elements[i].value='';
            }
        }
        if (textarea=='true') {
            if (elements[i].type=='text-area') {
                elements[i].value='';
            }
        }
        if (selectone=='true') {
            if (elements[i].type=='select-one') {
                elements[i].value='';
            }
        }
        if (radio=='true') {
            if (elements[i].type=='radio') {
                elements[i].value='';
            }
        }
        if (checkbox=='true') {
            if (elements[i].type=='checkbox') {
                elements[i].value='';
            }
        }
        if (password=='true') {
            if (elements[i].type=='password') {
                elements[i].value='';
            }
        }
    }
}

/* -------------------------------------------------------------------------- */
// Formata o campo Agencia
function formataAgenciaConta(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;
    if ( tam <= 1)
        campo.value = vr;
    if ( tam > 1)
        campo.value = vr.substr(0, tam-1) + '-' + vr.substr(tam-1, tam);
}

/* -------------------------------------------------------------------------- */
// Formata data no padr?o DDMMAAAA
function formataData(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam > 2 && tam < 5)
        campo.value = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, tam);
    if ( tam >= 5 && tam <= 10)
        campo.value = vr.substr( 0, 2) + '/' + vr.substr( 2, 2) + '/' + vr.substr( 4, 4);

}

/* -------------------------------------------------------------------------- */
// Formata hora no padrao HH:MM
function formataHora(campo,teclapres) {
    var tecla = teclapres.keyCode;
    campo.value = filtraCampo(campo);
    vr = campo.value;
    vr = vr.replace( ".", "");
    vr = vr.replace( ":", "");
    vr = vr.replace( ":", "");
    tam = vr.length + 1;

    if ( tecla != 9 && tecla != 8) {
        if ( tam > 2 && tam < 5)
            campo.value = vr.substr( 0, tam - 2 ) + ':' + vr.substr( tam - 2, tam);
    }
}

/* -------------------------------------------------------------------------- */
// Formata o campo valor
function formataValor(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 2) {
        campo.value = vr ; }
    if ( (tam > 2) && (tam <= 5)) {
        campo.value = vr.substr( 0, tam - 2) + ',' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 6) && (tam <= 8)) {
        campo.value = vr.substr( 0, tam - 5) + '.' + vr.substr( tam - 5, 3) + ',' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 9) && (tam <= 11)) {
        campo.value = vr.substr( 0, tam - 8) + '.' + vr.substr( tam - 8, 3) + '.' + vr.substr( tam - 5, 3) + ',' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 12) && (tam <= 14)) {
        campo.value = vr.substr( 0, tam - 11) + '.' + vr.substr( tam - 11, 3) + '.' + vr.substr( tam - 8, 3) + '.' + vr.substr( tam - 5, 3) + ',' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 15) && (tam <= 18)) {
        campo.value = vr.substr( 0, tam - 14) + '.' + vr.substr( tam - 14, 3) + '.' + vr.substr( tam - 11, 3) + '.' + vr.substr( tam - 8, 3) + '.' + vr.substr( tam - 5, 3) + ',' + vr.substr( tam - 2, tam) ;}

}

/* -------------------------------------------------------------------------- */
// Formata o campo valor
function formataNumerico(campo) {

    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;
}

/* -------------------------------------------------------------------------- */
// limpa todos os caracteres especiais do campo solicitado
function filtraCampo(campo) {
    var s = "";
    var cp = "";
    vr = campo.value;
    tam = vr.length;
    for (i = 0; i < tam ; i++) {
        if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != ",") {
            s = s + vr.substring(i,i + 1);}
    }
    campo.value = s;
    return cp = campo.value
}

/* -------------------------------------------------------------------------- */
// Seta o ajuda do campo no campo <SPAN>
function setaTextoAjuda(txt) {
    if (document.getElementById('textoAjuda')) document.getElementById('textoAjuda').innerHTML = txt + '&nbsp;' ;
}

/* -------------------------------------------------------------------------- */

function getTeclaPressionada(evt)
{
    if (typeof(evt)=='undefined')
        evt = window.event;
    return(evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode));
}

/* -------------------------------------------------------------------------- */
// teclas 63230 a 63240 = safari
function isTeclaEspecial(key)
{
    return key<32||(key>=35&&key<=36)||(key>=37&&key<=40)||key==46||(key>=63230&&key<=63240);
}

/* -------------------------------------------------------------------------- */

function isTeclaRelevante(key)
{
    return (key==8)||(key==46)||(key==88)||(key>=48&&key<=57)||(key>=96&&key<=105);
}

/* -------------------------------------------------------------------------- */

function isCaracterRelevante(key)
{
    return (key==88)||(key==120)||(key>=48&&key<=57);
}

/* -------------------------------------------------------------------------- */

function isCopiaCola(ctrlKey, key)
{
    return ctrlKey && (key==118 || key==86 || key==99 || key==67);
}

/* -------------------------------------------------------------------------- */

function filtraTeclas(evt)
{
    var key = getTeclaPressionada(evt);
    if (isTeclaEspecial(key) || isTeclaRelevante(key) || isCopiaCola(evt.ctrlKey, key))
        return true;
    StopEvent(evt);
    return false;
}

/* -------------------------------------------------------------------------- */

function filtraCaracteres(evt)
{
    var key = getTeclaPressionada(evt);
    if (isTeclaEspecial(key) || isCaracterRelevante(key) || isCopiaCola(evt.ctrlKey, key))
        return true;
    StopEvent(evt);
    return false;
}

/* -------------------------------------------------------------------------- */

function StopEvent(evt)
{
    if (document.all)evt.returnValue=false;
    else if (evt.preventDefault)evt.preventDefault();
}

/* -------------------------------------------------------------------------- */

function formataMascara(format, field)
{
    var result = "";
    var maskIdx = format.length - 1;
    var error = false;
    var valor = field.value;
    var posFinal = false;
    if (field.setSelectionRange)
    {
        if (field.selectionStart==valor.length)
            posFinal = true;
    }
    valor = valor.replace(/[^0123456789Xx]/g,'')
    for (var valIdx = valor.length - 1; valIdx >= 0 && maskIdx >= 0; --maskIdx)
    {
        var chr = valor.charAt(valIdx);
        var chrMask = format.charAt(maskIdx);
        switch (chrMask)
        {
        case '#':
            if (!(/\d/.test(chr)))
                error = true;
            result = chr + result;
            --valIdx;
            break;
        case '@':
            result = chr + result;
            --valIdx;
            break;
        default:
            result = chrMask + result;
        }
    }

    field.value = result;
    field.style.color = error ? 'red' : '';
    if (posFinal)
    {
        field.selectionStart = result.length;
        field.selectionEnd = result.length;
    }
    return result;
}

/* -------------------------------------------------------------------------- */

function saltaCampo(campo,tamanhoMaximo,indice,evt) {
    var vr = campo.value;
    var tam = vr.length;
    var elements = document.forms.aapf.elements;
    if (tam>=tamanhoMaximo && typeof(elements[indice])!='undefined') {
        // elements[indice].focus();
        for (i=0;i<elements.length;i++) {
            if (elements[i].tabIndex==indice+1) {
                elements[i].focus();
            }
        }
    }
}

/* -------------------------------------------------------------------------- */

function trocaBotaoAction(botao)
{
    if ( document.applets['tclAssinador'])
    {
        pos = document.forms.aapf.action.indexOf("?");
        acao = document.forms.aapf.action;
        if (pos != -1)
        {
            acao = acao.substring(0, pos);
        }
        document.forms.aapf.action = acao + "?" + botao + ".x=1";
    }
}

/* -------------------------------------------------------------------------- */

var confirmaAssinador = 0;
var linkJS = "";

function getSenha() {
    if ( document.getElementById('tclAssinadorContent') && document.getElementById('tclAssinadorContent').style.display=='none')
    {
        if (showApplet());
            return false;
    }

    if ( document.applets['tclJava']) {
        var senha = document.applets['tclJava'].getSenha();
        document.forms.aapf.elements['senhaConta'].value = senha;
    }
    else if ( document.applets['tclAssinador'])
    {
        if (confirmaAssinador==1)
        {
            confirmaAssinador = 0;
            if (document.applets['tclAssinador'].ok())
            {
                loadData();
                return true;
            }
            else
            {
                document.applets['tclAssinador'].focus();
                return false;
            }
        }
        else
        {
            return document.applets['tclAssinador'].cancel();
        }
    }
    return true;
}

/* -------------------------------------------------------------------------- */

function trocaBotaoAction(botao)
{
    if ( document.applets['tclAssinador'])
    {
        pos = document.forms.aapf.action.indexOf("?");
        acao = document.forms.aapf.action;
        if (pos != -1)
        {
            acao = acao.substring(0, pos);
        }
        document.forms.aapf.action = acao + "?" + botao + ".x=1";
    }
}

/* -------------------------------------------------------------------------- */
// metodo chamado pela applet na finaliza??o do processo
function appletTerminated(ok)
{
    if (ok)
        loadData();
    if (linkJS=="")
        document.forms.aapf.submit();
    else if (linkJS=="retorna") {
        linkJS = "";
        window.history.back(1);
    }
    else {
        var linkJSTemp = linkJS;
        linkJS = "";
        window.navigate(linkJSTemp);
    }
}

/* -------------------------------------------------------------------------- */

function formataMesAno(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam > 2 && tam < 5)
        campo.value = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, tam);
    if ( tam >= 5 && tam <= 10)
        campo.value = vr.substr( 0, 2) + '/' + vr.substr( 2, 4);
}

/* -------------------------------------------------------------------------- */

function formataCGC(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 2) {
        campo.value = vr ; }
    if ( (tam > 2) && (tam <= 6)) {
        campo.value = vr.substr( 0, tam - 2) + '-' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 7) && (tam <= 9)) {
        campo.value = vr.substr( 0, tam - 6) + '/' + vr.substr( tam - 6, 4) + '-' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 10) && (tam <= 12)) {
        campo.value = vr.substr( 0, tam - 9) + '.' + vr.substr( tam - 9, 3) + '/' + vr.substr( tam - 6, 4) + '-' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 13) && (tam <= 14)) {
        campo.value = vr.substr( 0, tam - 12) + '.' + vr.substr( tam - 12, 3) + '.' + vr.substr( tam - 9, 3) + '/' + vr.substr( tam - 6, 4) + '-' + vr.substr( tam - 2, tam) ; }
    if ( (tam >= 15) && (tam <= 17)) {
        campo.value = vr.substr( 0, tam - 14) + '.' + vr.substr( tam - 14, 3) + '.' + vr.substr( tam - 11, 3) + '.' + vr.substr( tam - 8, 3) + '.' + vr.substr( tam - 5, 3) + '-' + vr.substr( tam - 2, tam) ;}
}

/* -------------------------------------------------------------------------- */

function validarCNPJ() {
    CNPJ = document.validacao.CNPJID.value;
    erro = new String;
    if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
    if (erro.length==0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
    }
    // substituir os caracteres que não são números
    if (document.layers && parseInt(navigator.appVersion)==4) {
            x = CNPJ.substring(0,2);
            x += CNPJ. substring (3,6);
            x += CNPJ. substring (7,10);
            x += CNPJ. substring (11,15);
            x += CNPJ. substring (16,18);
            CNPJ = x;
    } else {
            CNPJ = CNPJ. replace (".","");
            CNPJ = CNPJ. replace (".","");
            CNPJ = CNPJ. replace ("-","");
            CNPJ = CNPJ. replace ("/","");
    }
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++) {
            a[i] = CNPJ.charAt(i);
            b += a[i] * c[i+1];
    }
    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
    b = 0;
    for (y=0; y<13; y++) {
            b += (a[y] * c[y]);
    }
    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
            erro +="Dígito verificador com problema!";
    }
    if (erro.length > 0) {
            alert(erro);
            return false;
    } else {
            alert("CNPJ valido!");
    }
    return true;
}

/* -------------------------------------------------------------------------- */

function formataCPF(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length ;
    if ( tam <= 2) {
        campo.value = vr ;}
    if ( tam > 2 && tam <= 5) {
        campo.value = vr.substr( 0, tam - 2) + '-' + vr.substr( tam - 2, tam);}
    if ( tam >= 6 && tam <= 8) {
        campo.value = vr.substr( 0, tam - 5) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr( tam - 2, tam);}
    if ( tam >= 9 && tam <= 11) {
        campo.value = vr.substr( 0, tam - 8) + '.' + vr.substr( tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr( tam - 2, tam);}
}

/* -------------------------------------------------------------------------- */

function validarCPF(input) {
    var cpf = input.value;
    var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;

    if (!filtro.test(cpf)) {
        window.alert("CPF inválido. Tente novamente.");
        input.value = "";
        input.focus();
        return false;
    }

    cpf = remove(cpf, ".");
    cpf = remove(cpf, "-");

    if (cpf.length != 11 || cpf=="00000000000" || cpf=="11111111111" ||
        cpf=="22222222222" || cpf=="33333333333" || cpf=="44444444444" ||
        cpf=="55555555555" || cpf=="66666666666" || cpf=="77777777777" ||
        cpf=="88888888888" || cpf=="99999999999") {
        window.alert("CPF inválido. Tente novamente.");
        input.value = "";
        input.focus();
        return false;
    }

    soma = 0;
    for(i = 0; i < 9; i++)
        soma += parseInt(cpf.charAt(i)) * (10 - i);

    resto = 11 - (soma % 11);
    if (resto==10 || resto==11)
        resto = 0;

    if (resto != parseInt(cpf.charAt(9))) {
        window.alert("CPF inválido. Tente novamente.");
        input.value = "";
        input.focus();
        return false;
    }

    soma = 0;
    for(i = 0; i < 10; i ++)
        soma += parseInt(cpf.charAt(i)) * (11 - i);

    resto = 11 - (soma % 11);
    if (resto==10 || resto==11)
        resto = 0;

    if (resto != parseInt(cpf.charAt(10))) {
        window.alert("CPF inválido. Tente novamente.");
        input.value = "";
        input.focus();
        return false;
    }
    return true;
}

/* -------------------------------------------------------------------------- */

function remove(str, sub) {
    i = str.indexOf(sub);
    r = "";
    if (i==-1) return str;
    r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
    return r;
}

/* -------------------------------------------------------------------------- */

function validaCPF(input) {
var s = input.value;
var c = s.substr(0,9);
var dv = s.substr(9,2);
var d1 = 0;
for (var i=0; i<9; i++) {
d1 += c.charAt(i)*(10-i);
}
if (d1==0) return false;
d1 = 11 - (d1 % 11);
if (d1 > 9) d1 = 0;
if (dv.charAt(0) != d1) {
return false;
}
d1 *= 2;
for (var i = 0; i < 9; i++) {
d1 += c.charAt(i)*(11-i);
}
d1 = 11 - (d1 % 11);
if (d1 > 9) d1 = 0;
if (dv.charAt(1) != d1) {
return false;
}
    return true;
}

/* -------------------------------------------------------------------------- */

function formataPercentual(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 3) {
        campo.value = vr ; }
    if ( (tam > 3) && (tam <= 6)) {
        campo.value = vr.substr( 0, tam - 3) + ',' + vr.substr( tam - 3, tam) ; }
}

/* -------------------------------------------------------------------------- */

function formataTelefone(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 4)
        campo.value = vr;
    if ( tam > 4)
        campo.value = vr.substr(0, tam-4) + '-' + vr.substr(tam-4, tam);
}

/* -------------------------------------------------------------------------- */

function contacampo(campo, tamtxt) {
    document.forms.aapf[tamtxt].value =  1540-document.forms.aapf[campo].value.length;
}

/* -------------------------------------------------------------------------- */

function limita(campo) {
    var tamanho = document.forms.aapf[campo].value.length;
    var tex=document.forms.aapf[campo].value;
    if (tamanho>=1539) {
        document.forms.aapf[campo].value=tex.substring(0,1539);
    }
    return true;
}

/* -------------------------------------------------------------------------- */

function mudaFoco(campofoco)
{
    focaCampo(campofoco);
}

/* -------------------------------------------------------------------------- */

function focaCampo(campofoco) {
    if (campofoco=='')
        campofoco = 'botaoConfirma.x';
    var num = parseInt(campofoco);
    if ( num || num==0)
    {
        if ( document.forms.aapf[num])
        {
            try
            {
                document.forms.aapf[num].focus();
            } catch (err) {}
        }
    }
    else
    {
        if ( (campofoco=="senhaConta" || campofoco=="senhaAtual") && document.applets["tclJava"]) {
            try
            {
                document.applets["tclJava"].setFocus();
            } catch (err) {}

        } else if ( document.forms.aapf[campofoco])
        {
            var campo = document.forms.aapf[campofoco];
            if (campo.length)
            {
                for (i = 0; i < campo.length; i++) {
                    if (campo[i].type=='submit') {
                        try
                        {
                            campo[i].focus();
                        } catch (err) {}
                        break;
                    }
                }
            }
            else
            {
                try
                {
                    campo.focus();
                } catch (err) {}
            }
        }
    }
}

/* -------------------------------------------------------------------------- */

function formataCartaoCredito(campo, teclapres) {
    var tammax = 16;
    var tecla = teclapres.keyCode;
    vr = document.forms.aapf[campo].value;

    if ( tecla==8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)) {
        vr = vr.replace( "/", "");
        vr = vr.replace( "/", "");
        vr = vr.replace( ",", "");
        vr = vr.replace( ".", "");
        vr = vr.replace( ".", "");
        vr = vr.replace( ".", "");
        vr = vr.replace( ".", "");
        vr = vr.replace( "-", "");
        vr = vr.replace( "-", "");
        vr = vr.replace( "-", "");
        vr = vr.replace( "-", "");
        vr = vr.replace( "-", "");
        tam = vr.length;

        if (tam < tammax && tecla != 8)
        {tam = vr.length + 1 ; }

        if (tecla==8) {tam = tam - 1 ; }

        if ( tam < 5)
        { document.forms.aapf[campo].value = vr ; }
        if ( ( tam >  4) && ( tam < 9))
        { document.forms.aapf[campo].value = vr.substr( 0, 4) + '.' + vr.substr( 4, tam-4) ; }
        if ( ( tam >  8) && ( tam < 13))
        { document.forms.aapf[campo].value = vr.substr( 0, 4) + '.' + vr.substr( 4, 4) + '.' + vr.substr( 8, tam-4) ; }
        if ( tam > 12)
        { document.forms.aapf[campo].value = vr.substr( 0, 4) + '.' + vr.substr( 4, 4) + '.' + vr.substr( 8, 4) + '.' + vr.substr( 12, tam-4); }
    }
}

/* -------------------------------------------------------------------------- */

var http_request = null;
function getConexaoHttp()
{
    if (http_request==null)
    {
        if (window.XMLHttpRequest)
        { // Mozilla, Safari, ...
            http_request = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        { // IE
            try
            {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e)
            {
                try
                {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
    }
    return http_request;

}

/* -------------------------------------------------------------------------- */

function mostraActive(caminhoApplet, versaoApplet, contraste, numCod, local, idTeclado, idDiv, legenda1, legenda2)
{
    var oDivTcl = document.getElementById(idDiv);
    var codigo = '<object alt="Senha do auto-atendimento" tabindex="70" codebase="' + caminhoApplet + '/teclado/BBTecladoV' + versaoApplet + '.cab#version=1,0,0,3" CLASSID="CLSID:6F03F00A-71B3-4B59-A934-25686DC63B42" name="' + idTeclado + '" id="' + idTeclado + '" width="316" height="80" NOEXTERNALDATA="true"> ';
    codigo += '<param name="id" value="' + idTeclado + '"> ';
    codigo += '<param name="local" value="cartao"> ';
    codigo += '<param name="campoAnterior" value=""> ';
    codigo += '<param name="campoPosterior" value="98"> ';
    codigo += '<param name="colorLabel" value="#000084"> ';
    codigo += '<param name="colorField" value="#FFFFFA"> ';
    codigo += '<param name="colorBorder" value="#BBBBBB"> ';
    codigo += '<param name="colorBackground" value="#FFFFFF"> ';
    if (local=='cartao')
    {
        codigo += '<param name="tipoLegenda" value="cartao"> ';
    }
    else if (local=='definido')
    {
        codigo += '<param name="tipoLegenda" value="definido"> ';
        codigo += '<param name="legenda1" value="' + legenda1 + '"> ';
        codigo += '<param name="legenda2" value="' + legenda2 + '"> ';
    }
    codigo += '<param name="colorEmb" value="azul"> ';
    codigo += '<param name="valorContr" value="' + contraste + '"> ';
    codigo += '<param name="numCod" value="' + numCod + '"> ';
    codigo += '</object>';
    oDivTcl.innerHTML = codigo;
    return true;
}

/* -------------------------------------------------------------------------- */

function mostraErro()
{
    var oDivTcl = document.getElementById('tclTecladoContent');
    oDivTcl.innerHTML = '<br>Ocorreu um erro ao carregar o Teclado Virtual.<br>Pressione F5 ou <a href="/aapf/login.jsp?forcaApplet=sim" >acesse o Teclado<br>Virtual em Java</a><br><br>';
    return true;
}

/* -------------------------------------------------------------------------- */

function setAppletArea(oDivTcl)
{
        try {
            oDivTcl.style.width = 316;
            oDivTcl.style.height = 80;
            oDivTcl.style.backgroundColor = "#f7f7f7";
            oDivTcl.innerHTML =  getMensagemErro();
            oDivTcl.style.display = "block";
        } catch (e2) {}
}

/* -------------------------------------------------------------------------- */

function  montaObjetoApplet(caminhoApplet, versaoApplet, contraste, numCod, local, idTeclado, idDiv, legenda1, legenda2, showCamposLogin) {
    var oDivTcl = document.getElementById(idDiv);
    var codigo = '<applet alt="Senha do auto-atendimento" tabindex="70" code="br/com/bb/aapf/bbteclado/CampoTeclado.class" cabbase="/aapf/ncresp/teclado/BBTeclado' + versaoApplet + '.cab" archive="/aapf/ncresp/teclado/BBTeclado' + versaoApplet + '.jar" codebase="/aapf/ncresp/teclado/" name="' + idTeclado + '" id="' + idTeclado + '" width="316" height="80" namespace="global" mayscript> ';
    codigo += '<param name="id" value="' + idTeclado + '"> ';
    codigo += '<param name="local" value="' + local + '"> ';
    codigo += '<param name="campoAnterior" value=""> ';
    codigo += '<param name="campoPosterior" value="98"> ';
    codigo += '<param name="colorLabel" value="0x000084"> ';
    codigo += '<param name="colorField" value="0xFFFFFA"> ';
    codigo += '<param name="colorBorder" value="0xBBBBBB"> ';
    codigo += '<param name="colorBackground" value="#FFFFFF"> ';
    if (local=="cartao")
    {
        codigo += '<param name="tipoLegenda" value="cartao"> ';
    }
    else if (local=="definido")
    {
        codigo += '<param name="tipoLegenda" value="definido"> ';
        codigo += '<param name="legenda1" value="' + legenda1 + '"> ';
        codigo += '<param name="legenda2" value="' + legenda2 + '"> ';
    }
    if (showCamposLogin=="true")
    {
        codigo += '<param name="showCamposLogin" value="true"> ';
    }
    codigo += '<param name="colorEmb" value="azul"> ';
    codigo += '<param name="valorContr" value="' + contraste + '"> ';
    codigo += '<param name="numCod" value="' + numCod + '"> ';
    codigo += '</applet>';
    mensagemErro = codigo;
    try {
        if (window.navigator.javaEnabled()&&oDivTcl) {
            var oAppletTcl = document.createElement("applet");

            // oAppletTcl.code = "br.com.bb.aapf.bbteclado.CampoTeclado.class";
            oAppletTcl.code = "br/com/bb/aapf/bbteclado/CampoTeclado.class";

            oAppletTcl.codeBase = caminhoApplet + "/teclado/";
            oAppletTcl.cabBase = caminhoApplet + "/teclado/BBTeclado" + versaoApplet + ".cab";
            oAppletTcl.archive = caminhoApplet + "/teclado/BBTeclado" + versaoApplet + ".jar";
            oAppletTcl.name = idTeclado;
            oAppletTcl.tabIndex = "70";
            oAppletTcl.title = "Senha do auto-atendimento";
            oAppletTcl.alt = "Senha do auto-atendimento";
            oAppletTcl.left = 0;
            oAppletTcl.top = 0;
            oAppletTcl.width = 316;
            oAppletTcl.height = 80;
            oAppletTcl.id = idTeclado;
            oAppletTcl.appendChild(makeParam("MAYSCRIPT", "true"));
            oAppletTcl.appendChild(makeParam("id", idTeclado));
            oAppletTcl.appendChild(makeParam("local", local));
            oAppletTcl.appendChild(makeParam("campoAnterior",""));
            oAppletTcl.appendChild(makeParam("campoPosterior","98"));
            oAppletTcl.appendChild(makeParam("colorLabel","0x000084"));
            oAppletTcl.appendChild(makeParam("colorField","0xFFFFFA"));
            oAppletTcl.appendChild(makeParam("colorBorder","0xBBBBBB"));
            oAppletTcl.appendChild(makeParam("colorBackground","#FFFFFF"));
            if (local=="cartao")
            {
                oAppletTcl.appendChild(makeParam("tipoLegenda","cartao"));
            }
            else if (local=="definido")
            {
                oAppletTcl.appendChild(makeParam("tipoLegenda","definido"));
                oAppletTcl.appendChild(makeParam("legenda1",legenda1));
                oAppletTcl.appendChild(makeParam("legenda2",legenda2));
            }
            if (showCamposLogin=="true")
            {
                oAppletTcl.appendChild(makeParam("showCamposLogin","true"));
            }
            oAppletTcl.appendChild(makeParam("colorEmb","azul"));
            oAppletTcl.appendChild(makeParam("valorContr",contraste));
            oAppletTcl.appendChild(makeParam("numCod",numCod));

            oDivTcl.appendChild(oAppletTcl);

        } else {
            window.defaultStatus = "Erro: Java nao suportado ou nao habilitado!";
            window.status = "Erro: Java nao suportado ou nao habilitado!";
            setAppletArea(oDivTcl);
        }
    } catch (e) {
        window.defaultStatus = "Erro ao criar Applet:" + e.description;
        window.status = "Erro ao criar Applet:" + e.description;
        setAppletArea(oDivTcl);
    }

    return true;
}

/* -------------------------------------------------------------------------- */

function makeParam(name, value)
{
    var p = document.createElement("param");
    p.name = name;
    p.value = value;
    return p;
}

/* -------------------------------------------------------------------------- */

function mostraApplet(caminhoApplet, versaoApplet, contraste, numCod, local, idTeclado, idDiv, legenda1, legenda2, showCamposLogin)
{
    var codigo = '<applet alt="Senha do auto-atendimento" tabindex="70" code="br/com/bb/aapf/bbteclado/CampoTeclado.class" cabbase="/aapf/ncresp/teclado/BBTeclado' + versaoApplet + '.cab" archive="/aapf/ncresp/teclado/BBTeclado' + versaoApplet + '.jar" codebase="/aapf/ncresp/teclado/" name="' + idTeclado + '" id="' + idTeclado + '" width="316" height="80" namespace="global" mayscript> ';
    codigo += '<param name="id" value="' + idTeclado + '"> ';
    codigo += '<param name="local" value="' + local + '"> ';
    codigo += '<param name="campoAnterior" value=""> ';
    codigo += '<param name="campoPosterior" value="98"> ';
    codigo += '<param name="colorLabel" value="0x000084"> ';
    codigo += '<param name="colorField" value="0xFFFFFA"> ';
    codigo += '<param name="colorBorder" value="0xBBBBBB"> ';
    codigo += '<param name="colorBackground" value="#FFFFFF"> ';
    if (local=="cartao")
    {
        codigo += '<param name="tipoLegenda" value="cartao"> ';
    }
    else if (local=="definido")
    {
        codigo += '<param name="tipoLegenda" value="definido"> ';
        codigo += '<param name="legenda1" value="' + legenda1 + '"> ';
        codigo += '<param name="legenda2" value="' + legenda2 + '"> ';
    }
    if (showCamposLogin=="true")
    {
        codigo += '<param name="showCamposLogin" value="true"> ';
    }
    codigo += '<param name="colorEmb" value="azul"> ';
    codigo += '<param name="valorContr" value="' + contraste + '"> ';
    codigo += '<param name="numCod" value="' + numCod + '"> ';
    codigo += '</applet>';
    oDivTcl.innerHTML = codigo;
    return true;
}

/* -------------------------------------------------------------------------- */

function mostraAssinador(width, caminhoApplet, nomeBotaoSubmit, idCartao, parametroD)
{
    var oDivTcl = document.getElementById("tclTecladoContent");
    var codigo = '<applet name="tclAssinador" id="tclAssinador" code="br.com.bb.cdg.assinador.applet.SignApplet" codebase="' + caminhoApplet + '/certificacao/" archive="' + caminhoApplet + '/certificacao/slogin.jar" width="' + width + '" height="80" mayscript="mayscript" alt="Assinador do auto-atendimento"> ';
    codigo += '<param name="botao" value="' + nomeBotaoSubmit + '"> ';
    if (idCartao != "null")
        codigo += '<param name="c" value="' + idCartao + '"> ';
    codigo += parametroD + ' ';
    codigo += 'Seu assinador do auto-atendimento não foi habilitado.<br> ';
    codigo += '<a href="/aapf/ajuda/faqCertificacao.jsp">Clique aqui para saber mais...</a><br><br> ';
    codigo += '</applet>';
    oDivTcl.innerHTML = codigo;
    return true;
}

/* -------------------------------------------------------------------------- */

function getTeclaPressionada(evt)
{
    if (typeof(evt)=='undefined') {
        evt = window.event;
    }
    return (evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode));
}

function isTeclaEspecial(key)
{
    // teclas 63230 a 63240 = safari
    return key<32 || (key>=35 && key<=36) || (key>=37 && key<=40) || key==46 || (key>=63230 && key<=63240);
}

function isTeclaRelevante(key)
{
    return (key==8) || (key==46) || (key==88) || (key>=48 && key<=57) || (key>=96 && key<=105);
}

function isCaracterRelevante(key)
{
    return (key==88) || (key==120) || (key>=48 && key<=57);
}

function isCopiaCola(ctrlKey, key)
{
    return ctrlKey && (key==118 || key==86 || key==99 || key==67);
}

function StopEvent(evt)
{
    if (document.all) {
        evt.returnValue=false;
    } else if (evt.preventDefault) {
        evt.preventDefault();
    }
}

function setaTextoAjuda(txt) {
    if (document.getElementById('textoAjuda')) {
        document.getElementById('textoAjuda').innerHTML = txt + '&nbsp;';
    }
}

/* -------------------------------------------------------------------------- */

function filtraTeclas(evt)
{
    var key = getTeclaPressionada(evt);
    if (isTeclaEspecial(key) || isTeclaRelevante(key) || isCopiaCola(evt.ctrlKey, key))
        return true;
    StopEvent(evt);
    return false;
}

/* -------------------------------------------------------------------------- */

function filtraCaracteres(evt)
{
    var key = getTeclaPressionada(evt);
    if (isTeclaEspecial(key) || isCaracterRelevante(key) || isCopiaCola(evt.ctrlKey, key))
        return true;
    StopEvent(evt);
    return false;
}

/* -------------------------------------------------------------------------- */

function formataMascara(format, field)
{
    var result = "";
    var maskIdx = format.length - 1;
    var error = false;
    var valor = field.value;
    var posFinal = false;
    if (field.setSelectionRange) {
        if (field.selectionStart == valor.length)
            posFinal = true;
}
    valor = valor.replace(/[^0123456789Xx]/g,'');
    for (var valIdx = valor.length - 1; valIdx >= 0 && maskIdx >= 0; --maskIdx) {
        var chr = valor.charAt(valIdx);
        var chrMask = format.charAt(maskIdx);
        switch (chrMask) {
        case '#':
            if (!(/\d/.test(chr)))
                error = true;
            result = chr + result;
            --valIdx;
            break;
        case '@':
            result = chr + result;
            --valIdx;
            break;
        default:
            result = chrMask + result;
        }
    }

    field.value = result;
    field.style.color = error ? 'red' : '';
    if (posFinal) {
        field.selectionStart = result.length;
        field.selectionEnd = result.length;
    }
    return result;
}

/* -------------------------------------------------------------------------- */

function saltaCampo(campo, tamanhoMaximo, indice, evt) {
    var vr = campo.value;
    var tam = vr.length;
    var elements = document.forms[0].elements;
    if (tam>=tamanhoMaximo && typeof(elements[indice])!='undefined') {
        // elements[indice].focus();
        for (i=0; i<elements.length; i++) {
            if (elements[i].tabIndex==indice+1) {
                elements[i].focus();
            }
        }
    }
}

/* -------------------------------------------------------------------------- */

function telaAnterior() {
    window.history.back();
}

/* -------------------------------------------------------------------------- */

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) break;
    }
}

/* -------------------------------------------------------------------------- */

function adicionarDias(data, dias){
    return new Date(data.getTime() + (dias * 24 * 60 * 60 * 1000));
}

/* -------------------------------------------------------------------------- */

function proximoDiaUtil(data) {
    var dia = data.split("/")[0];
    var mes = parseInt(data.split("/")[1], 10)-1;
    var ano = data.split("/")[2];
    var data = new Date(ano, mes, dia);
    var dias = 1;
    var dataFinal = new Date(data.getTime() + (dias * 24 * 60 * 60 * 1000))
    
    if (dataFinal.getDay() == 0 || dataFinal.getDay() == 6) 
       dataFinal = proximoDiaUtil(formatDate(dataFinal, "dd/MM/yyyy"));
    return dataFinal;
}

/* -------------------------------------------------------------------------- */

function selectCode(a) {
    // Get ID of code block
    var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
    if (window.getSelection) { // Not IE
        var s = window.getSelection();
        if (s.setBaseAndExtent) { // Safari
            s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
        } else { // Firefox and Opera
            var r = document.createRange();
            r.selectNodeContents(e);
            s.removeAllRanges();
            s.addRange(r);
        }
    } else if (document.getSelection) { // Some older browsers
        var s = document.getSelection();
        var r = document.createRange();
        r.selectNodeContents(e);
        s.removeAllRanges();
        s.addRange(r);
    } else if (document.selection) { // IE
        var r = document.body.createTextRange();
        r.moveToElementText(e);
        r.select();
    }
}

/* -------------------------------------------------------------------------- */

function Trim(str) {
    return str.replace(/^\s+|\s+$/g,"");
}

/* -------------------------------------------------------------------------- */

function SelectAll(element) {
    if (typeof(element) == 'string') 
        var element = document.getElementById(element);
    if (!element.disabled) {
        element.focus();
        element.select();
    }
}

/* -------------------------------------------------------------------------- */

function addOption(selectbox, value, text) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function getOption(selectbox, value) {
    var i;
    for (i=selectbox.options.length-1;i>=0;i--) {
        if (selectbox.options[i].value == value)
            return selectbox.options[i];
    }
    return null;
}

function getNumberOptions(selectbox){
    return (selectbox == null || selectbox.length <= 0 ? 0 : selectbox.length);
}

function getSelectedOption(selectbox) {
    return selectbox.options[selectbox.selectedIndex];
}

function removeAllOptions(selectbox) {
    selectbox.length = 0;
    return null;
}

function removeSelectedOption(selectbox) {
    var i;
    var optn = selectbox.options[selectbox.selectedIndex];
    selectbox.remove(selectbox.selectedIndex);
    return optn;
}

function removeOption(selectbox, value) {
    var i;
    for (i=selectbox.options.length-1;i>=0;i--) {
        if (selectbox.options[i].value == value)
            selectbox.remove(i);
    }
}

/* -------------------------------------------------------------------------- */

function NewWindow(pageFile, titulo, width, height, scrollBars, resizable) {
    resizable    = (resizable == null ? false : resizable);
    scrollBars   = (scrollBars == null ? false : scrollBars);
    LeftPosition = (screen.width) ? (screen.width-width)/2 : 0;
    TopPosition  = (screen.height) ? (screen.height-height)/2 : 0;
    settings     = 'height='+ height +',width='+ width +',top='+ TopPosition +',left='+ LeftPosition +',scrollbars='+ scrollBars +(resizable ? ',resizable' : '');
    return window.open(pageFile, titulo, settings)
}

/* -------------------------------------------------------------------------- */

function setVisibleOrHidden(element, visible) {
    if (element != null && typeof(element) != 'undefined') {
        if (typeof(element) == "string")
            document.getElementById(element).style.visibility = (visible == true || visible == "true" ? "visible" : "hidden");
        else if (typeof(element) == "object")
            element.style.visibility = (visible == true || visible == "true" ? "visible" : "hidden");       
        else
            alert("O tipo de parâmetro informado é inválido.");       
    }
}

/* -------------------------------------------------------------------------- */
