var _bSaving = false;
function Init() {
    window.focus();
    window.attachEvent("onbeforeunload", Close);
}
// Faz um postback e limpa o eventtarget e eventargument
function __doPostBack2(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
        theForm.__EVENTTARGET.value = '';
        theForm.__EVENTARGUMENT.value = '';
    }
}
// Exporta um relatório para pdf, doc, xls, etc (conforme nIdTipo)
// sUrl = url que é utilizada para visualizar o relatório. Ex: .../ReportViewer2.aspx?q=...
// nIdTipo = formato do arquivo para exportar. Possíveis formatos: RichText (2), Word (3), Excel (4), PDF (5),
//           HTML 3.2 (6), HTML 4.0 (7)
function Exportar(sUrl, nIdTipo) {
    var objEventTarget = document.createElement('input');
    objEventTarget.type = 'hidden';
    objEventTarget.id = '__EVENTTARGET';
    objEventTarget.name = '__EVENTTARGET';
    objEventTarget.value = 'exportar';

    var objEventArgument = document.createElement('input');
    objEventArgument.type = 'hidden';
    objEventArgument.id = '__EVENTARGUMENT';
    objEventArgument.name = '__EVENTARGUMENT';
    objEventArgument.value = nIdTipo;

    var objForm = document.createElement('form');
    objForm.appendChild(objEventTarget);
    objForm.appendChild(objEventArgument);
    objForm.action = sUrl;
    objForm.target = '_blank';
    objForm.id = 'frmPTAExportar';
    objForm.name = 'frmPTAExportar';
    objForm.method = 'post';
    document.appendChild(objForm);
    objForm.submit();
}

function Reset() {
    _bSaving = false;
}

function Close(bNovoMetodo) {
    if (!_bSaving && carregarXml(false, true, bNovoMetodo) != 3) {
        if (SimNao("Aviso", "Para salvar as alterações, clique em Cancelar e, em seguida, clique em Salvar ou em Salvar e Fechar.\n\nPara fechar este registro sem salvar as alterações, clique em OK.")) {
            event.returnValue = true;
        } else {
            event.returnValue = false;
        }
    }
}

function detachCloseAlert() {
    window.detachEvent("onbeforeunload", Close);
}


/*
SE O ULTIMO PARÂMETRO É INFORMADO A FORMA COMO É MONTADA O ARQUIVO XML QUE VAI SER 
ENVIADO PAR AO SERVIDOR É A FORMA NOVA QUE É USADA NO RAIZ DO FRAMEWORK/CORE
SE Ñ É INFORMADO OU É FALSE É USADO A FORMA ANTIGA (VERSÃO 6.20) ISSO É NECESSÁRIOA
PORQUE FOI ADICIONADO ALGUMAS TELAS GERADAS PELO ATRIBUTO DINAMICO DA RAIZ PARA A VERSÃO
6.20 PARA AS ENQUETES
*/
// 1 - success
// 2 - failed (validation)
// 3 - failed (no xml)
function carregarXml(bValidate, bClose, novaForma) {
    if (novaForma) {
        return carregarXmlNovoFormato(bValidate, bClose);
    }
    else {
        return carregarXmlVelhoFormado(bValidate, bClose);
    }
}

function carregarXmlNovoFormato(bValidate, bClose) {
    var sXML = ObterXML();
    if (sXML.length > 0) {
        document.aspnetForm.aspnetFormSubmitXml.value = sXML;
        return 1;
    }

    return 3;
}

// Retorna uma string com os campos do form no formato XML
function ObterXML() {
    var i, o;
    var sXml = "";
    var bInsert = document.aspnetForm.bInsert.value == '1';
    for (i = 0; i < document.aspnetForm.elements.length; i++) {
        o = document.aspnetForm.elements[i];
        var sNomeObj = o.name;
        //se o inicio do nome do controle nao for _c e tiver o $ e porque esta gerando errado
        if (sNomeObj.indexOf("$") > -1) {
            aNomeObj = sNomeObj.split("$");
            if (o.type == "checkbox") {
                if (aNomeObj.length > 2) {
                    sNomeObj = aNomeObj[aNomeObj.length - 2] + "$" + aNomeObj[aNomeObj.length - 1];
                }
                else {
                    if (aNomeObj.length == 2) {
                        sNomeObj = aNomeObj[0];
                    }
                }
            }
            else {
                sNomeObj = aNomeObj[aNomeObj.length - 1];
            }
        }

        if (sNomeObj.substr(0, 2) == "_c") {
            if (o.type == "text" || o.type == "textarea") {
                o.value = Trim(o.value);
            }

            if (!o.disabled) {
                sXml += buildElemNovo(o, bInsert);
            }
        }
    }

    if (sXml.length > 0) {
        var e = document.aspnetForm.aspnetFormRootElem.value;
        sXml = "<" + e + "s>" + "<" + e + ">" + sXml + "</" + e + ">" + "</" + e + "s>";
    }

    return sXml;
}


function buildElemNovo(o, bInsert) {
    var s = retornaValor(o);
    var sRetorno = "";
    if ((bInsert && s.length == 0) || (s.length == 0 && (o.type != "text" && o.type != "textarea" && o.getAttribute("tipointerface") != "pesquisa" && o.type != "checkbox") || o.getAttribute("format") == "time") && (o.type != "select-one")) {
        return "";
    }
    else {
        var regexp = /_x_/g;
        var sNomeObj = o.name;
        var sPrefixo = "";
        if (sNomeObj.indexOf("$") > -1) {
            aNomeObj = sNomeObj.split("$");

            if (o.type == "checkbox") {
                if (aNomeObj.length > 2) {
                    sNomeObj = aNomeObj[aNomeObj.length - 2] + "$" + aNomeObj[aNomeObj.length - 1];
                }
                else {
                    if (aNomeObj.length == 2) {
                        sNomeObj = aNomeObj[0];
                    }
                }
            }
            else {
                sNomeObj = aNomeObj[aNomeObj.length - 1];
            }

            for (var x = 0; x < aNomeObj.length - 1; x++) {
                sPrefixo += aNomeObj[x] + "_";
            }
        }

        var e = sNomeObj.replace(regexp, ".");

        e = e.replace('_c', '');
        var a = "";
        var t = "";
        if (o.getAttribute("field") == "key" || o.getAttribute("field") == "reftable") {
            if (o.getAttribute("field") == "key") {
                t = " field='key'";
            }
            else {
                if (s == "ref") {
                    t = " refTable='" + o.getAttribute("reftable") + "'";
                } else {
                    t = " field='key'";
                }
            }
        }

        if (o.type == "checkbox") {
            a = " list='true'";
            e = e.substring(0, e.indexOf('$'));
        }

        if (o.getAttribute("list") == "true") {
            a = " list='true'";
        }

        if (o.getAttribute("tb")) {
            e = o.getAttribute("tb") + '.' + e;
        }

        a += " type='" + o.getAttribute("tipo") + "'";

        if (document.getElementById(sPrefixo + "tdLbl" + sNomeObj) != null) {
            a += " description='" + document.getElementById(sPrefixo + "tdLbl" + sNomeObj).innerText + "'";
        }

        if (o.type == "select-multiple") {
            var arr = s.split('*');
            for (i = 0; i < arr.length; i++) {
                if (arr[i].length > 0) {
                    sRetorno += "<" + e.toLowerCase() + a + t + ">" + UnicodeToUTF8(arr[i]) + "</" + e.toLowerCase() + ">";
                }
            }
        }
        else {
            sRetorno = "<" + e.toLowerCase() + a + t + ">" + UnicodeToUTF8(s) + "</" + e.toLowerCase() + ">";
        }
        return sRetorno;
    }
}


/* OLD tive que fazer adaptações pq agora tem questões novas na parte de enquete*/
// 1 - success
// 2 - failed (validation)
// 3 - failed (no xml) 
function carregarXmlVelhoFormado(bValidate, bClose) {
    var i, ii, o;
    var iLen = document.aspnetForm.elements.length;
    var sXml = "";
    var bInsert = document.aspnetForm.bInsert.value == '1';

    for (i = 0; i < iLen; i++) {
        o = document.aspnetForm.elements[i];
        if (o.name.substr(0, 2) == "_c") {
            if (o.type == "text" || o.type == "textarea") {
                o.value = Trim(o.value);
            }
            if (!o.disabled) {
                sXml += buildElemVelho(o, bInsert);
            }
        }
    }
    if (sXml.length > 0) {
        var e = document.aspnetForm.aspnetFormRootElem.value;
        sXml = "<" + e + "s>" + "<" + e + ">" + sXml + "</" + e + ">" + "</" + e + "s>";
        document.aspnetForm.aspnetFormSubmitXml.value = sXml;
        return 1;
    }
    else {
        return 3;
    }
}

function buildElemVelho(o, bInsert) {
    var s = retornaValor(o);
    var sRetorno = "";
    if ((bInsert && s.length == 0) || (s.length == 0 && (o.type != "text" && o.type != "textarea" && o.getAttribute("tipointerface") != "pesquisa" && o.type != "checkbox") || o.getAttribute("format") == "time") && (o.type != "select-one")) {
        return "";
    }
    else {
        var regexp = /_x_/g;
        var e = o.name.replace(regexp, ".");
        e = e.replace('_c', '');
        var a = "";
        var t = "";
        if (o.getAttribute("field") == "key" || o.getAttribute("field") == "reftable") {
            if (o.getAttribute("field") == "key") {
                t = " field='key'";
            }
            else {
                if (s == "ref") {
                    t = " refTable='" + o.getAttribute("reftable") + "'";
                }
                else {
                    t = " field='key'";
                }
            }
        }
        if (o.type == "checkbox") {
            a = " list='true'";
            e = e.substring(0, e.indexOf('$'));
        }

        if (o.getAttribute("list") == "true") {
            a = " list='true'";
        }

        if (o.getAttribute("tb")) {
            e = o.getAttribute("tb") + '.' + e;
        }

        a += " type='" + o.getAttribute("tipo") + "'";

        if (document.aspnetForm.getElementsByTagName("*")["tdLbl" + o.id] != null) {
            a += " description='" + document.aspnetForm.getElementsByTagName("*")["tdLbl" + o.id].innerText + "'";
        }

        if (o.type == "select-multiple") {
            var arr = s.split('*');
            for (i = 0; i < arr.length; i++) {
                if (arr[i].length > 0) {
                    sRetorno += "<" + e.toLowerCase() + a + t + ">" + UnicodeToUTF8(arr[i]) + "</" + e.toLowerCase() + ">";
                }
            }
        } else {
            sRetorno = "<" + e.toLowerCase() + a + t + ">" + UnicodeToUTF8(s) + "</" + e.toLowerCase() + ">";
        }
        return sRetorno;
    }
}

function displayMissingValue(fieldName) {
    alert("Você deve fornecer um valor para " + fieldName + ".");
}


