// Funções para alterar a primeira letra de nomes próprios para maiúscula
function inputToNomeProprio(campo) {
    campo.value = toNomeProprio(campo.value);
}
function inputToMaiuscula(campo) {
    campo.value = campo.value.toUpperCase();
}
function inputToMinuscula(campo) {
    campo.value = campo.value.toLowerCase();
}
function inputToZeros(campo,tam) {
    if (!isEmpty(campo.value)) {
         campo.value = strZero(campo.value,tam);
    }
}
function inputToDir(campo,tam) {
    campo.value = padL(campo.value," ",tam);
}
function inputGetNumbers(campo) {
    return getNumbers(campo.value);
}
function inputToNumbers(campo) {
    campo.value = getNumbers(campo.value);
}
function removeCR(str) {
    var rtno="";
    for (var n = 0; n < str.length; n++) {
        if (str.charAt(n) == "\n") {
            rtno+="\\n";
        } else {
            rtno+=str.charAt(n);
        }
    }
}
function trocaImg(doc,matrizDocID, matrizObjNome) {
    for (var n=0; n < matrizDocID.length; n++) {
        doc.images[matrizDocID[n]].src = eval(matrizObjNome[n] + ".src");
    }
}
function zeraSel(sel) {
    for (;sel.length > 0;) {
        sel.options[sel.length -1] = null;
    }
}
function setSel(sel,value) {
    for (var n = 0; n < sel.options.length; n++) {
        if (sel.options[n].value == value) {
            sel.selectedIndex = n;
            break;
        }
    }
}
function setRadio(radio,value) {
    for (var n = 0; n < radio.length; n ++) {
        if (radio[n].value == value) {
            radio[n].checked = true;
        } else {
            radio[n].checked = false;
        }
    }
}

function unSel(sel) {
    for (var n = 0; n != sel.length; n++) {
         sel.options[n].selected = false;
    }
}
function selValue(sel) {
    return sel.options[sel.selectedIndex].value;
}
function radioValue(radio) {
    var value = null;
    for (var n = 0; n < radio.length; n ++) {
        if (radio[n].checked) {
            value = radio[n].value;
        }
    }
    return value;
}
function toNomeProprio(nome) {
    var nomeProprio = "";
    var priChar = true;
    var ch = "";
    for(var n=0; n < nome.length; n++) {
        ch = nome.charAt(n);
        if ((ch == ' ') || (ch == '.') || (ch == '/')) {
            priChar=true;
        } else {
           if (priChar) {
               if (betweenCh(ch,'a','z')) {
                  ch = ch.toUpperCase();
               }
               priChar=false;
           } else {
               if (betweenCh(ch,'A','Z')) {
                   ch = ch.toLowerCase();
               } else {
                   acent = "ÇÁÉÍÓÚÃÕÂÊÔÜÖ";
                   if (acent.indexOf(ch) > -1) {
                       ch = ch.toLowerCase();
                   }
               }
           }
           if (ch == "&") {
              ch = "e";
           }
        }
        nomeProprio += ch;
    }
    nomeProprio = parseTemplateArray(nomeProprio,[" Da "," Das "," De "," Do "," Dos "," E "],[" da "," das "," de "," do "," dos "," e "]);
    return nomeProprio;
}

function betweenCh(ch,chI,chF) {
    if ((ch >= chI) && (ch <= chF)) {
        return true;
    } else {
        return false;
    }
}

function isNumber(s) {
    var rtno = !isEmpty(s);
    for (var n = 0; n != s.length; n++) {
        if (!betweenCh(s.charAt(n),'0','9')) {
            rtno = false;
            break;
        }
    }
    return rtno;
}
function getNumbers(s) {
    var rtno = "";
    for (var n = 0; n < s.length; n++) {
        if (betweenCh(s.charAt(n),'0','9')) {
            rtno+=s.charAt(n);
        }
    }
    return rtno;
}
function isEmpty(s) {
    return ((s == null) || (s.length == 0) || (s == replicate(" ",s.length)));
}

