// Funçao para pegar acentos pro JBuilder
function acentos() {
    var acentos = "ã é Ã É ç õ Õ ó Ó à í ";
}
// Função para consulta
function consulta(form,naoCons,compl,where) {
    return montaFiltroConsulta(form,naoCons,compl,where);
}
function montaFiltroConsulta(form,naoCons,compl,where) {
    if (!naoCons) naoCons = "";
    var aNCons = new Array();
    if (!isEmpty(naoCons)) {
        aNCons = strTokenToArray(naoCons);
    }
    if (!compl) compl = "";
    if (!where) where = "";
    var campo = valor = expr = oper = null;
    var posI = posF = null;
    var vlrI = vlrF = null;
    var aTipoNCon = new Array("SVI","SEEK","SVE");
    for (var n=0; n < form.campos.length; n++) {
        campo = form.campos[n];
        if (!inArray(campo.tipo,aTipoNCon)) {
            if (!campo.isEmpty() && (!inArray(campo.nome,aNCons))) {
                if (!isEmpty(where))  where+=" AND ";
                if (campo.complNome != null) {
                    expr = campo.complNome;
                } else {
                    expr = campo.getExpr;
                    posI = expr.indexOf("get");
                    posF = expr.indexOf("()");
                    expr = firstLower(expr.substring(posI+3,posF));
                }
                if (!isEmpty(compl))  expr = compl+expr;
                if ((campo.tipo == "LK") || (campo.tipo == "DBS")) {
                    if (campo.objeto != null) {
                        where+=expr+' = \"'+campo.getOid()+'\"';
                    }
                } else if (campo.tipo == "CHV") {
                    var tipo = campo.objetos.elementAt(0);
                    if (isEmpty(compl)) {
                       where+=expr+' LIKE \"'+campo.getValue()+'%\" AND my'+firstUpper(getFieldName("set",campo.setExpr))+'.'+getFieldName("set",campo.extr[2])+' = "'+tipo.getOid()+'"';
                    } else {
                        where+=expr+' LIKE \"'+campo.getValue()+'%\" AND '+compl+'my'+firstUpper(getFieldName("set",campo.setExpr))+'.'+getFieldName("set",campo.extr[2])+' = "'+tipo.getOid()+'"';
                    }
                } else if (campo.tipo == "R" || campo.tipo == "S") {
                    where+=expr+' = \"'+campo.getValue()+'\"';
                } else {
                    if (campo.map.value.indexOf("NUL") > -1) {
                        if (campo.map.value.indexOf("!") > -1) {
                            where += "is_defined("+expr+")";
                        } else {
                            where += "is_undefined("+expr+")";
                        }
                    } else {
                        where+=expr;
                        if ((campo.map.value.indexOf("|") > -1) || (campo.map.value.indexOf(":") > -1)) {
                            valor = campo.map.value;
                            posF = valor.indexOf("|");
                            if (posF < 0) {
                                posF = valor.indexOf(":");
                            }
                            vlrI = valor.substring(0,posF);
                            vlrF = valor.substring(posF+1);
                            if (campo.tipo == "D") {
                                vlrF = getNumbers(vlrF);
                                vlrF = convStrData(vlrF,"DDMMAAAA","AAAA-MM-DD 00:00:00.0");
                            }
                            valor = vlrI;
                        } else {
                            valor = campo.getValue()+"";
                        }
                        oper = getOperLogFromStr(valor);
                        if ((campo.tipo == "A")) {
                            if (!isEmpty(oper)) {
                                var pos = valor.indexOf(getOperLogFromStr(valor,true));
                                where += oper+'"'+valor.substring(pos+(oper.length - 2),valor.length)+'"';
                            } else {
                                where += ' LIKE "'+valor+'%"';
                            }
                        } else if (campo.tipo == "S" || campo.tipo == "R") {
                            if (campo.valueType == "A") {
                                where+=' = "'+valor+'"';
                            } else {
                                where+=' = '+valor;
                            }
                        } else if (campo.tipo == "D") {
                            valor = getNumbers(valor);
                            valor = convStrData(valor,"DDMMAAAA","AAAA-MM-DD 00:00:00.0");
                            if (!isEmpty(oper)) {
                                where += oper+" \""+valor+"\"";
                            } else if (vlrF != null) {
                                where += " BETWEEN \""+valor+"\" AND \""+vlrF+"\"";
                            } else {
                                where += " = \""+valor+"\"";
                            }
                        } else if (campo.tipo == "M" || campo.tipo == "DC" || campo.tipo == "PC") {
                            valor = fmtDecimal(valor);
                            if (!isEmpty(oper)) {
                                var pos = valor.indexOf(getOperLogFromStr(valor,true));
                                where += oper+valor.substring(pos+(oper.length - 2),valor.length);
                            } else if (vlrF != null) {
                                where += " BETWEEN "+valor+" AND "+fmtDecimal(vlrF);
                            } else {
                                where += "="+valor;
                            }
                        } else {
                            if (!isEmpty(oper)) {
                                valor = getNumbers(valor);
                                where += oper+valor;
                            } else if (vlrF != null) {
                                where += " BETWEEN "+valor+" AND "+vlrF;
                            } else {
                                where += "="+valor;
                            }
                        }
                    }
                }
            }
        }
    }
    return where;
}
function getFieldName(iniStr,expr) {
    var rtno = "";
    var posI = expr.indexOf(iniStr);
    var posF = expr.indexOf("(");
    rtno = firstLower(expr.substring(posI+3,posF));
    return rtno;
}
// Funcoes NovoClick
function setNovoClick(campo) {
    var aExpr = null;
    if (campo.objeto != null) {
        var objRef = campo.objeto;
        if (campo.actNovoClick.length > 1) {
            for (var n=1; n < campo.actNovoClick.length; n++) {
                aExpr = campo.actNovoClick[n];
                if (eval(aExpr[0])) {
                    repos.nsXML.setValue(aExpr[1]+"/oid",campo.getOid());
                    location = repos.baseUrl+aExpr[1]+".htm";
                    break;
                }
            }
        } else {
            aExpr = campo.actNovoClick[0];
            repos.nsXML.setValue(aExpr[0]+"/oid",campo.getOid());
            location = repos.baseUrl+aExpr[0]+".htm";
        }
    } else {
        aExpr = campo.actNovoClick[0];
        location = repos.baseUrl+aExpr[0]+".htm";
    }
}
function getNovoClick(campo) {
    var aExpr = campo.actNovoClick[0];
    var objRef = repos.nsXML.getValue(aExpr[1]);
    if (objRef != null) {
        eval(parseTemplateArray(campo.setExpr,["%objRef"],["objRef"]));
        if (campo.tipo == "LK") {
            lksChange(campo.nome);
        } else if (campo.tipo == "DBS") {
            dbsChange(campo.nome);
        }
    }
    novoClick = "";
}
function checkNovoClick(path) {
    var oidTemp = repos.nsXML.getValue(path);
    var rtno = false;
    if (!isEmpty(oidTemp)) {
       navbar.carrega(oidTemp);
       repos.nsXML.setValue(path,null);
       rtno = true;
    }
    return rtno;
}
// Funções para Cookie
function setCookie(name,value,expires,path,domain,secure) {
    document.cookie = name+"="+escape(value)+
                      ((expires) ? "; expires="+expires.toGMTString() : "") +
                      ((path) ? "; path="+path : "") +
                      ((domain) ? "; domain="+domain : "") +
                      ((secure) ? "; secure="+secure : "");
}
function getCookieData(labelName) {
    var labelLen = labelName.length;
    var cookieData = document.cookie;
    var cLen = cookieData.length;
    var i = 0;
    var cEnd;
    var j;
    while (i < cLen) {
        j = i+labelLen;
        if (cookieData.substring(i,j) == labelName) {
            cEnd = cookieData.indexOf(";",j);
            if (cEnd == -1) {
                cEnd = cookieData.length;
            }
            return unescape(cookieData.substring(j+1,cEnd));
        }
        i++;
    }
    return "";
}
//
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 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 selValue(sel) {
    return sel.options[sel.selectedIndex].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 == '/') || (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();
                   }
               }
           }
        }
        nomeProprio += ch;
    }
    nomeProprio = parseTemplateArray(nomeProprio,[" Da "," Das "," De "," Do "," Dos "," E "," A "," Na "," No "," Em "," Ao "],
                                                 [" da "," das "," de "," do "," dos "," e "," a "," na "," no "," em "," ao "]);
    return nomeProprio;
}
function firstUpper(str) {
    return str.substr(0,1).toUpperCase()+str.substr(1,str.length);
}
function firstLower(str) {
    return str.substr(0,1).toLowerCase()+str.substr(1,str.length);
}
function betweenCh(ch,chI,chF) {
    if ((ch >= chI) && (ch <= chF)) {
        return true;
    } else {
        return false;
    }
}
function startWith(str,vlr) {
    return str.indexOf(vlr) == 0;
}
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) {
    if (s != null) 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 strLength(str) {
    if (str == null) {
        return 0;
    } else {
        str = str+"";
        return str.length;
    }
}
function lengthOid(obj) {
    if (obj == null) {
        return 0;
    } else if (isEmpty(obj.getOid())) {
        return 0;
    } else {
        var oidTemp = obj.getOid()+"";
        return oidTemp.length;
    }
}
function pegaOid(obj) {
    if (obj != null) {
        return obj.getOid();
    } else {
        return "";
    }
}
function equalsOid(obj1,obj2) {
    var rtno = false;
    if (obj1 != null && obj2 != null) {
        if (obj1.getOid()+"" == obj2.getOid()+"") {
            rtno = true;
        }
    }
    return rtno;
}
function removeChars(str,chars) {
    var rtno = "";
    var isChar = false;
    for (var n = 0; n < str.length; n++) {
        isChar = false;
        if (chars.indexOf(str.charAt(n)) >= 0) {
            isChar = true;
        }
        if (!isChar) {
            rtno += str.charAt(n);
        }
    }
    return rtno;
}
function inArray(str,array) {
    var rtno = false;
    for (var n=0; n < array.length; n++) {
        if (str.indexOf(array[n]) > -1) {
            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 strTokenToArray(str) {
    var posI = 0;
    var posF = 0;
    var aRtno = new Array();
    if (isEmpty(str.substring(0,1))) posF = posI = 1;
    for (var n = 0; n < str.length; n++) {
        if ((str.substring(n,n+1).indexOf(" ") > -1 && (n > 0)) || (n == (str.length - 1))) {
            if (n == (str.length - 1) && (str.substring(n,n+1).indexOf(" ") == -1)) {
                posF = n+1;
            } else {
                posF = n;
            }
            aRtno[n] = str.substring(posI,posF);
            posI = posF+1;
        }
    }
    return aRtno;
}
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;
}
function spdtUnescape(str) {
    var rtno = str;
    var aSpecCharTag = new Array("&apos;");
    var aSpecCharVal  = new Array("'");
    while (inArray(rtno,aSpecCharTag)) {
        rtno = parseTemplateArray(rtno,aSpecCharTag,aSpecCharVal);
    }
    return rtno;
}
function toLiteral(str) {
    var rtno = "";
    for (var n = 0; n < str.length; n++) {
        if (str.charAt(n) == "'") {
            rtno+="\\'";
        } else {
            rtno+=str.charAt(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 hoje() {
    var hoje = new Date();
    var ahoje = new Array(6);
    ahoje[0] = hoje.getDate()+"";
    ahoje[1] = hoje.getMonth()+1+"";
    ahoje[2] = hoje.getYear();
    ahoje[3] = hoje.getHours()+"";
    ahoje[4] = hoje.getMinutes()+"";
    ahoje[5] = hoje.getSeconds()+"";
    if (ahoje[0].length < 2) {
        ahoje[0] = "0"+ahoje[0];
    }
    if (ahoje[1].length < 2) {
        ahoje[1] = "0"+ahoje[1];
    }
    if (ahoje[2] < 1900) {
        ahoje[2] = ahoje[2] + 1900;
        ahoje[2] = ahoje[2]+"";
    }
    if (ahoje[3].length < 2) {
        ahoje[3] = "0"+ahoje[3];
    }
    if (ahoje[4].length < 2) {
        ahoje[4] = "0"+ahoje[4];
    }
    if (ahoje[5].length < 2) {
        ahoje[5] = "0"+ahoje[5];
    }
    return ahoje;
}
function nHoje() {
    var hoje = new Date();
    var ahoje = new Array(6);
    ahoje[0] = hoje.getDate();
    ahoje[1] = hoje.getMonth()+1;
    ahoje[2] = hoje.getYear();
    ahoje[3] = hoje.getHours();
    ahoje[4] = hoje.getMinutes();
    ahoje[5] = hoje.getSeconds();
    if (ahoje[2] < 1900) {
        ahoje[2] = ahoje[2] + 1900;
    }
   return ahoje;
}
function strDataToArray(str) {
    var rtno = new Array(3);
    rtno[0] = str.substring(0,2) * 1;
    rtno[1] = str.substring(3,5) * 1;
    rtno[2] = str.substring(6,str.length) * 1;
    return rtno;
}
function validaDatas(dataI,dataF) {
    var rtno = true;
    dataI = convStrData(dataI,"DD/MM/AAAA hh:mm","AAAAMMDDhhmm");
    dataF = convStrData(dataF,"DD/MM/AAAA hh:mm","AAAAMMDDhhmm");
    if ((dataI * 1) > (dataF * 1)) {
//        alert("Data Final < Data Inicial");
        rtno = false;
    }
    return rtno;
}
function validaData(dia,mes,ano) {
    var rtno = "0";
    dia += "";
    mes += "";
    ano += "";
    if ((!isNumber(ano)) | (ano.length < 2)) {
        rtno = 1;
    } else if ((!isNumber(mes)) | (!((mes >= 1) && (mes <= 12)))) {
        rtno = 2;
    } else if ((!isNumber(dia)) | (!((dia >= 1) && (dia <= maxDia(mes,ano))))) {
        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 (!isEmpty(data)) {
        var mes = data.getMonth() + 1;
        var dia = data.getDate();
        var ano = data.getYear();
        if (ano < 2000) ano = 1900 + ano;
        if (mes < 10)   mes = "0" + mes;
        if (dia < 10)   dia = "0" + dia;
        sData = dia+"/"+mes+"/"+ano;
    }
    return sData;
}
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 dataJava(strData) {
    var dia = strData.substring(0,2);
    var mes = strData.substring(3,5);
    var ano = strData.substring(6,strData.length);
    if (isEmpty(dia)) {
        dia = 0;
        mes = 0;
        ano = 0;
    }
    return aplt.getDate(dia,mes,ano);
}
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) {
    var rtno = fmtRtno;
    var POS = 0;
    var SIZE = 1;
    var diaLay = getLayoutStr("D",fmt);
    var mesLay = getLayoutStr("M",fmt);
    var anoLay = getLayoutStr("A",fmt);
    var horLay = getLayoutStr("h",fmt);
    var minLay = getLayoutStr("m",fmt);
    var segLay = getLayoutStr("s",fmt);
    var dia = null;
    var mes = null;
    var ano = null;
    var hor = null;
    var min = null
    var seg = 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]);
    if (horLay[POS] > -1)  hor = data.substr(horLay[POS],horLay[SIZE]);
    if (minLay[POS] > -1)  min = data.substr(minLay[POS],minLay[SIZE]);
    if (segLay[POS] > -1)  seg = data.substr(segLay[POS],segLay[SIZE]);
    // Retorno
    var rtnDiaLay = getLayoutStr("D",fmtRtno);
    var rtnMesLay = getLayoutStr("M",fmtRtno);
    var rtnAnoLay = getLayoutStr("A",fmtRtno);
    var rtnHorLay = getLayoutStr("h",fmtRtno);
    var rtnMinLay = getLayoutStr("m",fmtRtno);
    var rtnSegLay = getLayoutStr("s",fmtRtno);
    if ((rtnAnoLay[POS]) > -1) {
        var 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);
    if (rtnHorLay[POS] > -1) rtno = parseTemplate(rtno,"hh",hor);
    if (rtnMinLay[POS] > -1) rtno = parseTemplate(rtno,"mm",min);
    if (rtnSegLay[POS] > -1) rtno = parseTemplate(rtno,"ss",seg);
    return rtno;
}
function dataToStr(data,fmtRtno) {
    var rtno = fmtRtno;
    var POS = 0;
    var SIZE = 1;
    var dia = null;
    var mes = null;
    var 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
    var rtnDiaLay = getLayoutStr("D",fmtRtno);
    var rtnMesLay = getLayoutStr("M",fmtRtno);
    var rtnAnoLay = getLayoutStr("A",fmtRtno);
    if ((rtnAnoLay[POS]) > -1) {
        var 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) {
    var pos = str.indexOf(tag);
    var 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) ano = 1900 + ano;
        if (mes < 10)   mes = "0" + mes;
        if (dia < 10)   dia = "0" + dia;
        sData = dia+""+mes+""+ano;
    } else {
        sData = "";
    }
    return sData;
}
function validaOperadoresData(data) {
    var rtno = "";
    if (data.indexOf(">=") > -1) {
        oper = ">=";
    } else if (data.indexOf("<=") > -1) {
        oper = "<=";
    } else if (data.indexOf(">") > -1) {
        oper = ">";
    } else if (data.indexOf("<") > -1) {
        oper = "<";
    }
    if ((data.indexOf("|") > -1) || (data.indexOf(":") > -1)) {
        var posF = data.indexOf("|");
        if (posF < 0) {
            posF = data.indexOf(":");
        }
        var vlrI = data.substring(0,posF);
        var vlrF = data.substring(posF+1);
        vlrI = getNumbers(vlrI);
        vlrF = getNumbers(vlrF);
        vlrI = parseData(vlrI);
        vlrF = parseData(vlrF);
        if (validaDatas(vlrI,vlrF)) {
            rtno = vlrI+":"+vlrF;
        } else {
            rtno = vlrI;
        }
    } else if (oper != null) {
        data = getNumbers(data);
        rtno = parseData(data);
        rtno = oper+rtno;
    }
    return rtno;
}
function parseData(data) {
    var rtno = "";
    var vdata = "";
    var notNull = data.indexOf("!");
    if ((data.indexOf("NUL") > -1) || (data.indexOf("nul") > -1)) {
        if (notNull > -1) {
            rtno = "!NULA";
        } else {
            rtno = "NULA";
        }
    } else {
        var oper = "|:><=";
        for (var n = 0; n < oper.length; n++) {
            var o = oper.charAt(n);
            if (data.indexOf(o) > -1) {
                rtno = validaOperadoresData(data);
                break;
            }
        }
        if (rtno == "") {
            var hoje = new Date();
            var dia = hoje.getDate()+"";
            var mes = hoje.getMonth()+1+"";
            var ano = hoje.getYear();
            if (dia.length < 2) dia = "0"+dia;
            if (mes.length < 2) mes = "0"+mes;
            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,9);
            var quando = indexOfArray(data.toLowerCase(),["ontem","hoje","amanha","yestarday","today","tomorrow","h","o","a","y","t","w","d"]);
            var mais = data.indexOf("+");
            var menos = data.indexOf("-");
            var oper = null;
            var pos = 0;
            if (quando > -1) {
                var dias = dias + quandoVlr[quando];
                var faz = false;
                if (dias == 9) dias = 0;
                if (mais > -1) {
                    pos = mais;
                    mais = data.substring(mais+1,data.length) * 1;
                    dias = dias + mais;
                }
                if (menos > -1) {
                    pos = menos;
                    menos = data.substring(menos+1,data.length) * 1;
                    dias = dias - menos;
                }
                dias = dias * 24 * 60 * 60 * 1000;
                if (faz) {
                    for (var n=0; n < pos; n++) {
                        if (isNumber(data.substring(n,n+1))) {
                            vdata = vdata+data.substring(n,n+1);
                        }
                    }
                    var vdi = auxData(vdata,dia,mes,ano);
                    dia = vdi.substring(0,2);
                    mes = vdi.substring(2,4);
                    ano = vdi.substring(4,8);
                    var dtas = new Date(ano,mes - 1,dia);
                    dtas.setTime(dias + dtas.getTime());
                    dia = dtas.getDate()+"";
                    mes = dtas.getMonth()+1+"";
                    ano = dtas.getYear();
                    if (dia.length < 2) dia = "0"+dia;
                    if (mes.length < 2) mes = "0"+mes;
                    if (ano < 1900) {
                        ano = ano + 1900;
                        ano = ano+"";
                    }
                } else {
                    hoje.setTime(dias + hoje.getTime());
                    dia = hoje.getDate()+"";
                    mes = hoje.getMonth()+1+"";
                    ano = hoje.getYear();
                    if (dia.length < 2) dia = "0"+dia;
                    if (mes.length < 2) mes = "0"+mes;
                    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);
                    }
                }
                var vdi = auxData(vdata,dia,mes,ano);
                dia = vdi.substring(0,2);
                mes = vdi.substring(2,4);
                ano = vdi.substring(4,8);
            }
            vd = validaData(dia,mes,ano);
            rtno = "";
            if (vd == 3) {
                alert("Dia Inválido");
            } else if (vd == 2) {
                alert("Mes Inválido");
            } else if (vd == 1) {
                alert("Ano Inválido");
            } else {
                rtno = dia+"/"+mes+"/"+ano;
            }
        }
    }
    return rtno;
}
function auxData(vdata,dia,mes,ano) {
    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;
        }
    }
    return dia+mes+ano;
}
// Hora
// Funções de Hora
function fmtHora(hora) {
    sHora = "";
    if (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 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 Inválida");
    } else if (vh == 2) {
        alert("Minutos Inválido");
    } 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 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 fmtStr(str) {
   var s = "";
   if (str != null) {
       s = str;
   }
   return s;
}
function validaCampoNumerico(valor) {
    var rtno = 0;
    var oper = getOperLogFromStr(valor,true);
    if (isEmpty(oper) && ((valor.indexOf("|") > -1) || (valor.indexOf(":") > -1))) {
        var vlrI = getValorInicialOperBetween(valor);
        var vlrF = getValorFinalOperBetween(valor);
        if (validaValores(vlrI,vlrF)) {
            rtno = vlrI+":"+vlrF;
        } else {
            rtno = vlrI;
        }
    } else {
        valor = getNumbers(valor);
        rtno = oper+valor;
    }
    return rtno;
}
function fmtValor(valor) {
    var rtno = "";
    if (!isEmpty(valor)) {
        valor = ""+valor
        var oper = getOperLogFromStr(valor,true);
        if (isEmpty(oper) && ((valor.indexOf("|") > -1) || (valor.indexOf(":") > -1))) {
            var vlrI = getValorInicialOperBetween(valor);
            var vlrF = getValorFinalOperBetween(valor);
            if (validaValores(fmtDecimal(vlrI),fmtDecimal(vlrF))) {
                vlrI = fmtDecimalMoeda(vlrI);
                vlrF = fmtDecimalMoeda(vlrF);
                rtno = vlrI+":"+vlrF;
            } else {
                rtno = fmtValor(vlrI);
            }
        } else {
            rtno = oper+"R$"+fmtDecimalMoeda(valor);
        }
    } else {
        rtno = "R$0,00";
    }
    return rtno;
}
function fmtDecimalMoeda(valor) {
    var rtno = "";
    var sinal = 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);
    rtno = fmtMilhar(inteiro);
    if (sinal > -1) {
        rtno = "-"+rtno+decimal;
    } else {
        rtno = rtno+decimal;
    }
    return rtno;
}
function fmtDecimal(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";
        }
        rtno = getInteiro(valor,ponto);
        if (oper > -1) {
            rtno = "-"+rtno+decimal;
        } else {
            rtno = rtno+decimal;
        }
        if (operLog != null) {
            rtno = operLog+rtno;
        }
    }
    return rtno;
}
function fmtPercentual(valor) {
    var rtno = "";
    if (!isEmpty(valor)) {
        valor = ""+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";
        }
        var inteiro = getInteiro(valor,ponto);
        if (oper > -1) {
            rtno = "-"+inteiro+decimal+"%";
        } else {
            rtno = inteiro+decimal+"%";
        }
    }
    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 fmtMilhar(valor) {
    if (valor.length > 3) {
        var qtde = valor.length / 3;
        if (qtde > 1) {
            var resto = valor.length % 3;
            resto = valor.substring(0,resto);
            qtde = Math.floor(qtde);
            var vlrAux = valor;
            valor = "";
            for (var n = 0; n < qtde; n++) {
                var pIni = vlrAux.length - (3 + (3 * n));
                var pFin = vlrAux.length - (3 * n);
                if (!resto & (n == (qtde - 1))) {
                    valor = vlrAux.substring(pIni,pFin)+valor;
                } else {
                    valor = "."+vlrAux.substring(pIni,pFin)+valor;
                }
            }
            valor = resto+valor;
        }
    }
    return valor;
}
function getValorInicialOperBetween(valor) {
    var pos = valor.indexOf("|");
    if (pos < 0) {
        pos = valor.indexOf(":");
    }
    return valor.substring(0,pos);
}
function getValorFinalOperBetween(valor) {
    var pos = valor.indexOf("|");
    if (pos < 0) {
        pos = valor.indexOf(":");
    }
    return valor.substring(pos+1);
}
function validaValores(vlrI,vlrF) {
    var rtno = true;
    if ((vlrI * 1) > (vlrF * 1)) {
        alert("Valor Final < Valor Inicial");
        rtno = false;
    }
    return rtno;
}
//
function fmtHistoricoFiscal(cfop) {
    var rtno = "";
    if (cfop != null) {
        rtno = cfop.toString();
        rtno = rtno.substring(0,1)+"."+rtno.substring(1,rtno.length);
    }
    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()+"");
    }
}
function getReqTime() {
    var aHoje = hoje();
    return aHoje[2]+aHoje[1]+aHoje[0]+aHoje[3]+aHoje[4]+aHoje[5];
}
//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ção para vetores java
function isEmptyVector(v) {
    if ((v != null) && (v.size() > 0)) {
        return false;
    } else {
        return true;
    }
}
function lengthVector(v) {
    if ((v != null)) {
        return v.size();
    } else {
        return 0;
    }
}
function addAllVector(v1,v2) {
    if (v1 != null && v2 != null) {
        for (var n = 0; n < v2.size(); n++) {
            v1.addElement(v2.elementAt(n));
        }
    }
}
function setExclAllVector(v) {
    if (!isEmptyVector(v)) {
        var obj = null;
        for (var n = 0; n < v.size(); n++) {
            obj = v.elementAt(n);
            if (lengthOid(obj) > 7) {
                obj.setExcluir(true);
            }
        }
    }
}
function getElementVectorOid(oid,v) {
    var obj = null;
    if ((oid != null) && (v != null)) {
        if (v.size() > 0) {
            for (var n = 0; n < v.size(); n++) {
                obj = v.elementAt(n);
                if (obj.getOid()+"" == oid) {
                    break;
                } else {
                    obj = null
                }
            }
        }
    }
    return obj;
}
function getElementVectorPorIndice(n,v) {
    var obj = null;
    if ((n != null) && (v != null)) {
        if (v.size() > 0) {
            if (n < v.size()) {
                obj = v.elementAt(n);
            }
        }
    }
    return obj;
}
function removeElementVectorOid(oid,v) {
    if ((oid != null) && (v != null)) {
        if (v.size() > 0) {
            for (var n = 0; n < v.size(); n++) {
                obj = v.elementAt(n);
                if (obj.getOid()+"" == oid) {
                    v.removeElementAt(n);
                    break;
                }
            }
        }
    }
}
function getElementVectorExpr(expr,v) {
    var objRef = null;
    if ((expr != null) && (v != null)) {
        if (v.size() > 0) {
            for (var n = 0; n < v.size(); n++) {
                objRef = v.elementAt(n);
                if (eval(expr)) {
                    break;
                } else {
                    objRef = null;
                }
            }
        }
    }
    return objRef;
}
function removeElementVectorExpr(expr,v) {
    var objRef = null;
    if ((expr != null) && (v != null)) {
        if (v.size() > 0) {
            for (var n = 0; n < v.size(); n++) {
                objRef = v.elementAt(n);
                if (eval(expr)) {
                    v.removeElementAt(n);
                    break;
                }
            }
        }
    }
    return objRef;
}
function getInStrVectorExpr(expr,v) {
    var rtno = ' (';
    if ((expr != null) && (v != null)) {
        if (v.size() > 0) {
            var objRef = null;
            var valor = null;
            for (var n = 0; n < v.size(); n++) {
                objRef = v.elementAt(n);
                valor = eval(expr);
                rtno += '"'+valor+'"';
                if (n < (v.size() - 1)) {
                    rtno += ', ';
                }
            }
        }
    }
    return rtno+')';
}
// Funcoes de Link
function linkFocus(nome) {
    for (var n = 0; n < document.links.length; n++) {
        if (document.links[n].name == nome) {
            document.links[n].focus();
            break;
        }
    }
}
// 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. */
    alert("E-mail incorreto (ex: nome@dominio.com.br)");
    return false;
}
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) {
        alert("O nome do usuário contém caracteres inválidos!");
        return false;
    }
}
for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
        alert("O nome do domínio contém caracteres inválidos!");
        return false;
   }
}
// See if "user" is valid
if (user.match(userPat)==null) {
    alert("O nome do usuário parece inválido!");
    return false;
}
/* 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) {
            alert("Endereço IP de destino é inválido!");
            return false;
        }
    }
    return true;
}
// 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) {
        alert("O domínio parece inválido!");
        return false;
    }
}
/* 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) {
    alert("O E-mail deve terminar com um domínio conhecido (.com) ou as duas letras do país (.br)!");
    return false;
}
// Make sure there's a host name preceding the domain.
if (len<2) {
   alert("Falta o nome do host!");
   return false;
}
// If we've gotten this far, everything's valid!
return true;
}