function salvarPagina(bFechar, bLimpar, bNovoMetodo) {
    if (typeof antesSalvar2 == 'function') {
        if (!antesSalvar2()) {
            return false;
        }
    }

    if (typeof antesSalvar == 'function') {
        antesSalvar();
    }
    var iStatus = carregarXml(true, (document.aspnetForm.aspnetFormSubmitId.value != ""), bNovoMetodo);
    if (iStatus == 1) {
        var objBtnSalvar = document.getElementById("btnSalvar");
        var objBtnCancelar = document.getElementById("btnCancelar");
        var objBtnSalvarFechar = document.getElementById("btnSalvarFechar");

        try {
            document.body.style.cursor = "wait";
            var objLay = document.getElementById("layAviso");
            var objTam = new TamanhoDocumento();
            if (objLay) {
                objLay.style.left = Math.abs((objTam.width - parseInt(objLay.style.width)) / 2) + "px";
                objLay.style.top = Math.abs((objTam.height - parseInt(objLay.style.height)) / 2) + "px";
                objLay.style.display = 'block';
                objLay.style.zIndex = 1000;
                objLay.style.textAlign = 'left';
            }

            if (objBtnSalvarFechar) {
                objBtnSalvarFechar.disabled = true;
            }

            if (objBtnSalvar) {
                objBtnSalvar.disabled = true;
            }

            if (objBtnCancelar) {
                objBtnCancelar.disabled = true;
            }
            var o = new Object();
            o.bFechar = bFechar;
            o.bLimpar = bLimpar;
            SalvarAjax(o);

        } catch (e) {
            document.body.style.cursor = "default";

            if (objBtnSalvarFechar) {
                objBtnSalvarFechar.disabled = false;
            }

            if (objBtnSalvar) {
                objBtnSalvar.disabled = false;
            }

            if (objBtnCancelar) {
                objBtnCancelar.disabled = false;
            }
        }
    }
    else {
        _bSaving = false;
        return false;
    }
}
function retornarSalvar(res) {
    document.body.style.cursor = "default";
    var objLay = document.getElementById("layAviso");
    var objBtnSalvar = document.getElementById("btnSalvar");
    var objBtnCancelar = document.getElementById("btnCancelar");
    var objBtnSalvarFechar = document.getElementById("btnSalvarFechar");
    var bInsert = document.aspnetForm.bInsert.value == '1';

    if (objLay) {
        objLay.style.display = 'none';
    }

    if (objBtnSalvarFechar) {
        objBtnSalvarFechar.disabled = false;
    }

    if (objBtnSalvar) {
        objBtnSalvar.disabled = false;
    }

    if (objBtnCancelar) {
        objBtnCancelar.disabled = false;
    }
    if (res.error != null) {
        Erro(res.error.Message, "");
    }
    else {
        _bSaving = true;
        OK('Aviso', cadastro_efetuado_com_sucesso);
        if (document.aspnetForm.bReload.value == '1' && bInsert) {
            //Verifica se é pra fechar a janela
            var bFechar = ((res.context) && (res.context.bFechar));
            if (bFechar) {
                window.close();
            }
            else {
                var sListaChave = '';
                try {
                    sListaChave = preencheListaChave(res.value);
                }
                catch (e) {
                    sListaChave = preencheListaChave2(res.value);
                }

                var url = MontarUrlAjax(sListaChave);
                window.location.href = url.value;
            }
        } else {
            try {
                preencheChave(res.value);
            }
            catch (e) {
                preencheChave2(res.value);
            }
            if (res.context) {
                if (res.context.bFechar) {
                    window.close();
                }
                else {
                    if (res.context.bLimpar) {
                        Reset();
                    }
                }
            }
            document.aspnetForm.bInsert.value = '0';
        }
        recarregarGrid();
        if (typeof aposSalvar == 'function') {
            aposSalvar(bInsert, res.value);
        }
    }
}

function preencheListaChave2(o) {
    var sLista = '';
    var oKey = EncontrarObjetoID("key", "INPUT");
    var sPrefixo = "";
    var arrChave = Trim(oKey.value).split(',');
    var arrCampos = new Array();

    if (oKey.name.indexOf("$") > -1) {
        sPrefixo = oKey.name.substring(0, oKey.name.lastIndexOf("$") + 1).replace(/\$+/gi, '_');
    }

    for (i = 0; i < arrChave.length; i++) {
        arrChave[i] = Trim(arrChave[i]);
        arrCampos[i] = document.getElementById(sPrefixo + "_c" + arrChave[i]);

        if (arrCampos[i] == null) {
            arrCampos[i] = EncontrarObjetoID(arrChave[i], 'input');
        }

        if (arrCampos[i] == null) {
            arrCampos[i] = EncontrarObjetoID(arrChave[i], 'select');
        }
    }

    var valor = null;
    var sNomeCampo = '';
    for (i = 0; i < arrCampos.length; i++) {
        if (arrCampos[i]) {
            valor = o.getValue(arrCampos[i].getAttribute("tb").toLowerCase());
            if (valor != null) {
                sNomeCampo = arrCampos[i].name;
                sLista += sNomeCampo.substring(sNomeCampo.indexOf('_x_') + 3, sNomeCampo.length) + '=' + valor + '&';
            }
        }
    }
    if (sLista.length > 0) {
        sLista = sLista.substring(0, sLista.length - 1);
    }
    return sLista;
}

function preencheChave(o) {
    if (document.forms[0].key.value.length > 0) {
        var arrChave = Trim(document.forms[0].key.value).split(',');
        var arrCampos = new Array();
        for (i = 0; i < arrChave.length; i++) {
            arrChave[i] = Trim(arrChave[i]);
            arrCampos[i] = document.getElementById("_c" + arrChave[i]);
        }

        var valor = null;
        for (i = 0; i < arrCampos.length; i++) {
            if (arrCampos[i] != null) {
                valor = o.getValue(arrCampos[i].getAttribute("tb").toLowerCase());
                if (valor != null) {
                    arrCampos[i].value = valor;
                }
            }
        }

        if (document.forms[0].reftable && document.forms[0].reftable.length > 0) {
            var arrReftable = Trim(document.forms[0].reftable.value).split(',');
            if (arrReftable.length > 0) {
                arrCampos = new Array();
                for (i = 0; i < arrReftable.length; i++) {
                    arrCampos[i] = document.getElementById("_c" + arrReftable[i]);
                }
                var valor = null;
                for (i = 0; i < arrCampos.length; i++) {
                    if (arrCampos[i] != null) {
                        valor = o.getValue(arrCampos[i].getAttribute("reftable").toLowerCase());
                        if (valor != null) {
                            arrCampos[i].value = valor;
                        }
                    }
                }
            }
        }
    }
}

function preencheChave2(o) {
    var oKey = EncontrarObjetoID("key", "INPUT");
    if (oKey.value.length > 0) {
        var arrChave = Trim(oKey.value).split(',');
        var arrCampos = new Array();
        var sPrefixo = "";
        if (oKey.name.indexOf("$") > -1) {
            sPrefixo = oKey.name.substring(0, oKey.name.lastIndexOf("$") + 1).replace(/\$+/gi, '_');
        }

        for (i = 0; i < arrChave.length; i++) {
            arrChave[i] = Trim(arrChave[i]);
            arrCampos[i] = document.getElementById(sPrefixo + "_c" + arrChave[i]);
        }

        var valor = null;
        for (i = 0; i < arrCampos.length; i++) {
            if (arrCampos[i] != null) {
                valor = o.getValue(arrCampos[i].getAttribute("tb").toLowerCase());
                if (valor != null) {
                    arrCampos[i].value = valor;
                }
            }
        }

        var oRefTab = EncontrarObjetoID("reftable", "INPUT");
        sPrefixo = ""
        if (oRefTab && oRefTab.value.length > 0) {
            if (oRefTab.name.indexOf("$") > -1) {
                sPrefixo = oRefTab.name.substring(0, oRefTab.name.lastIndexOf("$") + 1).replace(/\$+/gi, '_');
            }

            var arrReftable = Trim(oRefTab.value).split(',');
            if (arrReftable.length > 0) {
                arrCampos = new Array();
                for (i = 0; i < arrReftable.length; i++) {
                    arrCampos[i] = document.getElementById(sPrefixo + "_c" + arrReftable[i]);
                }
                var valor = null;
                for (i = 0; i < arrCampos.length; i++) {
                    if (arrCampos[i] != null) {
                        valor = o.getValue(arrCampos[i].getAttribute("reftable").toLowerCase());
                        if (valor != null) {
                            arrCampos[i].value = valor;
                        }
                    }
                }
            }
        }
    }
}

function preencheListaChave(o) {
    var sLista = '';
    var oKey = EncontrarObjetoID("key", "INPUT");
    var sPrefixo = "";
    var arrChave = Trim(oKey.value).split(',');
    var arrCampos = new Array();

    if (oKey.name.indexOf("$") > -1) {
        sPrefixo = oKey.name.substring(0, oKey.name.lastIndexOf("$") + 1).replace(/\$+/gi, '_');
    }

    for (i = 0; i < arrChave.length; i++) {
        arrChave[i] = Trim(arrChave[i]);
        arrCampos[i] = document.getElementById(sPrefixo + "_c" + arrChave[i]);

        if (arrCampos[i] == null) {
            arrCampos[i] = EncontrarObjetoID(arrChave[i], 'input');
        }

        if (arrCampos[i] == null) {
            arrCampos[i] = EncontrarObjetoID(arrChave[i], 'select');
        }
    }

    var valor = null;
    var sNomeCampo = '';
    for (i = 0; i < arrCampos.length; i++) {
        if (arrCampos[i]) {
            valor = o.getValue(arrCampos[i].getAttribute("tb").toLowerCase());
            if (valor != null) {
                sNomeCampo = arrCampos[i].name;
                sLista += sNomeCampo.substring(sNomeCampo.indexOf('_x_') + 3, sNomeCampo.length) + '=' + valor + '&';
            }
        }
    }
    if (sLista.length > 0) {
        sLista = sLista.substring(0, sLista.length - 1);
    }
    return sLista;
}