function replicate(ch,num) {
    var rtno = "";
    for (var n = 0; n < num; n++) {
        rtno+=ch;
    }
    return rtno;
}
function padL(str,ch,num) {
    return rtno = replicate(ch,num-str.length)+str;
}
function strZero(str,num) {
    return padL(str,"0",num);
}
function inArray(str,array) {
    var rtno = false;
    for (var n=0; n < array.length; n++) {
        if (str == array[n]) {
            rtno = true;
            break;
        }
    }
    return rtno;
}
function indexOfArray(str,array) {
    var rtno = -1;
    for (var n=0; n < array.length; n++) {
        if (str.indexOf(array[n]) > -1) {
            rtno = n;
            break;
        }
    }
    return rtno;
}
function parseTemplate(templ,tag,str) {
    sub1 = templ.substring(0,templ.indexOf(tag));
    sub2 = templ.substring(templ.indexOf(tag)+tag.length,templ.length);
    return sub1+str+sub2;
}

function parseTemplateArray(templ,tags,strs) {
    var rtno = templ;
    for (var n = 0; n < tags.length; n++) {
        if (templ.indexOf(tags[n]) > -1) {
            rtno = parseTemplate(rtno,tags[n],strs[n]);
        }
    }
    return rtno;
}

// Funcao para selecionar os dados do campo que recebe o foco;
function autoSel(obj) {
    obj.select();
}

//Determinar se uma string eh de consulta ou nao
function isSearchString(s) {
    if ((s.indexOf('.') == 0) && (s.indexOf('..') > 1)) {
        return true;
    } else {
        return false;
    }
}

