﻿function mostraAutores(valor, event) {
    var posmouse = mouseXandY(event);
    
    document.getElementById('layerAutores').style.left = posmouse[0]+'px';
    document.getElementById('layerAutores').style.top = posmouse[1] + 'px';
    document.getElementById('layerAutores').style.display = '';
    document.getElementById('layerAutores').innerHTML = "<br/><br/><br/><br/><span id='textoAutores'><b>Autores:</b> " + valor + "</span>";
    
}
function mouseXandY(e) {
    var x = 0, y = 0;
    e = e || window.event;
    if (e.pageX || e.pageY) {
        x = e.pageX;
        y = e.pageY;
    } else if (typeof (e.clientX) == 'number') {
        var dE = document.documentElement;
        x = e.clientX + document.body.scrollLeft + (dE ? dE.scrollLeft : 0);
        y = e.clientY + document.body.scrollTop + (dE ? dE.scrollTop : 0);
    }
    return [x, y];
}
function ValidaCadastro(gridTel, hdnRowTelCount, hdnPostTelAddRows, gridInst, hdnRowInstCount, hdnPostInstAddRows, Tipo, Nome, CPF, Sexo, DtNasc, Cep, Rua, Num, Bairro, Cidade, Estado, Prof, Cargo, NivEsc, ArAt) {
    var iNome = document.getElementById(Nome);
    var iCPF = document.getElementById(CPF);
    var iSexo = document.getElementById(Sexo);
    var iDtNasc = document.getElementById(DtNasc);
    var iCep = document.getElementById(Cep);
    var iRua = document.getElementById(Rua);
    var iNum = document.getElementById(Num);
    var iBairro = document.getElementById(Bairro);
    var iCidade = document.getElementById(Cidade);
    var iEstado = document.getElementById(Estado);
    var iProf = document.getElementById(Prof);
    var iCargo = document.getElementById(Cargo);
    var iNivEsc = document.getElementById(NivEsc);
    var iArAt = document.getElementById(ArAt);
    var igridInst = document.getElementById(gridInst);
    var igridTel = document.getElementById(gridTel);


    if (trim(iNome.value, ' ').length == 0 || trim(iNome.value, ' ').indexOf(' ') == -1) {
        alert('Favor preencher o nome e sobrenome');
        iNome.focus();
        return false;
    }
    else if (trim(iCPF.value, ' ').length == 0) {
        alert('Favor preencher o CPF');
        iCPF.focus();
        return false;
    }
    else if (!valida_CPF(iCPF)) {
        alert('Favor preencher um CPF válido');
        iCPF.focus();
        return false;
    }
    else if (iSexo.selectedIndex <= 0) {
        alert('Favor selecionar um sexo');
        iSexo.focus();
        return false;
    }
    else if (trim(iDtNasc.value, ' ').length == 0) {
        alert('Favor preencher a data de nascimento');
        iDtNasc.focus();
        return false;
    }
    else if (!validaData(trim(iDtNasc.value, ' '))) {
        alert('Favor preencher uma data de nascimento válida. Formato: dd/mm/aaaa');
        iDtNasc.focus();
        return false;
    }
    else if (igridTel.rows.length <= 1) {
        alert('Favor inserir um telefone');
        return false;
    }
    else if (trim(iCep.value, ' ').length == 0) {
        alert('Favor preencher o CEP');
        iCep.focus();
        return false;
    }
    else if (trim(iRua.value, ' ').length == 0 && iRua.disabled == false) {
        alert('Favor preencher o logradouro');
        iRua.focus();
        return false;
    }
    else if (trim(iNum.value, ' ').length == 0 && iNum.disabled == false) {
        alert('Favor preencher o número do logradouro');
        iNum.focus();
        return false;
    }
    else if (iNum.disabled == true) {
        alert('Favor realizar a pesquisa de endereço por CEP');
        iCep.focus();
        return false;
    }
    else if (trim(iBairro.value, ' ').length == 0 && iBairro.disabled == false) {
        alert('Favor preencher o bairro');
        iBairro.focus();
        return false;
    }
    else if (trim(iCidade.value, ' ').length == 0 && iCidade.disabled == false) {
        alert('Favor preencher a cidade');
        iCidade.focus();
        return false;
    }
    else if (iEstado.selectedIndex <= 0 && iEstado.disabled == false) {
        alert('Favor selecionar um estado');
        iEstado.focus();
        return false;
    }

    if (Tipo == 'AP') {
        if (igridInst.rows.length <= 1) {
            alert('Favor inserir uma instituição');
            return false;
        }
    }
    else if (Tipo == 'L') {

        if (iProf.selectedIndex <= 0) {
            alert('Favor selecionar a profissão');
            iProf.focus();
            return false;
        }
        else if (iCargo.selectedIndex <= 0) {
            alert('Favor selecionar o cargo');
            iCargo.focus();
            return false;
        }
        else if (iNivEsc.selectedIndex <= 0) {
            alert('Favor selecionar o nível de escolaridade');
            iNivEsc.focus();
            return false;
        }
        else if (iArAt.selectedIndex <= 0) {
            alert('Favor selecionar a área de atuação');
            iArAt.focus();
            return false;
        }
    }

    GuardaValores(gridTel, hdnRowTelCount, hdnPostTelAddRows, gridInst, hdnRowInstCount, hdnPostInstAddRows);
}
function validaData(valor) {
    var date = valor;
    var ardt = new Array;
    var ExpReg = new RegExp("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}");
    ardt = date.split("/");
    erro = false;
    if (date.search(ExpReg) == -1) {
        erro = true;
    }
    else if (((ardt[1] == 4) || (ardt[1] == 6) || (ardt[1] == 9) || (ardt[1] == 11)) && (ardt[0] > 30))
        erro = true;
    else if (ardt[1] == 2) {
        if ((ardt[0] > 28) && ((ardt[2] % 4) != 0))
            erro = true;
        if ((ardt[0] > 29) && ((ardt[2] % 4) == 0))
            erro = true;
    }
    if (erro)
        return false;
    else
        return true;
}
function AbreFechaInf(ID) {
    var ctrlID = document.getElementById(ID);
    
    if (ctrlID.style.display != 'block') {
        ctrlID.style.display = 'block';
    }
    else {
        ctrlID.style.display = 'none';
    }
}
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function startclock() {
    var thetime = new Date();

    var nhours = thetime.getHours();
    var nmins = thetime.getMinutes();
    var nsecn = thetime.getSeconds();
    var nday = thetime.getDay();
    var nmonth = thetime.getMonth();
    var ntoday = thetime.getDate();
    var nyear = thetime.getYear();
    var AorP = " ";

// Comentado para o caso de voltar o padrão de horário AM PM
//    if (nhours >= 12)
//        AorP = "P.M.";
//    else
//        AorP = "A.M.";

//    if (nhours >= 13)
//        nhours -= 12;

//    if (nhours == 0)
//        nhours = 12;

    if (nsecn < 10)
        nsecn = "0" + nsecn;

    if (nmins < 10)
        nmins = "0" + nmins;

    if (nday == 0)
        nday = "domingo";
    if (nday == 1)
        nday = "segunda-feira";
    if (nday == 2)
        nday = "terça-feira";
    if (nday == 3)
        nday = "quarta-feira";
    if (nday == 4)
        nday = "quinta-feira";
    if (nday == 5)
        nday = "sexta-feira";
    if (nday == 6)
        nday = "sábado";

    nmonth += 1;

    if (nyear <= 99)
        nyear = "19" + nyear;

    if ((nyear > 99) && (nyear < 2000))
        nyear += 1900;

    document.getElementById('ctl00_ctl00_MHeader1_lblDataAtual').innerHTML = pad(nhours, 2, '0', 1) + ":" + pad(nmins, 2, '0', 1) + ":" + pad(nsecn, 2, '0', 1) + " " + AorP + " " + nday + ", " + pad(ntoday, 2, '0', 1) + "/" + pad(nmonth, 2, '0', 1) + "/" + nyear;
    setTimeout('startclock()', 1000);
}
function pad(str, len, pad, dir) {

    var STR_PAD_LEFT = 1;
    var STR_PAD_RIGHT = 2;
    var STR_PAD_BOTH = 3;
    
    str = str.toString();
    
    if (typeof (len) == "undefined") { var len = 0; }
    if (typeof (pad) == "undefined") { var pad = ' '; }
    if (typeof (dir) == "undefined") { var dir = STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir) {

            case STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
                break;

            case STR_PAD_BOTH:
                var right = Math.ceil((padlen = len - str.length) / 2);
                var left = padlen - right;
                str = Array(left + 1).join(pad) + str + Array(right + 1).join(pad);
                break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
                break;
        } // switch
    }
    return str;
}