function $d(o) {
    var a = AtributoControl().value;
    a.a = o.getAttribute("a");
    a.fontedado = o.getAttribute("fontedado");
    if (o.getAttribute("dependencia")) {
        var arrDependencia = Trim(o.getAttribute("dependencia")).split(',');
        for (i = 0; i < arrDependencia.length; i++) {
            a.hsdependencia.add(Trim(arrDependencia[i]), rv(arrDependencia[i]));
        }
    }
    return a;
}
function carregarLista_callback(res) {
    if (res.error != null) {
        Erro(res.error.Message, "");
    }
    else {
        PopulaCombo(res.value.toString(), res.context)
    }
}
function pesquisarValor(id) {
    var control;
    control = document.getElementById(id);
    if (typeof (control.value) == "string") {
        return control.value;
    }
    return pesquisarValorRecursivo(control);
}
function pesquisarValorRecursivo(control) {
    if (typeof (control.value) == "string" && (control.type != "radio" || control.checked == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i < control.childNodes.length; i++) {
        val = pesquisarValorRecursivo(control.childNodes[i]);
        if (val != "") { return val; }
    }
    return "";
}

function AbaReset(sImgName, oDiv, oTdId) {
    var arrElements = document.getElementsByTagName("TD");
    for (x = 0; x < arrElements.length; x++) {
        if (arrElements[x].className == "abaOn" && arrElements[x].id.indexOf(oTdId) > -1) {
            AplicarEstilo(arrElements[x], "aba");
        }
    }
    arrElements = document.getElementsByTagName("IMG");
    var count = 0;
    for (x = 0; x < arrElements.length; x++) {
        if (arrElements[x].name.indexOf(sImgName) > -1) {
            if (count == 0) {
                arrElements[x].src = PTA_sProjeto + "core/images/aba_01.gif";
                count++;
            } else {
                arrElements[x].src = PTA_sProjeto + "core/images/aba_03.gif";
                count--;
            }
        }
    }
}

function ResetAbaCorpo(oDiv) {
    if (oDiv) {
        arrElements = document.getElementsByTagName("DIV");
        for (x = 0; x < arrElements.length; x++) {
            if (arrElements[x].id.indexOf(oDiv) > -1) {
                arrElements[x].style.display = 'none';
            }
        }
    }
}

//-------------------------------------------------------------------------
//AbaClick(o, sImgName, oDiv, arrObjDivEsconder)
//@arrObjDivEsconder = Lista de ID de Objetos que serão escondidos
//Caso seja passado ele procurará os objetos e setará a propriedade display para none
//Exemplo: arrObjDivEsconder = 'layAba,layBotao,layCampo'
//-------------------------------------------------------------------------
function AbaClick(o, sImgName, oDiv, arrObjDivEsconder) {
    AbaClickOverride(o, sImgName, oDiv, arrObjDivEsconder);
}

//-------------------------------------------------------------------------
//AbaClick2(o, sImgName, oDiv)
//-------------------------------------------------------------------------
function AbaClick2(oTd, sImgName, oDiv) {
    AbaClickOverride(oTd, sImgName, oDiv);
}

//-------------------------------------------------------------------------
//AbaClickOverride(o, sImgName, oDiv)
//-------------------------------------------------------------------------
function AbaClickOverride(o, sImgName, oDiv, arrObjDivEsconder) {
    try {
        oTd = ProcurarPai(o, "TD");
        ResetAbaCorpo("abaCorpo");
        if (oTd.className != "abaOn") {
            AbaReset("imgAba", "abaCorpo", "tabAba");

            oImg = eval("document." + sImgName + "_01");
            oImg.src = PTA_sProjeto + "core/images/aba_ativa_01.gif";

            oImg = eval("document." + sImgName + "_02");
            oImg.src = PTA_sProjeto + "core/images/aba_ativa_03.gif";

            AplicarEstilo(oTd, 'abaOn');
        }

        if (arrObjDivEsconder) {
            var arrDivs = arrObjDivEsconder.split(',');

            var x;
            for (x = 0; x < arrDivs.length; x++) {
                MostrarEsconderObjeto(document.getElementById(arrDivs[x]), false);
            }
        }

        var msg = document.getElementById('Msg' + oDiv);
        if (msg) {
            if (msg.innerHTML.length > 0) {
                MostrarEsconderObjeto(document.getElementById('layTabMsgAviso'), true);
                document.getElementById('MsgAvisoAba').innerHTML = msg.innerHTML;
            } else {
                MostrarEsconderObjeto(document.getElementById('layTabMsgAviso'), false);
            }
        }

        if (oDiv) {
            MostrarEsconderObjeto(document.getElementById(oDiv), true);
        }
    }
    catch (e) {
    }
}

function AbaClickLink(o, sImgName, sURL) {
    try {
        window.location.href = sURL;
    }
    catch (e) {
    }
}

function AbaOut(o, sImgName) {
    try {
        oTd = ProcurarPai(o, "TD");

        if (oTd.className != "abaOn") {
            oImg = eval("document." + sImgName + "_01");
            oImg.src = PTA_sProjeto + "core/images/aba_01.gif";

            oImg = eval("document." + sImgName + "_02");
            oImg.src = PTA_sProjeto + "core/images/aba_03.gif";

            AplicarEstilo(oTd, 'aba');
        }

    }
    catch (e) {
    }
}

function AbaOver(o, sImgName) {
    try {
        oTd = ProcurarPai(o, "TD");

        if (oTd.className != "abaOn") {
            oImg = eval("document." + sImgName + "_01");
            oImg.src = PTA_sProjeto + "core/images/aba_over_01.gif";

            oImg = eval("document." + sImgName + "_02");
            oImg.src = PTA_sProjeto + "core/images/aba_over_03.gif";

            AplicarEstilo(oTd, 'abaOvr');
        }
    }
    catch (e) {
    }
}
function SelecionaLinhasRender(oFrmName, oCkbName) {
    var o = eval(oFrmName + '.' + oCkbName);
    for (i = 0; i < o.length; i++) {
        if (o[i].checked) {
            SelecionaLinhaChk(o[i]);
        }
    }
}

function DestacaTituloGrid(obj) {
    o = ProcurarPai(obj, "TH");
    if (o) {
        AplicarEstilo(o, "tdTituloListaOn");
    }
}

function RestoraTituloGrid(obj) {
    o = ProcurarPai(obj, "TH");
    if (o) {
        AplicarEstilo(o, "tdTituloLista");
    }
}

function SelecionaTodasLinhasChk(obj, objProcurar) {
    if (objProcurar) {
        if (objProcurar.length != null) {
            for (i = 0; i < objProcurar.length; i++) {
                if (!objProcurar[i].disabled) {
                    objProcurar[i].checked = (obj.checked);
                    SelecionaLinhaChk(objProcurar[i]);
                }
            }
        } else {
            if (!objProcurar.disabled) {
                objProcurar.checked = (obj.checked);
                SelecionaLinhaChk(objProcurar);
            }
        }
    }
}

function SelecionaLinhaRadio(obj) {
    var id = obj.id;
    var tam = eval("document.forms[0]." + id + ".length");
    var o = eval("document.forms[0]." + id);
    if (obj.type == "radio") {
        if (tam > 0) {
            for (var x = 0; x < tam; x++) {
                DeselecionaLinha(o[x]);
            }
        }

        if (!obj.checked) {
            DeselecionaLinha(obj);
        }
        else {
            SelecionaLinha(obj);
        }
    }
}

function SelecionaLinhaChk(obj, bEstiloSecundario) {
    if (obj.type == "checkbox") {
        if (!obj.checked) {
            DeselecionaLinha(obj, bEstiloSecundario);
        }
        else {
            SelecionaLinha(obj);
        }
    }
}

function SelecionaLinha(obj) {
    o = ProcurarPai(obj, "TR");
    if (o) {
        var x = 0;
        while (x < o.cells.length) {
            AplicarEstilo(o.cells[x], "tdItemListaOn");
            x++;
        }
    }
}

function DeselecionaLinha(obj, bEstiloSecundario) {
    o = ProcurarPai(obj, "TR");
    if (o) {
        var x = 0;
        while (x < o.cells.length - 1) {
            if (bEstiloSecundario == null) {
                AplicarEstilo(o.cells[x], "tdItemLista");
            }
            else {
                AplicarEstilo(o.cells[x], "tdItemListaSemBorda");
            }
            x++;
        }
        AplicarEstilo(o.cells[x], "tdItemListaFim");
    }
}

//obj = Objeto que desejar mostrar ou esconder
//bMostrar = booleano, true para mostrar, false para esconder
function MostrarEsconderObjeto(obj, bMostrar) {
    var bw = new PTADetectorBrowser();
    if (obj) {
        if (!bMostrar) {
            obj.style.display = "none";
        } else {
            if (!bw.ie) {
                switch (obj.tagName) {
                    case "CAPTION":
                        obj.style.display = "table-caption";
                        break;
                    case "TD":
                    case "TH":
                        obj.style.display = "table-cell";
                        break;
                    case "TR":
                        obj.style.display = "table-row";
                        break;
                    case "COL":
                        obj.style.display = "table-column";
                        break;
                    case "TFOOT":
                        obj.style.display = "table-footer-group";
                        break;
                    case "THEAD":
                        obj.style.display = "table-header-group";
                        break;
                    case "TBODY":
                        obj.style.display = "table-row-group";
                        break;
                    case "TABLE":
                        obj.style.display = "table";
                        break;
                    case "LI":
                        obj.style.display = "list-item";
                        break;
                    default:
                        obj.style.display = "";
                        break;
                }
            }
            else {
                obj.style.display = "";
            }
        }
    }
}

function setarTamanhoJanela(width, height) {
    if (window.outerWidth) {
        window.outerWidth = width;
        window.outerHeight = height;
    }
    else {
        if (window.resizeTo) {
            window.resizeTo(width, height);
        }
    }
    nPosLeft = (screen.width) ? (screen.width - width) / 2 : 100;
    nPosTop = (screen.height) ? (screen.height - height) / 2 - 50 : 100;

    window.moveTo(nPosLeft, nPosTop);
}

function AtivarActiveXControls() {
    objects = document.getElementsByTagName("object");
    for (var i = 0; i < objects.length; i++) {
        objects[i].outerHTML = objects[i].outerHTML;
    }
}

function extraiScript(texto) {
    var ini = 0;
    while (ini != -1) {
        ini = texto.indexOf('<script', ini);
        if (ini >= 0) {
            ini = texto.indexOf('>', ini) + 1;
            var fim = texto.indexOf('</script>', ini);
            codigo = texto.substring(ini, fim);
            novo = document.createElement("script")
            novo.text = codigo;
            document.body.appendChild(novo);
        }
    }
}

function EncontrarObjetoID(sObjID, sTipo) {
    var sArrLista = document.getElementsByTagName(sTipo);
    for (var x = 0; x < sArrLista.length; x++) {
        if (sArrLista[x].id.indexOf(sObjID) != -1) {
            var nPosicaoIni = sArrLista[x].id.indexOf(sObjID);
            var nTamanho = sArrLista[x].id.toString().length;
            if (sArrLista[x].id.substring(nPosicaoIni, nTamanho) == sObjID) {
                return sArrLista[x];
            }
        }
    }
}

function EncontrarTodosObjetoID(sObjID, sTipo) {
    var sArrLista = document.getElementsByTagName(sTipo);
    var oArrRetorno = new Array();
    for (var x = 0; x < sArrLista.length; x++) {
        if (sArrLista[x].id.indexOf(sObjID) != -1) {
            oArrRetorno.push(sArrLista[x]);
        }
    }
    return oArrRetorno;
}

function PTAEncontraObj(NomeObj, d) {
    var p, i, x;
    if (!d) d = document;
    if ((p = NomeObj.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[NomeObj.substring(p + 1)].document;
        NomeObj = NomeObj.substring(0, p);
    }
    if (!(x = d[NomeObj]) && d.all) {
        x = d.all[NomeObj];
    }
    for (i = 0; !x && i < d.forms.length; i++) {
        x = d.forms[i][NomeObj];
    }
    for (i = 0; !x && d.layers && i < d.layers.length; i++) {
        x = PTAEncontraObj(NomeObj, d.layers[i].document);
    }
    if (!x && document.getElementById) {
        x = document.getElementById(NomeObj);
    }
    return x;
}

// Retorna o primeiro objeto que possui o atributo sNmAtributo definido com o valor sVlAtributo
function PTAEncontraObjPorAtributo(sNmAtributo, sVlAtributo) {
    var arrElementos = document.getElementsByTagName('*');
    for (var i = 0; i < arrElementos.length; i++) {
        if (arrElementos[i].getAttribute(sNmAtributo) == sVlAtributo) {
            return arrElementos[i];
        }
    }

    return null;
}

function FindControl(objeto, strControl) {
    var oRetorno;
    for (var i = 0; i < objeto.childNodes.length; i++) {
        if (objeto.childNodes[i].name) {
            if (objeto.childNodes[i].name.indexOf(strControl) >= 0) {
                return objeto.childNodes[i];
            }
        }
        oRetorno = FindControl(objeto.childNodes[i], strControl);
        if (oRetorno) {
            break;
        }
    }
    return oRetorno;
}

function FindControlByID(objeto, strControl) {
    var oRetorno;
    for (var i = 0; i < objeto.childNodes.length; i++) {
        if (objeto.childNodes[i].id) {
            if (objeto.childNodes[i].id.indexOf(strControl) >= 0) {
                return objeto.childNodes[i];
            }
        }
        oRetorno = FindControlByID(objeto.childNodes[i], strControl);
        if (oRetorno) { break; }
    }
    return oRetorno;
}

function SetarTituloPagina(sTitulo) {
    if (sTitulo != "" && top.frames["main"].document.getElementById("lblTituloPagina")) {
        top.frames["main"].document.getElementById("lblTituloPagina").innerHTML = unescape(sTitulo);
    }
    else if (document.getElementById("lblTituloPagina")) {
        document.getElementById("lblTituloPagina").innerHTML = unescape(sTitulo);
    }
}

function SetarNomeUsuario(sNome) {
    if (sNome != "" && top.frames["main"].document.getElementById("layUser")) {
        top.frames["main"].document.getElementById("layUser").innerHTML = unescape(sNome);
    } else if(document.getElementById("layUser")) {
        document.getElementById("layUser").innerHTML = unescape(sNome);
    }
}

function AbrirJanela(sUrl, nLargura, nAltura, bCentralizado, bScroll, sNomeJanela, bMaximizado, bRedimencionavel) {
    var bw = new PTADetectorBrowser();
    if (!bw.ie7) {
        nAltura = Number(nAltura) + 20;
        nLargura = Number(nLargura) + 10;
    }

    var sParametros = '';
    sParametros += 'location=no,directories=no,status=no,menubar=no,toolbar=no,';

    if (nLargura == true) {
        bMaximizado = true;
        bRedimencionavel = true;
        bScroll = true;
    }

    if (bRedimencionavel) {
        sParametros += 'resizable=yes,';
    } else {
        sParametros += 'resizable=no,';
    }

    if (bMaximizado) {
        sParametros += 'width=' + (screen.availWidth - 10) + ', height=' + (screen.availHeight - 20) + ', top=0, left=0';
    }
    else {
        sParametros += 'width=' + nLargura + ', height=' + nAltura;
        if (bCentralizado) {
            nPosLeft = (screen.width) ? (screen.width - nLargura) / 2 : 100;
            nPosTop = (screen.height) ? (screen.height - nAltura) / 2 - 50 : 100;

            sParametros += ', top=' + nPosTop + ', left=' + nPosLeft;
        }
    }


    if (bScroll) {
        sParametros += ', scrollbars=1';
    }
    else {
        sParametros += ', scrollbars=0';
    }

    if (sNomeJanela == "" || sNomeJanela == null) {
        sNomeJanela = "WBCPOPUP";
    }
    var NovaJanela = window.open(sUrl, sNomeJanela, sParametros);
    NovaJanela.focus();

    return NovaJanela;
}


function AbrirJanela2(sUrl, nLargura, nAltura, bCentralizado, bScroll, sNomeJanela, bMaximizado, bRedimencionavel) {
    var bw = new PTADetectorBrowser();
    if (!bw.ie7) {
        nAltura = Number(nAltura) + 20;
        nLargura = Number(nLargura) + 10;
    }

    var sParametros = '';
    sParametros += 'location=no,directories=no,status=no,menubar=no,toolbar=no,';

    if (bRedimencionavel) {
        sParametros += 'resizable=yes,';
    } else {
        sParametros += 'resizable=no,';
    }

    if (bMaximizado) {
        sParametros += 'width=' + (screen.availWidth - 10) + ', height=' + (screen.availHeight - 20) + ', top=0, left=0';
    }
    else {
        sParametros += 'width=' + nLargura + ', height=' + nAltura;
        if (bCentralizado) {
            nPosLeft = (screen.width) ? (screen.width - nLargura) / 2 : 100;
            nPosTop = (screen.height) ? (screen.height - nAltura) / 2 - 50 : 100;

            nPosLeft = -10;
            nPosTop = -10;

            sParametros += ', top=' + nPosTop + ', left=' + nPosLeft;
        }
    }


    if (bScroll) {
        sParametros += ', scrollbars=1';
    } else {
        sParametros += ', scrollbars=0';
    }

    if (sNomeJanela == "" || sNomeJanela == null) {
        sNomeJanela = "WBCPOPUP";
    }
    var NovaJanela = window.open(sUrl, sNomeJanela, sParametros);
    NovaJanela.focus();

    return NovaJanela;
}


function AbrirJanelaDialogo(sUrl, objDialogParametro, nWidth, nHeight, bCentralizado, bScroll) {
    AbrirJanelaDlg(sUrl, objDialogParametro, nWidth, nHeight, bCentralizado, bScroll);
}
function AbrirJanelaDlg(sUrl, objDialogParametro, nWidth, nHeight, bCentralizado, bScroll, nLeft, nTop) {
    var sParametro = "";
    var bw = new PTADetectorBrowser();
    if (!bw.ie7) {
        nHeight = parseInt(nHeight) + 20;
        nWidth = parseInt(nWidth) + 10;
    }


    if (window.showModalDialog) {
        sParametro = "help:0; status:0;unadorned:1;";
        if (nHeight) { sParametro += "dialogHeight:" + nHeight + "px;"; } else { sParametro += "dialogHeight:350px;"; }
        if (nWidth) { sParametro += "dialogWidth:" + nWidth + "px;"; } else { sParametro += "dialogWidth:500px;"; }
        if (bCentralizado) { sParametro += "center:1;"; } else { sParametro += "center:0;"; }
        if (nLeft) { sParametro += "dialogLeft:" + nLeft + ";"; }
        if (nTop) { sParametro += "dialogTop:" + nTop + ";"; }
        if (bScroll) { sParametro += "scroll:1"; } else { sParametro += "scroll:0;"; }
        return window.showModalDialog(sUrl, objDialogParametro, sParametro);
    } else {
        sParametro = "toolbar=no, directories=no, status=no, menubar=no, resizable=no, modal=yes, dependent=yes, dialog=yes";
        if (nHeight) { sParametro += ",height=" + nHeight; } else { sParametro += ",height=350"; }
        if (nWidth) { sParametro += ",width=" + nWidth; } else { sParametro += ",width=500"; }
        if (bScroll) { sParametro += ",scrollbars=yes"; } else { sParametro += ",scrollbars=no"; }
        if (bCentralizado) {
            sParametro += "screenY=" + ((screen.availHeight - nHeight) / 2) + ",";
            sParametro += "screenX=" + ((screen.availWidth - nWidth) / 2);
        }
        if (nLeft) { sParametro += ",screenX=" + nLeft; }
        if (nTop) { sParametro += ",screenY=" + nTop; }

        return window.open(sUrl, "PTADialog", sParametro);
    }
}

function RetornarParentDocument() {
    if (window.opener) {
        return window.opener;
    }
    else {
        return window.dialogArguments;
    }
}

function AbrirMenu(sUrl, sTarget, sTituloPagina, nNrWidth, nNrHeight, sCdMenu) {
    try {
        nWidth = (nNrWidth != "") ? nNrWidth : 600;
        nHeight = (nNrHeight != "") ? nNrHeight : 550;

        switch (sTarget) {
            case "novajanela":
                AbrirJanela(sUrl, nWidth, nHeight, true, false, sCdMenu);
                break;
            case "novajanelamaximizada":
                AbrirJanela(sUrl, nWidth, nHeight, true, false, sCdMenu, true, true);
                break;
            case "minhaempresa":
                AbrirJanela(sUrl, nWidth, nHeight, true, false, 'EmpresaManutencao');
                break;
            case "sobre":
                AbrirJanelaDialogo(sUrl, '', nWidth, nHeight, true, false);
                break;
            case "imprimir":
                var bw = new PTADetectorBrowser();
                x = top.frames["main"];

                if (bw.ie) {
                    x.frmConteudo.focus();
                    x.frmConteudo.print();
                } else {
                    x = top.frames["main"];
                    var y = x.document.getElementsByTagName("IFRAME");
                    for (x = 0; x < y.length; x++) {
                        if (y[x].id == "frmConteudo") {
                            y[x].focus();
                            print();
                            break;
                        }
                    }
                }
                break;
            case "ajuda":
                AbrirJanela(sUrl, nWidth, nHeight, true, false, "Ajuda", false, true);
                break;
            case "configurador_de_ajuda":
                AbrirJanela(sUrl, nWidth, nHeight, true, false, "Ajuda", true, true);
                break;
            case "desconectar":
                top.location = PTA_sProjeto + 'default.aspx';
                break;
            case "sair":
                top.close();
                break;
            default:
                document.getElementById("frmConteudo").src = sUrl;
                SetarTituloPagina(sTituloPagina);
                break;
        }
    }
    catch (e) {
        alert(e.message);
        return false;
    }
}


function ProcurarPai(obj, sElemento) {
    var o = obj;
    while (o.tagName != sElemento) {
        o = o.parentNode;
        if (o == null) { return; }
    }
    return o;
}

function AplicarEstilo(obj, Estilo) {
    obj.className = Estilo;
}

function TamanhoDocumento() {
    var bw = new PTADetectorBrowser();

    if (bw.ie) {
        this.width = document.body.offsetWidth;
        this.height = document.body.offsetHeight;
    } else {
        this.width = innerWidth;
        this.height = innerHeight;
    }

    return this;
}

function PTADetectorBrowser() {
    this.ver = navigator.appVersion;
    this.agent = navigator.userAgent;
    this.dom = document.getElementById ? 1 : 0;
    this.opera5 = this.agent.indexOf("Opera 5") > -1;
    this.ie4 = (document.all && !this.dom && !this.opera5) ? 1 : 0;
    this.ie5 = (this.ver.indexOf("MSIE 5") > -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie6 = (this.ver.indexOf("MSIE 6") > -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie7 = (this.ver.indexOf("MSIE 7") > -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie8 = (this.ver.indexOf("MSIE 8") > -1 && this.dom && !this.opera5) ? 1 : 0;
    this.ie = (this.ie4 || this.ie5 || this.ie6 || this.ie7 || this.ie8);
    this.mac = this.agent.indexOf("Mac") > -1;
    this.ns4 = (document.layers && !this.dom) ? 1 : 0;
    this.ns6 = (this.dom && parseInt(this.ver) >= 5) ? 1 : 0;
    this.bw = (this.ie8 || this.ie7 || this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5);
    return this;
}

function ReturnComboValue(objCombo) {
    if (objCombo.selectedIndex > -1) {
        return objCombo.options[objCombo.selectedIndex].value;
    }
    else {
        return ("");
    }
}

function ReturnRadioValue(objRadio) {
    var strReturn = "";

    if (objRadio.length) {
        for (var i = 0; i < objRadio.length; i++) {
            if (objRadio[i].checked) {
                strReturn = objRadio[i].value;
                break;
            }
        }
    }
    else {
        if (objRadio.checked) {
            strReturn = objRadio.value;
        }
    }
    return (strReturn);
}

function ReturnCheckValue(objCheckbox, strSeparador) {
    if (!strSeparador) {
        strSeparador = ',';
    }

    var strReturn = "";

    if (objCheckbox.length) {
        for (var i = 0; i < objCheckbox.length; i++) {
            if (objCheckbox[i].checked) {
                strReturn += strSeparador + objCheckbox[i].value;
            }
        }

        if (strReturn.length > 0) {
            strReturn = strReturn.substr(strSeparador.length);
        }
    }
    else {
        if (objCheckbox.checked) {
            strReturn = objCheckbox.value;
        }
    }
    return (strReturn);
}

function ReturnListaChecked(strFormName, strCheckName) {
    var blFound = false;
    for (var x = 0; x < strFormName.length; x++) {
        if (strCheckName.length > 1) {
            if (strCheckName[0].name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                }
            }
        }
        else {
            if (strCheckName.name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                }
            }
        }
    }
    return blFound;
}

function ReturnComboText(objCombo) {
    if (objCombo.selectedIndex > -1) {
        return objCombo.options[objCombo.selectedIndex].text;
    }
    else {
        return ("");
    }
}

function SetComboOption(objCombo, strValue) {
    for (i = 0; i < objCombo.length; i++) {
        if (objCombo.options[i].value == strValue) {
            objCombo.selectedIndex = i;
            break;
        }
    }
}

function SetRadioListOption(objRadio, strValue) {
    for (i = 0; i < objRadio.length; i++) {
        if (objRadio[i].value == strValue) {
            objRadio[i].checked = true;
            break;
        }
    }
}

function setValidatorState(id, enabled) {

    var ctrl = PTAEncontraObj(id);
    if (ctrl) {
        ctrl.enabled = enabled;
        ctrl.IsValid = true;
    }

}

function Trim(s) {
    return s.replace(/^\s+|\s+$/g, '');
}

function decodeXml(s) {
    // remove all unicode encoded symbols
    try {
        s = eval('"' + s.replace(/&#x(\w\w\w\w);/g, "\\u$1").replace(/"/g, '\\"') + '"');
    }
    catch (e) { }
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&apos;/g, "'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/&amp;/g, "&");
    return s;
}

function UnicodeToUTF8(s) {
    if (!s) {
        return "";
    }

    s = escape(s);

    s = s.replace(/%20/g, " ");
    s = s.replace(/%u(\w{4})/g, "&#x$1;");
    s = s.replace(/%(\w{2})/g, "&#x$1;");

    return s;
}

function Legenda(o, sCssClass) {
    try {
        AplicarEstilo(o, sCssClass);

        var oImg = document.getElementById("imgIcoLegenda");
        var oLay = document.getElementById("layLegendaBody");

        if (sCssClass == 'tdLegendaOver') {
            if (oLay.style.display != 'block') {
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_b_legenda2.gif");
            }
            else {
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_c_legenda2.gif");
            }
        } else {
            if (oLay.style.display != 'block') {
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_b_legenda_off2.gif");
            }
            else {
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_c_legenda_off2.gif");
            }
        }
    }
    catch (e) {
    }
}

function LegendaClick(o) {
    try {
        var obj = document.getElementById(o);
        var oImg = document.getElementById("imgIcoLegenda");
        if (obj) {
            if (obj.style.display != 'block') {
                obj.style.display = 'block';
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_c_legenda_off2.gif");

            } else {
                obj.style.display = 'none';
                MudaImagem(oImg, oImg.src.substr(0, oImg.src.lastIndexOf("/")) + "/ic_b_legenda_off2.gif");
            }
        }

        if (window.Ajuste_Resize) {
            window.Ajuste_Resize();
        }
    }
    catch (e) {
    }
}

function MudaImagem(oImg, sImgNome) {
    if (oImg) {
        oImg.src = sImgNome;
    }
}

//Nome do txt que eh passado no strMessage = txt_msg_ck_ex_Sel 
//Menssagem do txt_msg_ck_ex_Sel = 'Erro: Nenhum item selecionado.'
//Nome do txt que eh passado no strMessageconfirm = txt_msg_ck_ex_Sel_confirm 
//Menssagem do txt_msg_ck_ex_Sel_confirm = ' item(ns) selecionado(s).\nContinuar ?'
function excluirSelecionados(strFormName, strCheckName, strMessage, strMessageconfirm) {
    if (strFormName == null || strFormName == "" || strFormName == "undefined") {
        OK("Aviso", strMessage);
        return false;
    }

    if (strCheckName == null || strCheckName == "" || strCheckName == "undefined") {
        OK("Aviso", strMessage);
        return false;
    }

    var blFound = false;
    var count = 0;

    for (var x = 0; x < strFormName.length; x++) {
        if (strCheckName.length > 1) {
            if (strCheckName[0].name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                    count++;
                }
            }
        }
        else {
            if (strCheckName.name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                    count++;
                }
            }
        }
    }

    if (blFound) {
        if (strMessageconfirm != '') {
            if (SimNao("Aviso", strMessageconfirm)) {
                return true;
            }
            else {
                return false;
            }
        }
    }
    else {
        OK("Aviso", strMessage);
    }

    return (blFound);
}

function excluirSelecionados2(strFormName, strCheckName, objOk, objConfirme) {
    if (strFormName == null || strFormName == "" || strFormName == "undefined") {
        objOk.show();
        return false;
    }

    if (strCheckName == null || strCheckName == "" || strCheckName == "undefined") {
        objOk.show();
        return false;
    }

    var blFound = false;
    var count = 0;

    for (var x = 0; x < strFormName.length; x++) {
        if (strCheckName.length > 1) {
            if (strCheckName[0].name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                    count++;
                }
            }
        }
        else {
            if (strCheckName.name.indexOf(strFormName.elements[x].name) != -1) {
                if (strFormName.elements[x].checked) {
                    blFound = true;
                    count++;
                }
            }
        }
    }
    if (blFound) {
        if (objConfirme) {
            return objConfirme.show();
        }
    }
    else {
        objOk.show();
    }
    return (blFound)
}

//Faz o replace de um valor por outro em toda a string.
//Parâmetros:
//str -> string que será alterada
//de -> valor que deseja ser alterado
//para -> valor que será substituido pelo valor desejado
function replaceAll(str, de, para) {
    var pos = str.indexOf(de);
    while (pos > -1) {
        str = str.replace(de, para);
        pos = str.indexOf(de);
    }
    return (str);
}

//Nome do txt que eh passado no strMessage = txt_msg_confirmarExclusao 
//Messagem do txt = 'Você tem certeza que deseja excluir o registro ?'
function confirmarExclusao(strMessage) {
    return SimNao("Aviso", strMessage);
}

function CopiarValorCombo(aComboDestino, aComboFonte) {
    for (i = aComboDestino.length; i >= 0; i--) {
        aComboDestino.options[i] = null;
    }
    for (i = 0; i < aComboFonte.length; i++) {
        AdicionarCombo(aComboFonte.options[i].value, aComboFonte.options[i].text, aComboDestino);
    }
    aComboDestino.selectedIndex = 0;
}

// Remove todos os itens (options e optgroups) de um combo
function LimparCombo(objCombo) {
    var objNode = objCombo.firstChild;
    while (objNode != null) {
        var objActualNode = objNode;
        objNode = objNode.nextSibling;

        if (objActualNode.tagName == 'OPTION' || objActualNode.tagName == 'OPTGROUP')
            objCombo.removeChild(objActualNode);
    }
}

// Popula o combo objCombo com os dados de arrItens. 
// O parâmetro arrItens deve ser uma lista de objetos Paradigma.Framework.Web.Controls.PTAListItem
function PopulaCombo2(arrItens, objCombo) {
    LimparCombo(objCombo);

    var objBrowser = new PTADetectorBrowser();
    var arrGrupos = new Array();

    for (var i = 0; i < arrItens.length; i++) {
        if (arrItens[i].sGrupo != '' && arrItens[i].sGrupo != null && arrGrupos[arrItens[i].sGrupo] == null) {
            var objOptGroup = document.createElement("OPTGROUP");
            objOptGroup.label = arrItens[i].sGrupo;
            objCombo.appendChild(objOptGroup);

            arrGrupos[arrItens[i].sGrupo] = objOptGroup;
        }

        var objOption = document.createElement("OPTION");

        if (objBrowser.ns6) {
            objCombo.add(objOption, null);
        }
        else {
            objCombo.add(objOption);
        }

        objOption.value = arrItens[i].sValor;
        objOption.text = arrItens[i].sTexto;

        if (arrItens[i].lstAtributos != null) {
            for (var j = 0; j < arrItens[i].lstAtributos.length; j++) {
                objOption.setAttribute(arrItens[i].lstAtributos[j].sNome, arrItens[i].lstAtributos[j].sValor);
            }
        }
    }
}

function PopulaCombo(Valor, aCombo) {
    oBrowser = new PTADetectorBrowser();

    var elem;
    var matriz = new Array();
    var matTMP = Valor.split(':-:');
    for (i = 0; i < matTMP.length; i++) {
        elem = matTMP[i].split("-:-");
        matriz[i] = new Array(elem[0], elem[1]);
    }
    if (oBrowser.ns4 || oBrowser.ns6) {
        for (i = aCombo.length; i >= 0; i--) {
            aCombo.options[i] = null;
        }
        for (i = 0; i < matriz.length; i++) {
            var elemento = new Option();
            elemento.text = matriz[i][1];
            elemento.value = matriz[i][0];
            if (i == 0) { elemento.defaultSelected = true; elemento.Selected = true; }
            aCombo.options[i] = elemento;
        }
        aCombo.selectedIndex = 0;
    }
    else {
        for (i = aCombo.length - 1; i >= 0; i--) {
            aCombo.remove(i);
        }
        for (i = 0; i < matriz.length; i++) {
            var elemento = document.createElement("OPTION");
            elemento.text = matriz[i][1];
            elemento.value = matriz[i][0];
            aCombo.add(elemento);
        }
    }
}
function AdicionarCombo(sValor, sTexto, aCombo) {
    oBrowser = new PTADetectorBrowser();
    if (oBrowser.ns4 || oBrowser.ns6) {
        var elemento = new Option();
        elemento.text = sTexto;
        elemento.value = sValor;
        aCombo.options[i] = elemento;
    }
    else {
        var elemento = document.createElement("OPTION");
        elemento.text = sTexto;
        elemento.value = sValor;
        aCombo.add(elemento);
    }
}

// Função que retorna o valor dos objetos passados no parâmetro
function retornaValor(o) {
    var sValor = '';
    switch (o.type) {
        case "text":
            if (o.getAttribute("format") == "time") {
                sValor = '';
            }
            else {
                if (o.getAttribute("format") == "datetime") {
                    var oHora = document.getElementById(o.id + '_Hora');
                    var sHora = "";
                    if (oHora) {
                        if (oHora.value.length > 0) {
                            sHora = " " + oHora.value + ":00";
                        }
                    }
                    sValor = o.value + sHora;
                } else {
                    sValor = o.value;
                }
            }
            break;
        case "radio":
            sValor = ReturnRadioValue(o);
            break;
        case "hidden":
            if (o.getAttribute("tipointerface") == "formula") {
                sValor = xmlFormulaAtributoDinamico(o);
            } else {
                sValor = o.value;
            }
            break;
        case "select-one":
            sValor = ReturnComboValue(o);
            break;
        case "select-multiple":
            sValor = saveItens(o);
            break;
        case "checkbox":
            if (o.checked) {
                sValor = o.value;
            }
            break;
        case "password":
            sValor = o.value;
            break;
        default:
            sValor = o.value;
            break;
    }
    return sValor;
}

// Carrega uma data em um PTADateTimeBox
// sIdControle: id do PTADateTimeBox
// sData: data para carregar
function carregaData(sIdControle, sData) {
    var objControle = document.getElementById(sIdControle);
    objControle.value = sData;
    
    var sSeparador = (objControle.getAttribute('PTA_SeparadorData')!= null) ? objControle.getAttribute('PTA_SeparadorData') : "/";

    var sRegExInput = new RegExp(sSeparador, 'g');
    eval("PTA" + sIdControle).Valor = sData.replace(sRegExInput, '');
    eval("PTA" + sIdControle).Exibe();
}

function carregaHora(sIdControle, sHora, sSeparadorHora) {
    var objControle = document.getElementById(sIdControle);
    objControle.value = sHora;

    var sSeparador = (sSeparadorHora != null) ? sSeparadorHora : ":";

    var sRegExInput = new RegExp(sSeparador, 'g');
    eval("PTA" + sIdControle).Valor = sHora.replace(sRegExInput, '');
    eval("PTA" + sIdControle).Exibe();
}


function xmlFormulaAtributoDinamico(o) {
    var sId = o.id.replace('_formula', '');
    return xmlFormula(sId);
}

function xmlFormula(sId) {
    var objFormula = document.getElementById(sId);
    var sIdFormula_formula = sId + '_formula';

    var sConteudoFormula = document.getElementById(sIdFormula_formula).value;
    var sParametros = objFormula.getAttribute("parametro");
    var sAssemblyID = objFormula.getAttribute("assemblyid");

    var sXmlParametros = "";
    if (sParametros.length > 0) {
        var arrTotal = sParametros.split(String.fromCharCode(19));
        for (var i = 0; i < arrTotal.length; i++) {
            arrTotal[i] = arrTotal[i].split(String.fromCharCode(18));
            sXmlParametros += "<parametro id=\"" + arrTotal[i][0] + "\" valor=\"" + arrTotal[i][1] + "\" />";
        }
    }
    return "<formula assemblyid=\"" + sAssemblyID + "\" metaobjeto=\"" + objFormula.getAttribute("metaobjeto") + "\" chavemetaobjeto=\"" + objFormula.getAttribute("chavemetaobjeto") + "\" descricaoformula=\"" + objFormula.getAttribute("descricaoformula") + "\" conteudoformula=\"" + UnicodeToUTF8(sConteudoFormula) + "\">" + sXmlParametros + "</formula>";
}

function varFormula(sLstVar) {
    var sRetorno = "";
    if (sLstVar.toString().length > 0) {
        var arrVariaveis = sLstVar.split(String.fromCharCode(19));
        for (var i = 0; i < arrVariaveis.length; i++) {
            var arrValores = arrVariaveis[i].split(String.fromCharCode(18));
            sRetorno += arrValores[0].toString() + " = " + (arrValores[1].toString().length == 0 ? '" "' : arrValores[1].toString()) + "<br>";
        }
    }
    return sRetorno;
}
function ValidarPreenchimentoVariaveis(val, args) {
    var controltovalidate = document.getElementById(val.controltovalidate)
    args.IsValid = (ValidarPreenchimentoVariaveis_2(controltovalidate));
}

function ValidarPreenchimentoVariaveis_2(obj) {
    var sLstVar = obj.getAttribute("parametro");
    var bRetorno = true;
    if (sLstVar.toString().length > 0) {
        var arrVariaveis = sLstVar.split(String.fromCharCode(19));
        for (var i = 0; i < arrVariaveis.length; i++) {
            arrValores = arrVariaveis[i].split(String.fromCharCode(18));
            if (arrValores[1].toString().length == 0) {
                bRetorno = false;
                AplicarEstilo(document.getElementById('div' + obj.id), 'tex texAviso');
                break;
            }
        }
    }
    return bRetorno;
}

function EncontrarObjeto(sNomeObjeto, d) {
    if (!d) { d = document.forms[0]; }
    for (var x = 0; x < d.elements.length; x++) {
        if (d.elements[x].id.indexOf(sNomeObjeto) != -1) {
            return d.elements[x];
        }
    }
}

function rv(NomeObj, d) {
    var id = '';
    if (!d) d = document.forms[0];
    for (var x = 0; x < d.elements.length; x++) {
        if (d.elements[x].id.indexOf('_x_') != -1) {
            id = d.elements[x].id;
            if (id.substring(id.lastIndexOf('_x_') + 3, id.length) == NomeObj) {
                return retornaValor(d.elements[x]);
            }
        }
    }
}
function recarregarGrid() {
    if (window.opener) {
        try {
            f = window.opener.document.forms[0];
            for (x = 0; x < f.length; x++) {
                if (f[x].id.indexOf('btnPesquisar') > -1) {
                    f[x].click();
                    break;
                }
            }
        } catch (e) { }
    }
}

function recarregarGridForm() {
    if (document.forms[0]) {
        try {
            f = document.forms[0];
            for (x = 0; x < f.length; x++) {
                if (f[x].id.indexOf('btnPesquisar') > -1) {
                    f[x].click();
                    break;
                }
            }
        } catch (e) { }
    }
}
function recarregarGridDialogo() {
    if (RetornarParentDocument()) {
        try {
            f = RetornarParentDocument().document.forms[0];
            for (x = 0; x < f.length; x++) {
                if (f[x].id.indexOf('btnPesquisar') > -1) {
                    f[x].click();
                    break;
                }
            }
        } catch (e) { }
    }
}

function recarregarRelatorio() {
    if (RetornarParentDocument()) {
        try {
            f = RetornarParentDocument().document.forms[0];
            if (f) {
                f.target = '_self';
                f.__EVENTTARGET.value = '';
                f.__EVENTARGUMENT.value = '';
                f.submit();
            }
        } catch (e) { }
    }
}

function ChecaCNPJ(source, objCNPJ) {
    var strCNPJ = objCNPJ;
    var NewCNPJ = "";
    var DV = "";
    var DVCNPJ;
    var s1 = 0;
    var s2 = 0;
    var NewDV;

    if ((strCNPJ.Value.length != 14) || (isNaN(strCNPJ.Value))) {
        objCNPJ.IsValid = false;
        return false;
    }

    DVCNPJ = strCNPJ.Value.substring(0, 12);

    for (i = 1; i <= 4; i++) {
        s1 = s1 + (parseInt(DVCNPJ.charAt(i - 1)) * (6 - i));
    }

    for (i = 5; i <= 12; i++) {
        s1 = s1 + (parseInt(DVCNPJ.charAt(i - 1)) * (14 - i));
    }

    r1 = s1 % 11;
    if (r1 < 2) {
        dv1 = 0;
    }
    else {
        dv1 = 11 - r1;
    }

    s2 = dv1 * 2;

    for (i = 1; i <= 5; i++) {
        s2 = s2 + (parseInt(DVCNPJ.charAt(i - 1)) * (7 - i));
    }
    for (i = 6; i <= 12; i++) {
        s2 = s2 + (parseInt(DVCNPJ.charAt(i - 1)) * (15 - i));
    }
    r2 = s2 % 11;
    if (r2 < 2) {
        dv2 = 0;
    } else {
        dv2 = 11 - r2;
    }

    DV = DV + dv1 + dv2;
    NewDV = strCNPJ.Value.substring(12, 14)
    if (NewDV == DV) {
        objCNPJ.IsValid = true;
        return true
    }
    else {
        objCNPJ.IsValid = false;
        return false;
    }
}


function ChecaCNPJ2(objCNPJ) {
    var strCNPJ = objCNPJ.replace(".", "").replace(".", "").replace(".", "").replace("-", "").replace("/", "").replace(/_/g, "");
    var NewCNPJ = "";
    var DV = "";
    var DVCNPJ;
    var s1 = 0;
    var s2 = 0;
    var NewDV;

    if ((strCNPJ.length != 14) || (isNaN(strCNPJ))) {
        objCNPJ.IsValid = false;
        return false;
    }

    DVCNPJ = strCNPJ.substring(0, 12);

    for (i = 1; i <= 4; i++) {
        s1 = s1 + (parseInt(DVCNPJ.charAt(i - 1)) * (6 - i));
    }

    for (i = 5; i <= 12; i++) {
        s1 = s1 + (parseInt(DVCNPJ.charAt(i - 1)) * (14 - i));
    }
    r1 = s1 % 11;
    if (r1 < 2) {
        dv1 = 0;
    } else {
        dv1 = 11 - r1;
    }

    s2 = dv1 * 2;

    for (i = 1; i <= 5; i++) {
        s2 = s2 + (parseInt(DVCNPJ.charAt(i - 1)) * (7 - i));
    }
    for (i = 6; i <= 12; i++) {
        s2 = s2 + (parseInt(DVCNPJ.charAt(i - 1)) * (15 - i));
    }
    r2 = s2 % 11;
    if (r2 < 2) {
        dv2 = 0;
    }
    else {
        dv2 = 11 - r2;
    }

    DV = DV + dv1 + dv2;
    NewDV = strCNPJ.substring(12, 14);
    if (NewDV == DV) {
        objCNPJ.IsValid = true;
        return true;
    }
    else {
        objCNPJ.IsValid = false;
        return false;
    }
}


function ChecaCPF(source, objCPF) {
    var CPF = objCPF;
    var NewCPF = "";

    if (CPF.Value.length != 11) {
        objCPF.IsValid = false;
        return false;
    }


    var DVCPF = CPF.Value.substring(0, 9);
    var s1 = 0;
    for (i = 1; i <= 9; i++) { s1 = s1 + (parseInt(DVCPF.charAt(i - 1)) * (11 - i)); }
    r1 = s1 % 11;
    if (r1 < 2) { dv1 = 0; }
    else { dv1 = 11 - r1; }
    var s2 = dv1 * 2;
    for (i = 1; i <= 9; i++) { s2 = s2 + (parseInt(DVCPF.charAt(i - 1)) * (12 - i)); }
    r2 = s2 % 11;
    if (r2 < 2) { dv2 = 0; }
    else { dv2 = 11 - r2; }
    var DV = "";
    DV = DV + dv1 + dv2;
    var NewDV = CPF.Value.substring(9, 11);

    if (NewDV == DV) {
        objCPF.IsValid = true;
        return true;
    }
    else {
        objCPF.IsValid = false;
        return false;
    }
}

function VerificaEspacoTrim(source, s) {
    s.IsValid = (s.Value.indexOf(" ") == -1);
}

function $MLCustom(val, args) {
    val.IsValid = ($ML(document.getElementById(val.controltovalidate)));
}
function $ML(el) {
    var TAMaxLength = el.getAttribute("TAMaxLength");
    var sValue = el.value;
    if (sValue.length > TAMaxLength) {
        OK('Aviso', 'Sua caixa de texto atingiu o m&aacute;ximo de ' + TAMaxLength + ' caracteres.');
        el.value = sValue.substring(0, TAMaxLength);
        return false;
    }
    return true;
}

//PTATextBox id="tbxTexto" textmode="MultiLine" rows="3" runat="server" 
//onkeypress="return checkMaxLength(event,this)" TAMaxLength="200" width="100%" cssclass="tar"
function checkMaxLength(e, el) {
    switch (e.keyCode) {
        case 37:
            return true;
        case 38:
            return true;
        case 40:
            return true;
        case 8:
            return true;
        case 27:
            el.value = '';
            return true;
    }
    return (el.value.length < el.getAttribute("TAMaxLength"));
}

function disableCtrlKeyCombination(e) {
    var forbiddenKeys = new Array('86', '78', '67');
    var key;
    var isCtrl;

    if (window.event) {
        key = window.event.keyCode;
        if (window.event.ctrlKey) {
            isCtrl = true;
        }
        else {
            isCtrl = false;
        }
    }
    else {
        key = e.which;
        if (e.ctrlKey) {
            isCtrl = true;
        }
        else {
            isCtrl = false;
        }
    }

    if (isCtrl) {
        for (i = 0; i < forbiddenKeys.length; i++) {
            if (forbiddenKeys[i].toLowerCase() == key) {
                window.event.returnValue = false;
            }
        }
    }
    return true;
}

function formataValorSoma(dblValor) {
    while (dblValor.indexOf('.') != -1) {
        dblValor = dblValor.replace('.', '');
    }
    dblValor = parseFloat(dblValor.replace(',', '.'));
    return dblValor;
}

/*Utilizada para tirar brancos de uma string
Parâmetros: Nome da string que poderá ser um campo*/
function TrimJava(str) {
    var strTrim = new String(str);
    while (strTrim.substr(0, 1) == ' ') {
        strTrim = strTrim.substr(1, strTrim.length - 1);
    }
    while (strTrim.substr(strTrim.length - 1, 1) == ' ') {
        strTrim = strTrim.substr(0, strTrim.length - 2);
    }
    return strTrim;
}
function Arredonda(dblNumero, intCasas) {
    if ((intCasas < 0) || isNaN(intCasas)) {
        return (dblNumero);
    }
    var intQtde = Math.pow(10, intCasas);
    dblNumero = dblNumero * intQtde;
    dblNumero = (Math.round(dblNumero) / intQtde);
    return (dblNumero);
}
function FormataFloat(dblValor, SepMilhar, SepDecimal, CasasDecimais) {
    var CASA_DECIMAL = CasasDecimais;
    var strInteiro = '';
    var strDecimal = '';
    var strValorFinal = '';

    var strValorOriginal = String(Arredonda(dblValor, CASA_DECIMAL));
    var intPos = 0;
    var intTam = 0;
    var intContador1 = 0;
    var intContador2 = 0;
    var Num1 = '';
    var Num2 = '';

    intPos = strValorOriginal.indexOf('.');
    if (intPos >= 0) {
        strInteiro = strValorOriginal.substring(0, intPos);
        strDecimal = strValorOriginal.substr(intPos + 1, strValorOriginal.length - 1);
    }
    else {
        strInteiro = strValorOriginal;
    }
    while (strDecimal.length < CASA_DECIMAL) {
        strDecimal = strDecimal + '0';
    }
    intTam = strInteiro.length;
    while ((intTam % 3) != 0) {
        strInteiro = ' ' + strInteiro;
        intTam = strInteiro.length;
    }
    for (intContador1 = 1; intContador1 <= (intTam / 3); intContador1++) {
        if (strValorFinal != '') {
            strValorFinal = strValorFinal + SepMilhar;
        }
        strValorFinal = strValorFinal + strInteiro.substr(intContador2, 3);
        intContador2 = intContador2 + 3;
    }
    if (strDecimal.length > 0) {
        strValorFinal = strValorFinal + SepDecimal + strDecimal;
    }
    return (TrimJava(strValorFinal));
}

function SetValidatorsAllEnable(bolEnable) {
    for (i = 0; i < Page_Validators.length; i++) {
        Page_Validators[i].enabled = bolEnable;
        Page_Validators[i].IsValid = !bolEnable;
    }
}

function AbrirCalendario(sender, sIdRetorno, e) {
    var bw = PTADetectorBrowser();
    var nLeft = 0;
    var nTop = 0;
    if (bw.ie) {
        nLeft = event.clientX + document.body.scrollLeft;
        nTop = event.clientY + document.body.scrollTop + window.screenTop + sender.offsetHeight + sender.offsetTop;
    } else {
        nLeft = e.pageX;
        nTop = e.pageY;
    }

    var tDtSelecionada = PTAEncontraObj(sIdRetorno);
    var stDtSelecionada = "";
    if (tDtSelecionada) {
        stDtSelecionada = tDtSelecionada.value;
    }
    AbrirJanelaDlg(PTA_sProjeto + 'core/include/calendario.aspx?tDtSelecionada=' + stDtSelecionada + "&sIdRetorno=" + sIdRetorno, window, 250, 170, false, false, nLeft, nTop);
}

function SelecionaSelect(frmDestino, strValor) {
    var isNew = true;
    var thisitem = "";
    var j = 0;
    if (frmDestino.length > 0) {
        for (j = 0; j < frmDestino.length; j++) {
            thisitem = frmDestino.options[j].value;
            if (thisitem == strValor) {
                frmDestino.options[j].selected = true;
                break;
            }
        }
    }
}

// bSituacao: Boolean, parâmetro para mostrar(true) ou restaurar(false) a mensagem da tela.
// [arguments] coleção de objetos a serem desabilitados na tela durante a operação. 
function ProcessarInformacao(bSituacao) {
    if (bSituacao) {
        document.body.style.cursor = "wait";
        for (var y = 1; y < ProcessarInformacao.arguments.length; y++) {
            ProcessarInformacao.arguments[y].disabled = true;
        }
        var objSel = document.getElementsByTagName("SELECT");
        for (var i = 0; i < objSel.length; i++) {
            objSel[i].style.visibility = "hidden";
        }
        var objLay = document.getElementById("layAviso");
        var objTam = new TamanhoDocumento();
        if (objLay) {
            objLay.style.left = Math.abs((objTam.width - parseInt(objLay.style.width)) / 2) + "px";
            objLay.style.top = Math.abs((objTam.height - parseInt(objLay.style.height)) / 2) + "px";
            objLay.style.display = 'block';
            objLay.style.zIndex = 1000;
            objLay.style.textAlign = 'left';
        }
    }
    else {
        document.body.style.cursor = "default";
        for (var y = 1; y < ProcessarInformacao.arguments.length; y++) {
            ProcessarInformacao.arguments[y].disabled = false;
        }
        var objSel = document.getElementsByTagName("SELECT");
        for (var i = 0; i < objSel.length; i++) {
            objSel[i].style.visibility = "visible";
        }
        var objLay = document.getElementById("layAviso");
        if (objLay) {
            objLay.style.display = 'none';
        }
    }
}



/*
+-------------------------------------------------------------------+
|                   J S - T O O L T I P   (v1.5)                    |
|                                                                   |
| Copyright Gerd Tentler               www.gerd-tentler.de/tools    |
| Created: Feb. 15, 2005               Last modified: Mar. 28, 2006 |
+-------------------------------------------------------------------+
| This program may be used and hosted free of charge by anyone for  |
| personal purpose as long as this copyright notice remains intact. |
|                                                                   |
| Obtain permission before selling the code for this program or     |
| hosting this software on a commercial website or redistributing   |
| this software over the Internet or in any other medium. In all    |
| cases copyright must remain intact.                               |
+-------------------------------------------------------------------+

======================================================================================================

This script was tested with the following systems and browsers:

- Windows XP: IE 6, NN 4, NN 7, Opera 7, Firefox 1
- Mac OS X:   IE 5, Safari 1

If you use another browser or system, this script may not work for you - sorry.

------------------------------------------------------------------------------------------------------

USAGE:

Use the toolTip-function with mouse-over and mouse-out events (see example below).

- To show a tooltip, use this syntax: toolTip(text, width in pixels, opacity in percent)
Note: width and opacity are optional

- To hide a tooltip, use this syntax: toolTip()

------------------------------------------------------------------------------------------------------

EXAMPLE:

<a href="#" onMouseOver="toolTip('Just a test', 150)" onMouseOut="toolTip()">some text here</a>

======================================================================================================
*/

var OP = (navigator.userAgent.indexOf('Opera') != -1) ? true : false;
var IE = (navigator.userAgent.indexOf('MSIE') != -1 && !OP) ? true : false;
var GK = (navigator.userAgent.indexOf('Gecko') != -1) ? true : false;
var NN4 = document.layers;
var DOM = document.getElementById;

function TOOLTIP() {
    //----------------------------------------------------------------------------------------------------
    // Configuration
    //----------------------------------------------------------------------------------------------------
    this.width = 200;                // width (pixels)
    this.bgColor = '#FFFFE1';             // background color
    this.textColor = '#000000';           // text color
    this.borderColor = '#CCCCCC';         // border color
    this.opacity = 100;                    // opacity (percent) - doesn't work with all browsers
    this.cursorDistance = 10;              // distance from cursor (pixels)

    // don't change


    this.text = '';
    this.title = '';
    this.height = 0;
    this.obj = 0;
    this.sobj = 0;
    this.active = false;

    this.create = function() {
        if (!this.sobj) this.init();

        var t = '<table border=0 cellspacing=0 cellpadding=3 width=' + this.width + ' bgcolor=' + this.bgColor + '>' + '<tr><td class=titToolTip>' + this.title + '</td></tr>' + '<tr><td><font color=' + this.textColor + '>' + this.text + '</font></td></tr></table>';

        if (NN4) {
            t = '<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=' + this.borderColor + '>' + t + '</td></tr></table>';
            this.sobj.document.write(t);
            this.sobj.document.close();
        }
        else {
            this.sobj.border = '1px solid ' + this.borderColor;
            this.setOpacity();
            if (document.getElementById) document.getElementById('ToolTip').innerHTML = t;
            else document.all.ToolTip.innerHTML = t;
        }
        if (DOM) this.height = this.obj.offsetHeight;
        else if (IE) this.height = this.sobj.pixelHeight;
        else if (NN4) this.height = this.obj.clip.bottom;

        this.show();
    }

    this.init = function() {
        if (DOM) {
            this.obj = document.getElementById('ToolTip');
            this.sobj = this.obj.style;
        }
        else if (IE) {
            this.obj = document.all.ToolTip;
            this.sobj = this.obj.style;
        }
        else if (NN4) {
            this.obj = document.ToolTip;
            this.sobj = this.obj;
        }
    }

    this.show = function() {
        var ext = (document.layers ? '' : 'px');
        var left = mouseX;
        var top = mouseY;

        if (left + this.width + this.cursorDistance > winX) { left -= this.width + this.cursorDistance; }
        else { left += this.cursorDistance; }

        if (top + this.height + this.cursorDistance - scrTop > winY) { top -= this.height; }
        else { top += this.cursorDistance; }

        this.sobj.left = left + ext;
        this.sobj.top = top + ext;

        if (!this.active) {
            this.sobj.visibility = 'visible';
            this.active = true;
        }
    }

    this.hide = function() {
        if (this.sobj) this.sobj.visibility = 'hidden';
        this.active = false;
    }

    this.esconderCombos = function() {
        for (var x = 0; x < document.forms[0].elements.length; x++) {
            if (document.forms[0].elements[x].type.indexOf("select") > -1) {
                document.forms[0].elements[x].style.visibility = 'hidden';
            }
        }
    }

    this.mostrarCombos = function() {
        for (var x = 0; x < document.forms[0].elements.length; x++) {
            if (document.forms[0].elements[x].type.indexOf("select") > -1) {
                document.forms[0].elements[x].style.visibility = 'visible';
            }
        }
    }

    this.setOpacity = function() {
        this.sobj.filter = 'alpha(opacity=' + this.opacity + ')';
        this.sobj.mozOpacity = '.1';
        if (this.obj.filters) { this.obj.filters.alpha.opacity = this.opacity; }
        if (!document.all && this.sobj.setProperty) { this.sobj.setProperty('-moz-opacity', this.opacity / 100, ''); }
    }
}

var tooltip = mouseX = mouseY = winX = winY = scrTop = 0;

if (document.layers) {
    document.write('<layer id="ToolTip"></layer>');
    document.captureEvents(Event.MOUSEMOVE);
}
else {
    document.write('<div id="ToolTip" style="position:absolute; z-index:69"></div>');
}
document.onmousemove = getMouseXY;

function getMouseXY(e) {
    if (document.body && document.body.scrollTop >= 0) { scrTop = document.body.scrollTop; }
    else
    { if (window.pageYOffset >= 0) scrTop = window.pageYOffset; }

    if (IE) {
        if (event != null && document.body != null) {
            mouseX = event.clientX + document.body.scrollLeft;
            mouseY = event.clientY + document.body.scrollTop;
        }
    }
    else {
        mouseX = e.pageX;
        mouseY = e.pageY;
    }

    if (mouseX < 0) { mouseX = 0; }
    if (mouseY < 0) { mouseY = 0; }

    if (GK || NN4) {
        winX = window.innerWidth - 25;
        winY = window.innerHeight;
    }
    else if (DOM) {
        if (document.body != null) {
            winX = document.body.offsetWidth - 25;
            winY = document.body.offsetHeight;
        }
    }
    else {
        winX = screen.width - 25;
        winY = screen.height;
    }
    if (tooltip && tooltip.active) { tooltip.show(); }
}

function toolTip(title, text, width, opacity) {
    if (text) {
        tooltip = new TOOLTIP();
        tooltip.text = text;
        if (title) { tooltip.title = title; }
        if (width) { tooltip.width = width; }
        if (opacity) { tooltip.opacity = opacity; }
        tooltip.create();
    }
    else {
        if (tooltip) {
            tooltip.hide();
        }
    }
}

// PRKALVA ToolTip
// Modificação do tooltip original para atender a detalhes do WBCPublic
// Modificado por: prkalva 15/01/2009
function TOOLTIPPRK() {

    this.width = 400;
    this.bgColor = '#FFFFE1';
    this.textColor = '#000000';
    this.borderColor = '#CCCCCC';
    this.moreHeight = 10;
    this.text = '';
    this.height = 100;
    this.obj = 0;
    this.sobj = 0;
    this.active = false;

    this.init = function() {
        if (DOM) {
            this.obj = document.getElementById('ToolTipPRK');
            this.sobj = this.obj.style;
        } else {
            if (IE) {
                this.obj = document.all.ToolTip;
                this.sobj = this.obj.style;
            } else {
                if (NN4) {
                    this.obj = document.ToolTip;
                    this.sobj = this.obj;
                }
            }
        }
    }
    this.create = function() {
        if (!this.sobj) { this.init(); }

        var t = '<table onmouseout="toolTipPRKtimeDown();" border=0 cellspacing=0 cellpadding=3 width=' + this.width + ' bgcolor=' + this.bgColor + '>' + '<tr><td><div style="overflow: auto; width: ' + this.width + 'px;"><font color=' + this.textColor + '>' + this.text + '</font></div></td></tr></table>';

        if (NN4) {
            t = '<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=' + this.borderColor + '>' + t + '</td></tr></table>';
            this.sobj.document.write(t);
            this.sobj.document.close();
        }
        else {
            this.sobj.border = '1px solid ' + this.borderColor;

            if (document.getElementById) { document.getElementById('ToolTipPRK').innerHTML = t; }
            else { document.all.ToolTip.innerHTML = t; }
        }

        if (DOM) {
            this.height = this.obj.offsetHeight + this.moreHeight;
        }
        else {
            if (IE) {
                this.height = this.sobj.pixelHeight + this.moreHeight;
            } else {
                if (NN4) {
                    this.height = this.obj.clip.bottom + this.moreHeight;
                }
            }
        }

        var t = '<table onmouseout="toolTipPRKtimeDown();" border=0 cellspacing=0 cellpadding=3 width=' + this.width + ' bgcolor=' + this.bgColor + '>' + '<tr><td><div style="overflow: auto; width: ' + this.width + 'px; height: ' + this.height + 'px;"><font color=' + this.textColor + '>' + this.text + '</font></div></td></tr></table>';

        if (NN4) {
            t = '<table border=0 cellspacing=0 cellpadding=1><tr><td bgcolor=' + this.borderColor + '>' + t + '</td></tr></table>';
            this.sobj.document.write(t);
            this.sobj.document.close();
        }
        else {
            this.sobj.border = '1px solid ' + this.borderColor;

            if (document.getElementById) { document.getElementById('ToolTipPRK').innerHTML = t; }
            else { document.all.ToolTip.innerHTML = t; }
        }

        this.show();
    }
    this.show = function() {
        var ext = (document.layers ? '' : 'px');
        var left = mouseX;
        var top = mouseY;
        if (left + this.width > winX) {
            left -= this.width;
        }

        if (top + this.height - scrTop > winY) {
            top -= this.height;
        }

        this.sobj.left = (left - 20) + ext;
        this.sobj.top = (top - 20) + ext;

        if (!this.active) {
            this.sobj.visibility = 'visible';
            this.active = true;
        }
    }

    this.hide = function() {
        if (this.sobj) { this.sobj.visibility = 'hidden'; }
        this.active = false;
    }
}

var mousePrkX = mousePrkY = winPrkX = winPrkY = scrTopPrk = 0;
var prkToolTip = 0;
var mouseXant = mouseYant = 0;
var textMen = "";
var prkInter = 0;
var prkInter2 = 0;
var prkActive = false;
var prkActiveDown = false;
var prkToolTipShowActive = false;

if (document.layers) {
    document.write('<layer id="ToolTipPRK"></layer>');
}
else {
    document.write('<div id="ToolTipPRK" style="position:absolute; z-index:69"></div>');
}





function toolTipPublic(title, text, width, opacity) {
    if (text && prkActive != true) {
        mouseXant = mouseX;
        mouseYant = mouseY;
        textMen = text;
        prkInter = setInterval('toolTipPRKtime()', 1000);
        prkActive = true;
    } else {
        if (prkToolTipShowActive == false) {
            prkActive = false;
            clearInterval(prkInter);
            clearInterval(prkInter2);
        }
    }
}
function toolTipPRKtime() {
    if (prkActive == true) {
        prkToolTip = new TOOLTIPPRK();
        prkToolTip.text = textMen;
        prkToolTip.create();
        clearInterval(prkInter);
        prkToolTipShowActive = true;
    }
    prkActive = false;
}
function toolTipPRKtimeDown() {
    if (prkActiveDown != true) {
        prkInter2 = setInterval('toolTipPRKtimeDownOut()', 1000);
        prkActiveDown = true;
    }
}
function toolTipPRKtimeDownOut() {
    clearInterval(prkInter2);
    prkActiveDown = false;
    a = prkToolTip.sobj.left;
    b = prkToolTip.sobj.top;
    a = parseInt(a.replace('px', ''));
    b = parseInt(b.replace('px', ''));
    c = a + prkToolTip.width;
    d = b + +prkToolTip.height;

    mx = mouseX;
    my = mouseY;

    if ((mx > a && mx < c) && (my > b && my < d)) {
        return;
    }

    if (prkToolTip) {
        prkToolTip.hide();
        prkToolTipShowActive = false;
    }
}


function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {

    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function AtacharEvento(obj, evt, func) {
    var bw = new PTADetectorBrowser();
    if (bw.ie) {
        obj.attachEvent("on" + evt, func);
    }
    else {
        obj.AttachEvent(evt, func, false);
    }
}

String.prototype.Format = function(text) {
    if (arguments.length <= 1) {
        return text;
    }
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
}