// Funcoes de Formatacao
// Funções de Data
function validaData(dia,mes,ano) {
    var rtno = "0";
    dia += "";
    mes += "";
    ano += "";
    if ((!isNumber(dia)) | (!((dia >= 1) && (dia <= maxDia(mes,ano))))) {
        rtno = 1;
    } else if ((!isNumber(mes)) | (!((mes >= 1) && (mes <= 12)))) {
        rtno = 2;
    } else if ((!isNumber(ano)) | (ano.length < 2)) {
        rtno = 3;
    }
    return rtno;
}
function maxDia(mes,ano) {
    var dias = [31,28,31,30,31,30,31,31,30,31,30,31];
    if (mes != 2) {
        return dias[mes - 1];
    } else {
        if (leapYear(ano)) {
            return 29;
        } else {
            return 28;
        }
    }
}
function leapYear(ano) {
    if ((ano % 100) == 0) {
        if ((ano % 400) == 0) {
            return true;
        }
    } else {
        if ((ano % 4) == 0) {
            return true;
        }
    }
    return false;
}
function fmtData(data) {
    var sData = "";
    if (data) {
        var mes = data.getMonth() + 1;
        var dia = data.getDate();
        var ano = data.getYear();
        if (ano < 2000) {        // correçao para browsers que retornam 100 no ano 2000
            ano = 1900 + ano;
        }
        if (mes < 10) {
           mes = "0" + mes;
        }
        if (dia < 10) {
           dia = "0" + dia;
        }
        sData = dia+"/"+mes+"/"+ano;
    }
    return sData;
}
function fmtHora(hora) {
    var h = hora.getHours();
    var m = hora.getMinutes();
    if (h < 10) {
        h = "0" + h;
    }
    if (m < 10) {
        m = "0" + m;
    }
    var sHora = h+":"+m;
    return sHora;
}
function dataSql(ano,mes,dia,hor,min,seg,mil) {
    if (ano.length < 4) {
        if (ano < 90) {
            ano = 2000 + ano;
        } else {
            ano = 1900 + ano;
        }
    }
    if (mes.length < 2) {
        mes = "0" + mes;
    }
    if (dia.length < 2) {
        dia = "0" + dia;
    }
    if (hor.length < 2) {
        hor = "0" + hor;
    }
    if (min.length < 2) {
        min = "0" + min;
    }
    return ano+"-"+mes+"-"+dia+" "+hor+":"+min+":"+seg+"."+mil;
}
function dtoh(data,nch) {
    if (!nch) {
        nch = 3;
    }
    var dia = (data.getDate() - 1) * 24;
    var hor = data.getHours() + dia;
    var min = data.getMinutes();
    return top.padL(hor+""," ",nch)+top.strZero(min+"",2);
}
function convStrData(data,fmt,fmtRtno) {
    rtno = fmtRtno;
    POS = 0;
    SIZE = 1;
    diaLay = getLayoutStr("D",fmt);
    mesLay = getLayoutStr("M",fmt);
    anoLay = getLayoutStr("A",fmt);
    dia = null;
    mes = null;
    ano = null;
    if (anoLay[POS] > -1) {
        ano = data.substr(anoLay[POS],anoLay[SIZE]);
    }
    if (mesLay[POS] > -1) {
        mes = data.substr(mesLay[POS],mesLay[SIZE]);
    }
    if (diaLay[POS] > -1) {
        dia = data.substr(diaLay[POS],diaLay[SIZE]);
    }
    // Retorno
    rtnDiaLay = getLayoutStr("D",fmtRtno);
    rtnMesLay = getLayoutStr("M",fmtRtno);
    rtnAnoLay = getLayoutStr("A",fmtRtno);
    if ((rtnAnoLay[POS]) > -1) {
        tagAno = replicate("A",rtnAnoLay[SIZE]);
        if (rtnAnoLay[SIZE] == 4) {
            if (ano.length != 4) {
                if (ano > 30) {
                    ano = "19"+ano;
                } else {
                    ano = "20"+ano;
                }
            }
        } else {
            ano = ano.substr(ano.length-rtnAnoLay[SIZE],rtnAnoLay[SIZE]);
        }
        rtno = parseTemplate(rtno,tagAno,ano);
    }
    if (rtnMesLay[POS] > -1) {
        rtno = parseTemplate(rtno,"MM",mes);
    }
    if (rtnDiaLay[POS] > -1) {
        rtno = parseTemplate(rtno,"DD",dia);
    }
    return rtno;
}
function dataToStr(data,fmtRtno) {
    rtno = fmtRtno;
    POS = 0;
    SIZE = 1;
    dia = null;
    mes = null;
    ano = null;
    ano = data.getYear();
    mes = data.getMonth() + 1;
    dia = data.getDate();
    if (ano < 2000) {
        ano = 1900 + ano;
    }
    ano = ano + "";
    if (mes < 10) {
        mes = "0" + mes;
    }
    if (dia < 10) {
        dia = "0" + dia;
    }
    // Retorno
    rtnDiaLay = getLayoutStr("D",fmtRtno);
    rtnMesLay = getLayoutStr("M",fmtRtno);
    rtnAnoLay = getLayoutStr("A",fmtRtno);
    if ((rtnAnoLay[POS]) > -1) {
        tagAno = replicate("A",rtnAnoLay[SIZE]);
        if (rtnAnoLay[SIZE] == 4) {
            if (ano.length != 4) {
                if (ano > 30) {
                    ano = "19"+ano;
                } else {
                    ano = "20"+ano;
                }
            }
        } else {
            ano = ano.substr(ano.length-rtnAnoLay[SIZE],rtnAnoLay[SIZE]);
        }
        rtno = parseTemplate(rtno,tagAno,ano);
    }
    if (rtnMesLay[POS] > -1) {
        rtno = parseTemplate(rtno,"MM",mes);
    }
    if (rtnDiaLay[POS] > -1) {
        rtno = parseTemplate(rtno,"DD",dia);
    }
    return rtno;
}
function getLayoutStr(tag,str) {
    pos = str.indexOf(tag);
    size = (str.lastIndexOf(tag) - pos) + 1;
    return new Array(pos,size);
}
function dataToString(data) {
    var sData = "";
    if (data != null) {
        var mes = data.getMonth() + 1;
        var dia = data.getDate();
        var ano = data.getYear();
        if (ano < 2000) {        // correçao para browsers que retornam 100 no ano 2000
            ano = 1900 + ano;
        }
        if (mes < 10) {
           mes = "0" + mes;
        }
        if (dia < 10) {
           dia = "0" + dia;
        }
        sData = dia+""+mes+""+ano;
    } else {
        sData = "";
    }
    return sData;
}
function toData(str) {
    var dia = str.substring(0,2) * 1;
    var mes = str.substring(3,5) * 1;
    var ano = str.substring(6,10) * 1;
    return new Date(ano,mes,dia);
}
function parseData(data) {
    var rtno = "";
    var vdata = "";
    var hoje = new Date();
    var dia = hoje.getDate()+"";
    var mes = hoje.getMonth()+1+"";
    var ano = hoje.getYear();
    if (ano < 1900) {
        ano = ano + 1900;
        ano = ano+"";
    }
    var dias = 0;
    var quandoVlr = new Array(-1,0,1,-1,0,1,0,-1,1,-1,0,1);
    var quando = indexOfArray(data.toLowerCase(),["ontem","hoje","amanha","yestarday","today","tomorrow","h","o","a","y","t","w"]);
    if (quando > -1) {
        dias = dias + quandoVlr[quando];
        var mais = data.indexOf("+");
        var menos = data.indexOf("-");
        if (mais > -1) {
            mais = data.substring(mais+1,data.length) * 1;
            dias = dias + mais;
        }
        if (menos > -1) {
            menos = data.substring(menos+1,data.length) * 1;
            dias = dias - menos;
        }
        dias = dias * 24 * 60 * 60 * 1000;
        hoje.setTime(dias + hoje.getTime());
        var dia = hoje.getDate()+"";
        var mes = hoje.getMonth()+1+"";
        var ano = hoje.getYear();
        if (ano < 1900) {
            ano = ano + 1900;
            ano = ano+"";
        }
    } else {
        for (var n=0; n < data.length; n++) {
            if (isNumber(data.substring(n,n+1))) {
                vdata = vdata+data.substring(n,n+1);
            }
        }
        if (vdata.length == 1) {
            dia = vdata.substring(0,1);
        }
        if (vdata.length == 2) {
            dia = vdata.substring(0,2);
        }
        if (vdata.length == 3) {
            dia = vdata.substring(0,1);
            mes = vdata.substring(1,3);
        }
        if (vdata.length == 4) {
            dia = vdata.substring(0,2);
            mes = vdata.substring(2,4);
        }
        if (vdata.length == 5) {
            dia = vdata.substring(0,2);
            mes = vdata.substring(2,4);
            ano = vdata.substring(4,5);
            ano = ano * 1;
            if (ano < 30) {
                ano = ano + 2000;
            } else {
                ano = ano + 1900;
            }
            ano = ano+"";
        }
        if (vdata.length == 6) {
            dia = vdata.substring(0,2);
            mes = vdata.substring(2,4);
            ano = vdata.substring(4,6);
            ano = ano * 1;
            if (ano < 30) {
                ano = ano + 2000;
            } else {
                ano = ano + 1900;
            }
            ano = ano+"";
        }
        if (vdata.length == 8) {
            dia = vdata.substring(0,2);
            mes = vdata.substring(2,4);
            ano = vdata.substring(4,vdata.length);
        }
        if (vdata.length == 10) {
            dia = vdata.substring(0,2);
            mes = vdata.substring(3,5);
            ano = vdata.substring(6,vdata.length);
        }
    }
    if (dia.length < 2) {
        dia = "0"+dia;
    }
    if (mes.length < 2) {
        mes = "0"+mes;
    }
    if (ano.length < 4) {
        if (ano > 30) {
            ano = "19"+ano;
        } else {
            ano = "20"+ano;
        }
    }
    vdi = validaData(dia,mes,ano);
    if (vdi == 1) {
        alert("Dia Inválido");
        rtno = "";
    } else if (vdi == 2) {
        alert("Mes Inválido");
        rtno = "";
    } else if (vdi == 3) {
        alert("Ano Inválido");
        rtno = "";
    } else {
        rtno = dia+"/"+mes+"/"+ano;
    }
    return rtno;
}