//Validação de CPF
function valida_CPF(args) {
    if (trim(args.value, ' ').replace(/\D/g, '').length == 11)
        s = trim(args.value, ' ').replace(/\D/g, '');
    else
        return false; 
    if (isNaN(s))
        return false;
    var i;
    var c = s.substr(0, 9);
    var dv = s.substr(9, 2);
    var d1 = 0;
    for (i = 0; i < 9; i++)
        d1 += c.charAt(i) * (10 - i);
    if (d1 == 0)
        return false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9)
        d1 = 0;
    if (dv.charAt(0) != d1)
        return false;
    d1 *= 2;

    for (i = 0; i < 9; i++)
        d1 += c.charAt(i) * (11 - i);
    d1 = 11 - (d1 % 11);

    if (d1 > 9)
        d1 = 0;
    if (dv.charAt(1) != d1)
        return false;
    return true;
}

//Validação de CNPJ
function valida_CNPJ(oSrc, args) {
    s = args.Value;
    if (isNaN(s))
        return args.IsValid = false;
    var i;
    var c = s.substr(0, 12);
    var dv = s.substr(12, 2);
    var d1 = 0;
    for (i = 0; i < 12; i++)
        d1 += c.charAt(11 - i) * (2 + (i % 8));
    if (d1 == 0)
        return args.IsValid = false;
    d1 = 11 - (d1 % 11);
    if (d1 > 9)
        d1 = 0;
    if (dv.charAt(0) != d1)
        return args.IsValid = false;
    d1 *= 2;
    for (i = 0; i < 12; i++)
        d1 += c.charAt(11 - i) * (2 + ((i + 1) % 8));
    d1 = 11 - (d1 % 11);
    if (d1 > 9)
        d1 = 0;
    if (dv.charAt(1) != d1)
        return args.IsValid = false;
    return args.IsValid = true;
}
function TogglePalestra(combo,tr1,tr2,tr3,tr4,tr5,r1,r2,r3,r4,r5) {
    var cmbAssunto = document.getElementById(combo);
    var trAutor = document.getElementById(tr1);
    var trContato = document.getElementById(tr2);
    var trDtEv = document.getElementById(tr3);
    var trTelEvento = document.getElementById(tr4);
    var trInst = document.getElementById(tr5);
    var rfvAutor = document.getElementById(r1);
    var rfvInst = document.getElementById(r2);
    var rfvTelEvento = document.getElementById(r3);
    var rfvContato = document.getElementById(r4);
    var rfvDataEvento = document.getElementById(r5);

    if (cmbAssunto != null && trAutor != null && trContato != null && trDtEv != null && trTelEvento != null && trInst != null) {
        if (cmbAssunto.options[cmbAssunto.selectedIndex].value == "5") {
            trContato.style.display = "";
            trAutor.style.display = "";
            trDtEv.style.display = "";
            trTelEvento.style.display = "";
            trInst.style.display = "";
            ValidatorEnable(rfvAutor, true);
            ValidatorEnable(rfvInst, true);
            ValidatorEnable(rfvTelEvento, true);
            ValidatorEnable(rfvContato, true);
            ValidatorEnable(rfvDataEvento, true);
        }
        else {
            trAutor.style.display = "none";
            trContato.style.display = "none";
            trDtEv.style.display = "none";
            trTelEvento.style.display = "none";
            trInst.style.display = "none";
            ValidatorEnable(rfvAutor, false);
            ValidatorEnable(rfvInst, false);
            ValidatorEnable(rfvTelEvento, false);
            ValidatorEnable(rfvContato, false);
            ValidatorEnable(rfvDataEvento, false);
        }
    }
}
function CleanAJAX(tbTelefone,tbInst,Campo) {
    var Telefone = document.getElementById(tbTelefone);
    var Instituicao = document.getElementById(tbInst);
    var CampoVal = document.getElementById(Campo);

    if (trim(CampoVal.value, ' ').length > 0) {

        if (Telefone != null) {
            for (var el = 0; el < Telefone.getElementsByTagName("input").length; el++) {
                var hdn = Telefone.getElementsByTagName("input")[el];
                if (hdn.type == 'hidden' && hdn.name.length > 0) {
                    hdn.name = '';
                }
            }
        }
        if (Instituicao != null) {
            for (var el = 0; el < Instituicao.getElementsByTagName("input").length; el++) {
                var hdn = Instituicao.getElementsByTagName("input")[el];
                if (hdn.type == 'hidden' && hdn.name.length > 0) {
                    hdn.name = '';
                }
            }
        }
    }
    else {
        alert('Favor preencher campo para pesquisa.');
        CampoVal.focus();
        return false;
    }
}
function AddTelGrid(grid, chkHeader, TipoTelefone, EndTelCodeArea, EndTel) {

    var ckHeader = document.getElementById(chkHeader);
    var TipoTel = document.getElementById(TipoTelefone);
    var DDD = document.getElementById(EndTelCodeArea);
    var Tel = document.getElementById(EndTel);
    var table = document.getElementById(grid);

    if (TipoTel != null) {
        if (TipoTel.selectedIndex > 0) {
        }
        else {
            alert('Favor selecionar um tipo de telefone.');
            TipoTel.focus();
            return;
        }
    }
    if (DDD != null) {
        if (trim(DDD.value, ' ').length > 0) {
        }
        else {
            alert('Favor preencher o DDD.');
            DDD.focus();
            return;
        }
    }
    if (Tel != null) {
        if (trim(Tel.value, ' ').length > 0) {
        }
        else {
            alert('Favor preencher o número de telefone.');
            Tel.focus();
            return;
        }
    }

    //Verifica duplicidade de telefones
    if (table.rows.length > 1) {
        for (var li = 1; li < table.rows.length; li++) {
            if ((trim(DDD.value, ' ') == (table.rows[li].cells[2].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim() != undefined ? trim(table.rows[li].cells[2].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim(), ' ') : '') || trim(DDD.value, ' ') == (table.rows[li].cells[2].outerText != undefined ? trim(table.rows[li].cells[2].outerText, ' ') : '')) && (trim(Tel.value, ' ') == (table.rows[li].cells[3].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim() != undefined ? trim(table.rows[li].cells[3].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim(), ' ') : '') || trim(Tel.value, ' ') == (table.rows[li].cells[3].outerText != undefined ? trim(table.rows[li].cells[3].outerText, ' ') : ''))) {
                alert('Telefone já existente.\n\rFavor preencher outro número de telefone.');
                return;
            }
        }
    }
    
    if ((moz) || (saf)) {

        var objTRow = table.insertRow(table.rows.length);

        var objTCell = objTRow.insertCell(0);
        var newCheckBox = document.createElement('input');
        newCheckBox.id = 'checkchild';
        newCheckBox.type = 'checkbox';
        newCheckBox.onclick = function() { CheckHeader(grid, chkHeader) };
        objTCell.appendChild(newCheckBox);
        ckHeader.disabled = false;
        ckHeader.checked = false;

        var CodTipo = document.createElement("input");
        CodTipo.type = 'hidden';
        CodTipo.id = 'IdTipoTel';
        CodTipo.value = TipoTel.options[TipoTel.selectedIndex].value;
        
        var objTCel2 = objTRow.insertCell(1);
        objTCel2.appendChild(CodTipo);
        objTCel2.appendChild(document.createTextNode(TipoTel.options[TipoTel.selectedIndex].text));

        var objTCel3 = objTRow.insertCell(2);
        objTCel3.appendChild(document.createTextNode(DDD.value));

        var objTCel4 = objTRow.insertCell(3);
        objTCel4.appendChild(document.createTextNode(Tel.value));
    }
    else if (ie) {

        var ckHeader = document.getElementById(chkHeader);

        var newRow = table.insertRow(-1);

        var newCel0 = newRow.insertCell(0);
        var newCheckBox = document.createElement('input');
        newCheckBox.id = 'checkchild';
        newCheckBox.type = 'checkbox';
        newCheckBox.onclick = function() { CheckHeader(grid, chkHeader) };
        newCel0.appendChild(newCheckBox);
        ckHeader.disabled = false;
        ckHeader.checked = false;

        var CodTipo = document.createElement('input');
        CodTipo.type = 'hidden';
        CodTipo.id = 'IdTipoTel';
        CodTipo.value = TipoTel.options[TipoTel.selectedIndex].value;

        var newCel1 = newRow.insertCell(1);
        newCel1.appendChild(CodTipo);
        newCel1.appendChild(document.createTextNode(TipoTel.options[TipoTel.selectedIndex].text));

        var newCel2 = newRow.insertCell(2);
        newCel2.appendChild(document.createTextNode(DDD.value));

        var newCel3 = newRow.insertCell(3);
        newCel3.appendChild(document.createTextNode(Tel.value));
    }
}
function AddInstGrid(grid, chkHeader, InstNome, InstValue, cmbCurso, chkDisc, cmbPeriodo, txtInstNova, txtTelInstNova,trInstCurso) {

    var ckHeader = document.getElementById(chkHeader);
    var Inst = document.getElementById(InstNome);
    var CodInst = document.getElementById(InstValue);
    var Curso = document.getElementById(cmbCurso);
    var Disc = document.getElementById(chkDisc);
    var Periodo = document.getElementById(cmbPeriodo);
    var InstNova = document.getElementById(txtInstNova);
    var TelInstNova = document.getElementById(txtTelInstNova);
    var InstCurso = document.getElementById(trInstCurso);
    var chkDiscCount = 0;
    var cntNovaInst = 0;
    var table = document.getElementById(grid);

    if (InstCurso.style.display == 'none') {
        alert('Favor realizar a pesquisa da instituição de interesse');
        return;
    }
    else if (InstCurso.style.display == 'block') {
        if (Inst != null) {
            if (trim(Inst.value, ' ').length > 0) {
                if (CodInst.value == '330653') {
                    if (!trim(InstNova.value, ' ').length > 0) {
                        alert('Para adicionar uma nova instituição é necessário o preenchimento do nome desta instituição');
                        InstNova.focus();
                        return;
                    }
                    if (!trim(TelInstNova.value, ' ').length > 0) {
                        alert('Para adicionar uma nova instituição é necessário o preenchimento do telefone desta instituição');
                        TelInstNova.focus();
                        return;
                    }
                }
            }
            else {
                alert('Para adicionar uma instituição é necessário o preenchimento do nome da instituição');
                Inst.focus();
                return;
            }
            if (Curso != null) {
                if (Curso.selectedIndex > 0) {
                }
                else {
                    alert('Para adicionar uma instituição é necessária a seleção de um curso');
                    Curso.focus();
                    return;
                }
            }
            if (Disc != null) {
                for (var el = 0; el < Disc.getElementsByTagName('input').length; el++) {
                    var chk = Disc.getElementsByTagName('input')[el];
                    
                    if (chk.type == 'checkbox' && chk.checked) {
                        chkDiscCount++;
                    }
                }
            }
            if (chkDiscCount <= 0) {
                alert('Para adicionar uma instituição é necessária a marcação de no mínimo uma disciplina');
                return;
            }
            else if (chkDiscCount > 3) {
                alert('Para adicionar uma instituição é necessária a marcação de no máximo três disciplinas');
                return;
            }
            if (Periodo != null) {
                if (Periodo.selectedIndex > 0) {
                }
                else {
                    alert('Para adicionar uma instituição é necessária a seleção de um período');
                    Periodo.focus();
                    return;
                }
            }
        }

        //Verifica duplicidade de instituições
        if (table.rows.length > 1) {
            for (var li = 1; li < table.rows.length; li++) {
                if ((trim(CodInst.value, ' ') == table.rows[li].cells[1].childNodes[0].value)) {

                    if ((trim(CodInst.value, ' ') == '330653') && (InstNova != null && trim(InstNova.value, ' ') != table.rows[li].cells[1].childNodes[4].nodeValue)) {
                        cntNovaInst++;
                    }
                    else {
                        alert('Instituição já existente.');
                        return;
                    }

                }
            }
        }
        if (cntNovaInst > 1) {
            alert('O limite máximo de cadastro de novas instituições é de duas instituições');
            return;
        }

        if ((moz) || (saf)) {

            var objTRow = table.insertRow(table.rows.length);

            var objTCell = objTRow.insertCell(0);
            var newCheckBox = document.createElement('input');
            newCheckBox.id = 'checkchild';
            newCheckBox.type = 'checkbox';
            newCheckBox.onclick = function() { CheckHeader(grid, chkHeader) };
            objTCell.appendChild(newCheckBox);
            ckHeader.disabled = false;
            ckHeader.checked = false;

            var IdInst = document.createElement('input');
            IdInst.type = 'hidden';
            IdInst.id = 'IdInst';
            IdInst.value = CodInst.value;

            var CodCurso = document.createElement('input');
            CodCurso.type = 'hidden';
            CodCurso.id = 'IdCursoInst';
            CodCurso.value = (IdInst.value == '330653' ? trim(Curso.options[Curso.selectedIndex].text, ' ') : Curso.options[Curso.selectedIndex].value);

            var CodDisc = document.createElement('input');
            CodDisc.type = 'hidden';
            CodDisc.id = 'IdDiscInst';

            for (var el = 0; el < Disc.getElementsByTagName("input").length; el++) {
                var chk = Disc.getElementsByTagName("input")[el];
                if (chk.type == 'checkbox' && chk.checked) {
                    CodDisc.value += trim(document.getElementById(chk.id + 'Value').value, ' ') + '**';
                }
            }

            var CodPeriodo = document.createElement('input');
            CodPeriodo.type = 'hidden';
            CodPeriodo.id = 'IdPeriodoInst';
            CodPeriodo.value = (IdInst.value == '330653' ? trim(Periodo.options[Periodo.selectedIndex].text, ' ') : Periodo.options[Periodo.selectedIndex].value);

            var TelInstOutras = document.createElement('input');
            TelInstOutras.type = 'hidden';
            TelInstOutras.id = 'TelInstNova';
            TelInstOutras.value = (IdInst.value == '330653' ? trim(TelInstNova.value, ' ') : '');

            var newCel1 = objTRow.insertCell(1);
            newCel1.appendChild(IdInst);
            newCel1.appendChild(CodCurso);
            newCel1.appendChild(CodDisc);
            newCel1.appendChild(CodPeriodo);
            newCel1.appendChild(TelInstOutras);

            newCel1.appendChild(document.createTextNode(IdInst.value == '330653' ? trim(InstNova.value, ' ') : trim(Inst.value, ' ')));
        }
        else if (ie) {

            var ckHeader = document.getElementById(chkHeader);

            var newRow = table.insertRow(-1);

            var newCel0 = newRow.insertCell(0);
            var newCheckBox = document.createElement('input');
            newCheckBox.id = 'checkchild';
            newCheckBox.type = 'checkbox';
            newCheckBox.onclick = function() { CheckHeader(grid, chkHeader) };
            newCel0.appendChild(newCheckBox);
            ckHeader.disabled = false;
            ckHeader.checked = false;

            var IdInst = document.createElement('input');
            IdInst.type = 'hidden';
            IdInst.id = 'IdInst';
            IdInst.value = CodInst.value;

            var CodCurso = document.createElement('input');
            CodCurso.type = 'hidden';
            CodCurso.id = 'IdCursoInst';
            CodCurso.value = (IdInst.value == '330653' ? trim(Curso.options[Curso.selectedIndex].text, ' ') : Curso.options[Curso.selectedIndex].value);

            var CodDisc = document.createElement('input');
            CodDisc.type = 'hidden';
            CodDisc.id = 'IdDiscInst';

            for (var el = 0; el < Disc.getElementsByTagName("input").length; el++) {
                var chk = Disc.getElementsByTagName("input")[el];
                if (chk.type == 'checkbox' && chk.checked) {
                    CodDisc.value += (IdInst.value == '330653' ? trim(document.getElementById(chk.id + 'Value').parentNode.childNodes[0].innerText, ' ') : document.getElementById(chk.id + 'Value').value) + '**';
                }
            }

            var CodPeriodo = document.createElement('input');
            CodPeriodo.type = 'hidden';
            CodPeriodo.id = 'IdPeriodoInst';
            CodPeriodo.value = (IdInst.value == '330653' ? trim(Periodo.options[Periodo.selectedIndex].text, ' ') : Periodo.options[Periodo.selectedIndex].value);

            var TelInstOutras = document.createElement('input');
            TelInstOutras.type = 'hidden';
            TelInstOutras.id = 'TelInstNova';
            TelInstOutras.value = (IdInst.value == '330653' ? trim(TelInstNova.value, ' ') : '');

            var newCel1 = newRow.insertCell(1);
            newCel1.appendChild(IdInst);
            newCel1.appendChild(CodCurso);
            newCel1.appendChild(CodDisc);
            newCel1.appendChild(CodPeriodo);
            newCel1.appendChild(TelInstOutras);

            newCel1.appendChild(document.createTextNode(IdInst.value == '330653' ? trim(InstNova.value, ' ') : trim(Inst.value, ' ')));
        }
    }
}
function CheckHeader(grid, chkHeader) {
    var Parent = document.getElementById(grid);
    var items = Parent.getElementsByTagName('input');
    var contItems = 0;
    var Chk = document.getElementById(chkHeader);
    var cont = 0;

    for (i = 1; i < items.length; i++)
        if (items[i].id != Chk.id && items[i].type == "checkbox")
            contItems++;
    
    for (i = 0; i < items.length; i++) {
        if (items[i].id != Chk.id && items[i].type == "checkbox") {
            if (items[i].checked)
                cont++;
            else
                if (Chk.checked)
                Chk.checked = false;
        }

        if (cont == contItems)
            Chk.checked = true;
    }
    return true;
}
function CheckTodos(grid, Chk) {
    var Parent = document.getElementById(grid);
    var IsChecked = Chk.checked;
    var items = Parent.getElementsByTagName('input');
    for (i = 0; i < items.length; i++) {
        if (items[i].id != Chk.id && items[i].type == "checkbox") {
            if (items[i].checked != IsChecked)
                items[i].checked = IsChecked;
        }
    }
}
function RemGrid(grid, chkHeader) {
    try {
        var table = document.getElementById(grid);
        var rowCount = table.rows.length;
        var ckHeader = document.getElementById(chkHeader);

        for (var i = 1; i < rowCount; i++) {
            var row = table.rows[i];

            var chkbox = row.getElementsByTagName("input")[0];
            if (null != chkbox && true == chkbox.checked && chkbox.id != ckHeader.id) {
                table.deleteRow(i);
                rowCount--;
                i--;
            }
            if (table.rows.length == 1) {
                ckHeader.checked = false;
                ckHeader.disabled = true;
            }

        }
    } catch (e) {
        alert(e);
    }
}
function GuardaValores(gridTel, hdnRowTelCount, hdnPostTelAddRows, gridInst, hdnRowInstCount, hdnPostInstAddRows) {
    GuardaValTel(gridTel, hdnRowTelCount, hdnPostTelAddRows);
    if (gridInst != '')
        GuardaValInst(gridInst, hdnRowInstCount, hdnPostInstAddRows);
}
function GuardaValInst(gridInst, hdnRowInstCount, hdnPostInstAddRows) {
    var rowCount = 0;
    var strExpression = '';
    var table = document.getElementById(gridInst);
    var valor0 = '';
    var valor1 = '';
    var valor2 = '';
    var valor3 = '';
    var valor4 = '';
    var valor5 = '';

    var originalRowCount = parseInt(document.getElementById(hdnRowInstCount).value);

    for (rowCount = 1; rowCount < table.rows.length; rowCount++) {
        var str = '';
        var operator = '';
        var tr = table.rows[rowCount];

        if ((moz) || (saf)) {

            //Codigo
            if (tr.cells[1].childNodes[0].id != undefined && tr.cells[1].childNodes[0].id == 'IdInst')
                valor0 = tr.cells[1].childNodes[0].value;
            else
                valor0 = tr.cells[1].childNodes[1].value;

            //Nome
            if (tr.cells[1].childNodes[5].nodeValue != undefined)
                valor1 = tr.cells[1].childNodes[5].nodeValue;
            else
                valor1 = tr.cells[1].childNodes[2].nodeValue.trim();

            //Cod Curso
            if (tr.cells[1].childNodes[1].id != undefined && tr.cells[1].childNodes[1].id == 'IdCursoInst')
                valor2 = tr.cells[1].childNodes[1].value;
            else
                valor2 = tr.cells[1].childNodes[3].value;

            //Cod Disc
            if (tr.cells[1].childNodes[2].id != undefined && tr.cells[1].childNodes[2].id == 'IdDiscInst')
                valor3 = tr.cells[1].childNodes[2].value;
            else
                valor3 = tr.cells[1].childNodes[5].value;

            //Cod Per
            if (tr.cells[1].childNodes[3].id != undefined && tr.cells[1].childNodes[3].id == 'IdPeriodoInst')
                valor4 = tr.cells[1].childNodes[3].value;
            else
                valor4 = tr.cells[1].childNodes[7].value;

            if (tr.cells[1].childNodes[4].value != undefined && tr.cells[1].childNodes[4].id == 'TelInstNova')
                valor5 = tr.cells[1].childNodes[4].value;
            


        } else if (ie) {


            //Codigo Instituicao
            valor0 = tr.cells[1].childNodes[0].value;

            //Nome da Instituição
            if (tr.cells[1].childNodes[1].nodeValue != undefined)
                valor1 = tr.cells[1].childNodes[1].nodeValue;
            else if (valor0 == '330653')
                valor1 = tr.cells[1].lastChild.nodeValue;
            else if (tr.cells[1].childNodes[4].nodeValue != null)
                valor1 = tr.cells[1].childNodes[4].nodeValue;
            else
                valor1 = tr.cells[1].lastChild.nodeValue;

            //Codigo curso
            if (tr.cells[1].childNodes[2] != undefined && tr.cells[1].childNodes[2].id != 'IdDiscInst')
                valor2 = tr.cells[1].childNodes[2].value;
            else
                valor2 = tr.cells[1].childNodes[1].value;

            //Codigo Disciplina
            if (tr.cells[1].childNodes[4].value != undefined && tr.cells[1].childNodes[4].id != 'TelInstNova')
                valor3 = tr.cells[1].childNodes[4].value;
            else
                valor3 = tr.cells[1].childNodes[2].value;

            //Codigo Periodo
            if (tr.cells[1].childNodes[6] != undefined && tr.cells[1].childNodes[6].value != undefined)
                valor4 = tr.cells[1].childNodes[6].value;
            else
                valor4 = tr.cells[1].childNodes[3].value;
           
            if (tr.cells[1].childNodes[4] != null && tr.cells[1].childNodes[4].id == 'TelInstNova')
                valor5 = tr.cells[1].childNodes[4].value;
        }

        str = str + (valor0.length > 0 ? valor0 : '-') + '%%';
        str = str + (valor1 != undefined && valor1.length > 0 ? valor1 : '-') + '%%';
        str = str + (valor2 != undefined && valor2.length > 0 ? valor2 : '-') + '%%';
        str = str + (valor3 != undefined && valor3.length > 0 ? valor3 : '-') + '%%';
        str = str + (valor4 != undefined && valor4.length > 0 ? valor4 : '-') + '%%';
        str = str + (valor5 != undefined && valor5.length > 0 ? valor5 : '-') + '%%';

        strExpression = strExpression + str;
        if (rowCount < table.rows.length - 1)
            strExpression = strExpression + '~~';
    }
    
    document.getElementById(hdnPostInstAddRows).value = strExpression;
}
function GuardaValTel(gridTel, hdnRowTelCount, hdnPostTelAddRows) {
    var rowCount = 0;
    var strExpression = '';
    var table = document.getElementById(gridTel);
    var valor1 = '';
    var valor2 = '';
    var valor3 = '';

    var originalRowCount = parseInt(document.getElementById(hdnRowTelCount).value);
    
    for (rowCount = 1; rowCount < table.rows.length; rowCount++) {
        var str = '';
        var operator = '';
        valor1 = '';
        valor2 = '';
        valor3 = '';
        var tr = table.rows[rowCount];

        if ((moz) || (saf)) {

            if (tr.cells[1].childNodes[0].id != undefined && tr.cells[1].childNodes[0].id == 'IdTipoTel')
                valor1 = tr.cells[1].childNodes[0].value;
            else
                valor1 = tr.cells[1].childNodes[1].value;

                valor2 = tr.cells[2].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim();

                valor3 = tr.cells[3].childNodes[0].nodeValue.replace('\n', '').replace('\t', '').trim();

        }
        else if (ie) {
            valor1 = tr.cells[1].childNodes[0].value;
            valor2 = tr.cells[2].childNodes[0].nodeValue;
            valor3 = tr.cells[3].childNodes[0].nodeValue;
        }

        str = str + trim(valor1, ' ') + '%%';
        str = str + trim(valor2, ' ') + '%%';
        str = str + trim(valor3, ' ') + '%%';
        
        strExpression = strExpression + str;
        if (rowCount < table.rows.length -1)
            strExpression = strExpression + '~~';
    }
    document.getElementById(hdnPostTelAddRows).value = strExpression;
}
function execmascara() {
    v_obj.value = v_fun(v_obj.value);
}
function Integer(v) {
    return v.replace(/\D/g, "")
}
function mascara(o, f) {
    v_obj = o;
    v_fun = f;
    setTimeout("execmascara()", 1);
}
function data(v) {
    v = v.replace(/\D/g, "")
    v = v.replace(/(\d{2})(\d)/, "$1/$2")
    v = v.replace(/(\d{2})(\d)/, "$1/$2")
    return v
}
function tel(v) {
    v = v.replace(/\D/g, "")
    v = v.replace(/(\d{2})(\d)/, "($1) $2")
    v = v.replace(/(\d{4})(\d)/, "$1-$2")
    return v
}
function cpf(v) {
    v = v.replace(/\D/g, "");                     
    v = v.replace(/(\d{3})(\d)/, "$1.$2");        
    v = v.replace(/(\d{3})(\d)/, "$1.$2");        
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2"); 
    return v;
}
function SetUniqueRadioButton(nameregex, current) {
    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }
    current.checked = true;
}
function toggle(div_id) {
    var el = document.getElementById(div_id);
    el.style.display = 'block'; 
}
function blanket_size(popUpDivVar, blank_id) {
    if (typeof window.innerWidth != 'undefined') {
        viewportheight = window.innerHeight;
    } else {
        viewportheight = document.documentElement.clientHeight;
    }
    if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
        blanket_height = viewportheight;
    } else {
        if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
            blanket_height = document.body.parentNode.clientHeight;
        } else {
            blanket_height = document.body.parentNode.scrollHeight;
        }
    }
    var blanket = document.getElementById(blank_id);
    blanket.style.height = blanket_height + 'px';