function parseHora(hora) {
    var rtno = "";
    var vhora = "";
    var agora = new Date();
    var hor = agora.getHours()+"";
    var min = agora.getMinutes()+"";
    if (hor.length < 2) hor = "0"+hor;
    if (min.length < 2) min = "0"+min;
    for (var n=0; n < hora.length; n++) {
        if (isNumber(hora.substring(n,n+1))) vhora = vhora+hora.substring(n,n+1);
    }
    var vhi = auxHora(vhora,hor,min);
    hor = vhi.substring(0,2);
    min = vhi.substring(2,4);
    vh = validaHora(hor,min);
    if (vh == 1) {
        alert("Hora Invlida");
    } else if (vh == 2) {
        alert("Minutos Invlido");
    } else {
        rtno = hor+":"+min;
    }
    return rtno;
}
function auxHora(vhora,hor,min) {
    if (vhora.length == 1) {
        hor = vhora.substring(0,1);
        min = "00";
    }
    if (vhora.length == 2) {
        hor = vhora.substring(0,2);
        min = "00";
    }
    if (vhora.length == 3) {
        hor = vhora.substring(0,1);
        min = vhora.substring(1,3);
    }
    if (vhora.length == 4) {
        hor = vhora.substring(0,2);
        min = vhora.substring(2,4);
    }
    if (hor.length < 2) hor = "0"+hor;
    if (min.length < 2) min = "0"+min;
    return hor+min;
}
function validaHora(hor,min) {
    var rtno = "0";
    hor += "";
    min += "";
    if ((!isNumber(hor)) | (!((hor >= 0) && (hor <= 24)))) {
        rtno = 1;
    } else if ((!isNumber(min)) | (!((min >= 0) && (min <= 60)))) {
        rtno = 2;
    }
    return rtno;
}

/****************************
* Valida documentos
**************************/
function validaCPF(ncpf) {
    var rtno = true;
    if (ncpf.length == 11) {
        var num = ncpf.substring(ncpf,0,9);
        var dig = ncpf.substring(ncpf,9,11);
        var d1 = 0;
        for (var i=0; i<9; i++)
            d1 += num.charAt(i)*(10-i);
        d1 = 11 - (d1 % 11);
        if (d1>9) d1 = 0;
        if (dig.charAt(0) != d1) {
            rtno = false;
        } else {
            d1 *= 2;
            for (i=0;i<9;i++)
                d1 += num.charAt(i)*(11-i);
            d1 = 11 - (d1 % 11);
            if (d1>9) d1 = 0;

            if (dig.charAt(1) != d1)
                rtno = false;
        }
    } else {
        rtno = false;
    }
    return rtno;
}
function validaCNPJ(ncnpj) {
    var rtno = false;
    if (ncnpj.length < 14) {
        ncnpj=strZero(ncnpj,14);
    }
    var digito = ncnpj.substring(12,14);
    var d1 = new Array(12);
    for(var n=0; n < 12; n++) {
        d1[n] = (ncnpj.charAt(n) + "") * 1;
    }
    //PRIMEIRO DIGITO
    //Calculo df1
    var df1 = 0;
    var mult = 5;
    for(var n=0; n < 4; n++) {
        df1+= d1[n] * mult;
        mult-=1;
    }
    mult = 9;
    for(var n=4; n < 12; n++) {
        df1+= d1[n] * mult;
        mult-=1;
    }
    var resto1 = df1 % 11;
    var pridig = -1;
    if((resto1 == 0) || (resto1 == 1)) {
        pridig = 0;
    } else {
        pridig = 11 - resto1;
    }
    //Segundo digito
    mult = 6;
    var df2=0;
    for(var n=0; n < 5; n++) {
        df2+= d1[n] * mult;
        mult-=1;
    }
    mult = 9;
    for(var n=5; n < 12; n++) {
        df2+= d1[n] * mult;
        mult-=1;
    }
    df2+=2*pridig;
    var resto2 = df2 % 11;
    var segdig = -1;
    if((resto2==0) || (resto2==1)) {
        segdig = 0;
    } else {
        segdig=11-resto2;
    }
    if (pridig+""+segdig == digito) {
       rtno = true;
    }
    return rtno;
}