//    var popUpDiv = document.getElementById(popUpDivVar);
//    popUpDiv_height = (blanket_height - 600); //150 is half popup's height
//    popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerHeight;
    } else {
        viewportwidth = document.documentElement.clientHeight;
    }
    if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
        window_width = viewportwidth;
    } else {
        if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
            window_width = document.body.parentNode.clientWidth;
        } else {
            window_width = document.body.parentNode.scrollWidth;
        }
    }
//    var popUpDiv = document.getElementById(popUpDivVar);
//    //window_width = window_width / 2 - 150; //150 is half popup's width
//    popUpDiv.style.left = window_width + 'px';

}
function processKey(e,element,act) {
    if (null == e)
        e = window.event;
    if (e.keyCode == 13) {
        if (act == 'submit')
            document.getElementById(element).click();
        else if (act == 'focus')
            document.getElementById(element).focus();

        return false;
    }
}
function popup(windowname,blank_id) {
    blanket_size(windowname, blank_id);
    toggle(blank_id);
    toggle(windowname);
}
function PopulaComboCapAte(cmbCapDe, cmbCapAte) {

    var cmbDe = document.getElementById(cmbCapDe);
    var cmbAte = document.getElementById(cmbCapAte);
    var cont = 0;

    cmbAte.options.length = 0;

    for (var i = cmbDe.selectedIndex; i < cmbDe.length; i++) {
        cmbAte.options[cont] = new Option(cmbDe[i].value, cmbDe[i].value, false, false);
        cont++;
    }

}