// Outras funções de formatação
function fmtStr(str) {
   var s = "";
   if (str != null) {
       s = str;
   }
   return s;
}
function fmtValor(valor) {
    var rtno = "";
    if (valor) {
        var s = ""+valor;
        var oper = s.indexOf("-");
        var ponto = s.lastIndexOf(",");
        if (ponto == -1) {
            ponto = s.lastIndexOf(".");
        }
        if (ponto > -1) {
            var pFimI = ponto;
            var decimal = s.substring((ponto + 1),s.length);
            if (decimal) {
                decimal = getNumbers(decimal);
            } else {
                decimal = "0";
            }
            if (decimal.length == 1) {
                decimal = decimal+"0";
            }
            decimal = ","+decimal;
        } else {
            pFimI = s.length;
            var decimal = ",00";
        }
        var inteiro = s.substring(0,pFimI);
        if (inteiro) {
            inteiro = getNumbers(inteiro);
            if (!inteiro) {
                inteiro = 0;
            }
        } else {
            inteiro = 0;
        }
        var qtdeI = inteiro.length / 3;
        var restoI = "";
        if (inteiro.length > 3) {
            restoI = inteiro.length % 3;
            restoI = inteiro.substring(0,restoI);
        }
        if (qtdeI > 1) {
            qtdeI = Math.floor(qtdeI);
            for (n = 0; n < qtdeI; n++) {
                var pIni = inteiro.length - (3 + (3 * n));
                var pFin = inteiro.length - (3 * n);
                if (!restoI & (n == (qtdeI - 1))) {
                    rtno = inteiro.substring(pIni,pFin)+rtno;
                } else {
                    rtno = "."+inteiro.substring(pIni,pFin)+rtno;
                }
            }
        } else {
            rtno = inteiro;
        }
        if (oper > -1) {
            rtno = "R$-"+restoI+rtno+decimal;
        } else {
            rtno = "R$"+restoI+rtno+decimal;
        }
    } else {
        rtno = "R$0,00";
    }
    return rtno;
}

function getInteiro(valor,ponto) {
    var inteiro = valor.substring(0,ponto);
    if (!isEmpty(inteiro)) {
        inteiro = getNumbers(inteiro);
        if (isEmpty(inteiro)) {
            inteiro = 0;
        }
    } else {
        inteiro = 0;
    }
    return inteiro;
}
function getDecimal(valor,ponto) {
    var decimal = valor.substring((ponto + 1),valor.length);
    if (!isEmpty(decimal)) {
        decimal = getNumbers(decimal);
    } else {
        decimal = "0";
    }
    if (decimal.length == 1) {
        decimal = decimal+"0";
    }
    return decimal;
}
function getOperLogFromStr(s,withoutSpace) {
    if (s.indexOf(">=") > -1) {
        return withoutSpace ? ">=" : " >= ";
    } else if (s.indexOf("<=") > -1) {
        return withoutSpace ? "<=" : " <= ";
    } else if (s.indexOf(">") > -1) {
        return withoutSpace ? ">" : " > ";
    } else if (s.indexOf("<") > -1) {
        return withoutSpace ? "<" : " < ";
    } else {
        return "";
    }
}
function fmtPercentual(valor) {
    var rtno = "";
    if (!isEmpty(valor)) {
        valor = ""+valor;
        var operLog = getOperLogFromStr(valor,true);
        var oper = valor.indexOf("-");
        var ponto = valor.lastIndexOf(",");
        if (ponto == -1) {
            ponto = valor.lastIndexOf(".");
        }
        if (ponto > -1) {
            var decimal = getDecimal(valor,ponto);
            decimal = "."+decimal;
        } else {
            ponto = valor.length;
            var decimal = ".00";
        }
        var inteiro = getInteiro(valor,ponto);
        if (oper > -1) {
            rtno = "-"+inteiro+"%";
        } else {
            rtno = inteiro+"%";
        }
        if (operLog != null) {
            rtno = operLog+rtno;
        }
    }
    return rtno;
}
function fmtDecimal(valor) {
    var rtno = "";
    if (!isEmpty(valor)) {
        valor = ""+valor;
        var operLog = getOperLogFromStr(valor);
        var oper = valor.indexOf("-");
        var ponto = valor.lastIndexOf(",");
        if (ponto == -1) {
            ponto = valor.lastIndexOf(".");
        }
        if (ponto > -1) {
            var decimal = getDecimal(valor,ponto);
            decimal = "."+decimal;
        } else {
            ponto = valor.length;
            var decimal = ".00";
        }
        rtno = getInteiro(valor,ponto);
        if (oper > -1) {
            rtno = "-"+rtno+decimal;
        } else {
            rtno = rtno+decimal;
        }
        if (operLog != null) {
            rtno = operLog+rtno;
        }
    }
    return rtno;
}