function ValidaExibeFast(Baixa, Media, Alta, Dissertativas,MaxBaixa,MaxMedia,MaxAlta,MaxDiss) {
    var txbBaixa = document.getElementById(Baixa);
    var txbMedia = document.getElementById(Media);
    var txbAlta = document.getElementById(Alta);
    var txbDissertativas = document.getElementById(Dissertativas);
    
    if (txbBaixa.value.length == 0) {
        alert('Favor preencher a quantidade de questões do grau de dificuldade baixo para exibição.');
        txbBaixa.focus();
        return false;
    }
    if (txbMedia.value.length == 0) {
        alert('Favor preencher a quantidade de questões do grau de dificuldade médio para exibição.');
        txbMedia.focus();
        return false;
    }
    if (txbAlta.value.length == 0) {
        alert('Favor preencher a quantidade de questões do grau de dificuldade alto para exibição.');
        txbAlta.focus();
        return false;
    }
    if (txbDissertativas.value.length == 0) {
        alert('Favor preencher a quantidade de questões dissertativas para exibição.');
        txbDissertativas.focus();
        return false;
    }

    if (parseInt(txbBaixa.value) > parseInt(MaxBaixa)) {
        alert('Quantidade de questões do grau de dificuldade baixo excedida.');
        txbBaixa.focus();
        return false;
    }
    if (parseInt(txbMedia.value) > parseInt(MaxMedia)) {
        alert('Quantidade de questões do grau de dificuldade médio excedida.');
        txbMedia.focus();
        return false;
    }
    if (parseInt(txbAlta.value) > parseInt(MaxAlta)) {
        alert('Quantidade de questões do grau de dificuldade alto excedida.');
        txbAlta.focus();
        return false;
    }
    if (parseInt(txbDissertativas.value) > parseInt(MaxDiss)) {
        alert('Quantidade de questões dissertativas excedida.');
        txbDissertativas.focus();
        return false;
    }       
}


//initialization, browser, os detection
var d, dom, nu = '', brow = '', ie, ie4, ie5, ie5x, ie6, ie7;
var ns4, moz, moz_rv_sub, release_date = '', moz_brow, moz_brow_nu = '', moz_brow_nu_sub = '', rv_full = '';
var mac, win, old, lin, ie5mac, ie5xwin, konq, saf, op, op4, op5, op6, op7;

d = document;
n = navigator;
nav = n.appVersion;
nan = n.appName;
nua = n.userAgent;
old = (nav.substring(0, 1) < 4);
mac = (nav.indexOf('Mac') != -1);
win = (((nav.indexOf('Win') != -1) || (nav.indexOf('NT') != -1)) && !mac) ? true : false;
lin = (nua.indexOf('Linux') != -1);
// begin primary dom/ns4 test
// this is the most important test on the page
if (!document.layers) {
    dom = (d.getElementById) ? d.getElementById : false;
}
else {
    dom = false;
    ns4 = true; // only netscape 4 supports document layers
}
// end main dom/ns4 test

op = (nua.indexOf('Opera') != -1);
saf = (nua.indexOf('Safari') != -1);
konq = (!saf && (nua.indexOf('Konqueror') != -1)) ? true : false;
moz = ((!saf && !konq) && (nua.indexOf('Gecko') != -1)) ? true : false;
ie = ((nua.indexOf('MSIE') != -1) && !op);
if (op) {
    str_pos = nua.indexOf('Opera');
    nu = nua.substr((str_pos + 6), 4);
    brow = 'Opera';
}
else if (saf) {
    str_pos = nua.indexOf('Safari');
    nu = nua.substr((str_pos + 7), 5);
    brow = 'Safari';
}
else if (konq) {
    str_pos = nua.indexOf('Konqueror');
    nu = nua.substr((str_pos + 10), 3);
    brow = 'Konqueror';
}
// this part is complicated a bit, don't mess with it unless you understand regular expressions
// note, for most comparisons that are practical, compare the 3 digit rv nubmer, that is the output
// placed into 'nu'.
else if (moz) {
    // regular expression pattern that will be used to extract main version/rv numbers
    pattern = /[(); \n]/;
    // moz type array, add to this if you need to
    moz_types = new Array('Firebird', 'Phoenix', 'Firefox', 'Iceweasel', 'Galeon', 'K-Meleon', 'Camino', 'Epiphany', 'Netscape6', 'Netscape', 'MultiZilla', 'Gecko Debian', 'rv');
    rv_pos = nua.indexOf('rv'); // find 'rv' position in nua string
    rv_full = nua.substr(rv_pos + 3, 6); // cut out maximum size it can be, eg: 1.8a2, 1.0.0 etc
    // search for occurance of any of characters in pattern, if found get position of that character
    rv_slice = (rv_full.search(pattern) != -1) ? rv_full.search(pattern) : '';
    //check to make sure there was a result, if not do  nothing
    // otherwise slice out the part that you want if there is a slice position
    (rv_slice) ? rv_full = rv_full.substr(0, rv_slice) : '';
    // this is the working id number, 3 digits, you'd use this for 
    // number comparison, like if nu >= 1.3 do something
    nu = rv_full.substr(0, 3);
    for (i = 0; i < moz_types.length; i++) {
        if (nua.indexOf(moz_types[i]) != -1) {
            moz_brow = moz_types[i];
            break;
        }
    }
    if (moz_brow)// if it was found in the array
    {
        str_pos = nua.indexOf(moz_brow); // extract string position
        moz_brow_nu = nua.substr((str_pos + moz_brow.length + 1), 3); // slice out working number, 3 digit
        // if you got it, use it, else use nu
        moz_brow_nu = (isNaN(moz_brow_nu)) ? moz_brow_nu = nu : moz_brow_nu;
        moz_brow_nu_sub = nua.substr((str_pos + moz_brow.length + 1), 8);
        // this makes sure that it's only the id number
        sub_nu_slice = (moz_brow_nu_sub.search(pattern) != -1) ? moz_brow_nu_sub.search(pattern) : '';
        //check to make sure there was a result, if not do  nothing
        (sub_nu_slice) ? moz_brow_nu_sub = moz_brow_nu_sub.substr(0, sub_nu_slice) : '';
    }
    if (moz_brow == 'Netscape6') {
        moz_brow = 'Netscape';
    }
    else if (moz_brow == 'rv' || moz_brow == '')// default value if no other gecko name fit
    {
        moz_brow = 'Mozilla';
    }
    if (!moz_brow_nu)// use rv number if nothing else is available
    {
        moz_brow_nu = nu;
        moz_brow_nu_sub = nu;
    }
    if (n.productSub) {
        release_date = n.productSub;
    }
}
else if (ie) {
    str_pos = nua.indexOf('MSIE');
    nu = nua.substr((str_pos + 5), 3);
    brow = 'Microsoft Internet Explorer';
}
// default to navigator app name
else {
    brow = nan;
}
op5 = (op && (nu.substring(0, 1) == 5));
op6 = (op && (nu.substring(0, 1) == 6));
op7 = (op && (nu.substring(0, 1) == 7));
op8 = (op && (nu.substring(0, 1) == 8));
op9 = (op && (nu.substring(0, 1) == 9));
ie4 = (ie && !dom);
ie5 = (ie && (nu.substring(0, 1) == 5));
ie6 = (ie && (nu.substring(0, 1) == 6));
ie7 = (ie && (nu.substring(0, 1) == 7));
// default to get number from navigator app version.
if (!nu) {
    nu = nav.substring(0, 1);
}
/*ie5x tests only for functionavlity. dom or ie5x would be default settings. 
Opera will register true in this test if set to identify as IE 5*/
ie5x = (d.all && dom);
ie5mac = (mac && ie5);
ie5xwin = (win && ie5x);    