function setChave(comp,obj) {
    if ((comp.type == "MaskField") && (comp.dataType == 'D')) {
        obj.setChave(top.convStrData(comp.getValue(),top.cnst.DATAMASK,top.cnst.DATACHAVE));
    } else {
        obj.setChave(comp.getValue());
    }
}
function getChave(obj,comp) {
    if ((comp.type == "MaskField") && (comp.dataType == 'D')) {
        comp.setValue(top.convStrData(obj.getChave()+"",top.cnst.DATACHAVE,top.cnst.DATAMASK));
    } else {
        comp.setValue(obj.getChave()+"");
    }
}

//Validacao padrao aValid matriz de campos
function validar(aValid) {
    var rtno = true;
    var msg = "";
    var firstCampo = -1;
    for (var n = 0; n < aValid.length; n++) {
        var erro = aValid[n].validar();
        if (erro > 0) {
            msg+="Campo " + aValid[n].valid.titulo +
                            eval("top.cnst.ERRO_"+erro)+"\n";
            rtno = false;
            if (firstCampo == -1) {
                firstCampo = n;
            }
        }
    }
    if (!rtno) {
        alert(msg);
        aValid[firstCampo].focus();
    }
    return rtno;
}


// Funções para trabalhar com Entidades //
function getTipoEntidade(idSys) {
    var rtno = null;
    var nomeCons = "consTipoEntidade";
    top.aplt.novaInstancia("cadTipoEntidade",top.pctPessoas+"TipoEntidade");
    if (aplt.criaConsulta(nomeCons,"cadTipoEntidade")) {
        aplt.montaConsulta(nomeCons,"sdl","like","%IDSYS%"+idSys+"%","O","","");
        if (aplt.consultar(nomeCons)) {
            tpEntds = top.aplt.getObjeto(nomeCons);
            rtno = tpEntds.elementAt(0);
        }
    }
    return rtno;
}


// Funçoes para validaçao de e-mail
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Changes: Clovis Wichoski (clovis_wichoski@uol.com.br) -->
/*
1.1.4.1: Translated Messages to Brasilian Portuguese.
1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */
// -->

<!-- Begin
function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray = emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

return "E-mail incorreto (ex: nome@dominio.com.br)";
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
return "O nome do usuário contém caracteres inválidos!";

   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
return "O nome do domínio contém caracteres inválidos!";
   }
}

// See if "user" is valid

if (user.match(userPat)==null) {

// user is not valid

return "O nome do usuário parece inválido!";
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
return "Endereço IP de destino é inválido!";
   }
}
return "";
}

// Domain is symbolic name.  Check if it's valid.

var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
return "O domínio parece inválido.";
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 &&
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
    return "O E-mail deve terminar com um domínio conhecido (.com) ou as duas letras do país (.br)!";
}

// Make sure there's a host name preceding the domain.

if (len<2) {
   return "Falta o nome do host!";
}
// If we've gotten this far, everything's valid!
return "";
}

function cleanCAPS(str) {
	capsallowed = 3;
	do {
		eval("re = /([A-Z]{" + (capsallowed+1) + ",})/g;");
		myArray = str.match(re);
		if (myArray) {
			eval("re = /" + myArray[0] + "/;");
			str = str.replace(re, ""+myArray[0].toLowerCase());
		}
	}
while (myArray);
return str;

}
