
function TamDado(objeto, tam) {
    if (objeto.value.length > tam) {
        alert("O tamanho máximo de "+tam+" caracteres do campo foi superado. Elimine o excesso.");
    }
}

function TamData(objeto, tam) {
    if (objeto.value.match("^\\d{3}$")) {
        if (tam < 9)
            objeto.value = objeto.value.substring(0, 2)+":"+ objeto.value.substring(2, 3);
        else
            objeto.value = objeto.value.substring(0, 2)+"/"+ objeto.value.substring(2, 3);
    }
    else if (objeto.value.match("^\\d{2}[/:]\\d{3}$")) {
        if (tam < 9)
            objeto.value = objeto.value.substring(0, 5)+":"+ objeto.value.substring(5, 6);
        else
            objeto.value = objeto.value.substring(0, 5)+"/"+ objeto.value.substring(5, 6);
    }
    else if (objeto.value.match("\\d{2}[/]\\d{2}[/]\\d{5}$"))
        objeto.value = objeto.value.substring(0, 10)+" "+ objeto.value.substring(10, 11);
    else if (objeto.value.match("\\d{2}[/]\\d{2}[/]\\d{4}[ ]\\d{3}$"))
        objeto.value = objeto.value.substring(0, 13)+":"+ objeto.value.substring(13, 14);
    else if (objeto.value.match("\\d{2}[/]\\d{2}[/]\\d{4}[ ]\\d{2}[:]\\d{3}$"))
        objeto.value = objeto.value.substring(0, 16)+":"+ objeto.value.substring(16, 17);
}

function TamCpf(objeto) {
    if (objeto.value.length > 14) {
        alert("O tamanho máximo de "+tam+" caracteres do campo foi superado. Elimine o excesso.");
    }
}

function TamCep(objeto) {
    for(i=0;i<9;i++){
        if (/^[0-9]+$/.test(objeto.value))
            break;
        objeto.value = objeto.value.replace( ".", "" );
        objeto.value = objeto.value.replace( " ", "" );
        objeto.value = objeto.value.replace( "/", "" );
        objeto.value = objeto.value.replace( "-", "" );
    }
    if (/^[0-9]{0,8}$/.test(objeto.value)) {
    } else {
        alert("CEP incorreto.");
        objeto.focus();
    }
}

function erroString(obj, obrigatorio, tam, titulo) {
    if (fLTrim(obj.value).length == 0) {
        if (obrigatorio == "Sim") {
            alert("Preenchimento obrigatorio de "+titulo);
            obj.focus();
            return true;
        }
    }
    else if (obj.value.length > tam) {
        alert("Conteúdo do campo superou o tamanho máximo. Elimine "+eval(obj.value.length - tam)+" caracteres.");
        obj.focus();
        return true;
    }
    return false;
}

function fLTrim(sValor) {
    var wI = sValor.length - 1;
    for (; wI > -1; wI--) {
        if (sValor.substring(wI, wI + 1) != " ")
            return sValor.substring(0,wI + 1);
    }
    return "";
}

function erroBoolean(obj, obrigatorio, titulo) {
    if ((obrigatorio == "Sim") && (obj.value.length == 0)) {
        alert("Informe obrigatoriamente Sim ou Não em "+titulo);
        obj.focus();
        return true;
    }
    return false;
}

function erroEmail(obj, obrigatorio, titulo) {
    if ((obrigatorio == "Sim") && (obj.value.length == 0)) {
        alert("Informe obrigatoriamente seu e-mail.");
        obj.focus();
        return true;
    }
    else if ((obrigatorio == "Não") && (obj.value.length == 0)) {
        return false;
    }
    else {
        if (/^((\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+;?){1,3})+$/.test(obj.value))
        {}
        else {
            alert("Informe corretamente o e-mail.");
            obj.focus();
            return true;
        }
    }
    return false;
}

function erroInt(obj, obrigatorio, tam, titulo) {
    if ((obrigatorio != "Sim") && (obj.value.length == 0))
        return false;
    if (obj.value.length > tam) {
        alert("Conteúdo do campo superou o máximo de "+tam+" caracteres. Corrija!");
        obj.focus();
        return true;
    }
    if (/^[-]?[0-9]+$/.test(obj.value))
    {}
    else {
        alert("Informe obrigatoriamente um Número Inteiro em "+titulo);
        obj.focus();
        return true;
    }
    return false;
}

function erroFK(obj, obrigatorio, titulo) {
    if (obrigatorio != "Sim")
        return false;
    if (fLTrim(obj.value).length > 0) {
        if (obj.value != "0")
            return false;
    }
    alert("Selecione uma das opções de "+titulo);
    obj.focus();
    return true;
}

function erroFloat(obj, obrigatorio, tam, titulo) {
    if ((obrigatorio != "Sim") && (obj.value.length == 0))
        return false;
    if (obj.value.length > tam) {
        alert("Conteúdo do campo superou o máximo de "+tam+" caracteres. Corrija!");
        obj.focus();
        return true;
    }
    if (/^[-]?[0-9]+([.,][0-9]+)?$/.test(obj.value))
    {}
    else {
        alert("Informe obrigatoriamente um número com casas decimais em "+titulo);
        obj.focus();
        return true;
    }
    obj.value = obj.value.replace( ",", "." );
    return false;
}

function erroCEP(obj, obrigatorio, titulo) {
    if ((obrigatorio != "Sim") && (obj.value.length == 0))
        return false;
    if (erroInt(obj, "obrigatorio", 8))
        return true;
    if (obj.value < 1000000) {
        alert("CEP incorreto.");
        obj.focus();
        return true;
    }
    return false;
}

function erroDateTime(obj, obrigatorio, tam, titulo) {
    if ((obrigatorio != "Sim") && (obj.value.length == 0))
        return false;
    if (obj.value.length != tam) {
        if (tam == 10)
            msg = "Preencha a DATA com o formato DD/MM/AAAA";
        else if (tam == 16)
            msg = "Preencha a DATA/HORA com o formato DD/MM/AAAA HH:MM";
        else if (tam == 19)
            msg = "Preencha a DATA/HORA com o formato DD/MM/AAAA HH:MM:SS";
        else if (tam == 8)
            msg = "Preencha a HORA com o formato HH:MM:SS";
    }
    else {
        msg = ValidaDataDMA(obj.value, tam);
        if(msg == "") {
            msg = ValidaHoraHMS(obj.value, tam);
            if(msg == "")
                return false;
        }
    }
    alert(msg+" em "+titulo);
    obj.focus();
    return true;
}

function ValidaDataDMA(strData, tipo) {
    if (tipo == 8)
        return("");

    var strDia = new String;
    var strMes = new String;
    var strAno = new String;

    strDia = strData.substring(0,2);
    strMes = strData.substring(3,5);
    strAno = strData.substring(6,10);

    if ((strAno < "1900") || (strAno > "2050"))
        return("Informe ANO dentro da faixa de 1900 a 2050.");

    if ((strMes < "01") || (strMes > "12"))
        return("Informe MÊS dentro da faixa de 01 a 12.");

    if ((strMes == "01") || (strMes == "03") || (strMes == "05") ||
        (strMes == "07") || (strMes == "08") || (strMes == "10") ||
        (strMes == "12")) {
        if((strDia < "01" ) || (strDia > "31"))
            return("Informe Dia dentro da faixa de 01 a 31.");
    }

    if((strMes == "04") || (strMes == "06") || (strMes == "09") ||
        (strMes == "11")) {
        if((strDia < "01") || (strDia > "30"))
            return("Informe Dia dentro da faixa de 01 a 30.");
    }

    if (strMes == "02") {
        if ((strDia < "01") || (strDia > "29"))
            return("Informe Dia dentro da faixa de 01 a 29.");
        else {
            if ((strDia == "29") && ((parseFloat(strAno) % 4) != 0))
                return("Informe Dia dentro da faixa de 01 a 28.");
        }
    }
    return("");
}

function ValidaHoraHMS(sHora, tipo) {
    if (tipo == 10)
        return("");
    if (tipo == 19)
        strHora = sHora.substring(11,19);
    else if (tipo == 16)
        strHora = sHora.substring(11,16);
    else
        strHora = sHora;

    var strHH = new String;
    var strMM = new String;
    var strSS = new String;

    strHH = strHora.substring(0,2);
    if ((strHH  < "00") || (strHH > "23"))
        return("Informe HORA dentro da faixa de 00 a 23.");

    strMM = strHora.substring(3,5);
    if ((strMM   < "00") || (strMM > "59"))
        return("Informe MINUTOS dentro da faixa de 00 a 59.");

    if ((tipo == 8) || (tipo == 19)){
        strSS = strHora.substring(6,8);
        if ((strSS   < "00") || (strSS > "59"))
            return("Informe SEGUNDOS dentro da faixa de 00 a 59.");
    }
    return("");
}

function erroCpf(obj, obrigatorio, titulo) {
    obj.value.concat("");
    if ((obrigatorio != "Sim") && (obj.value.length == 0)) {
        return false;
    }
    else {
        str1 = obj.value.concat("@");
        for(i=0;i<14;i++){
            str1 = str1.replace( "@", "" );
            str1 = str1.replace( ".", "" );
            str1 = str1.replace( " ", "" );
            str1 = str1.replace( "/", "" );
            str1 = str1.replace( "-", "" );
        }
        if (str1.length != 11) {
            alert("Preencha obrigatoriamente o CPF com 11 dígitos, incluindo os zeros à esquerda.");
            obj.focus();
            return true;
        }
        if (ValidaCPF(str1)) {
            obj.value = str1.substring(0,3)+"."+str1.substring(3,6)+"."+str1.substring(6,9)+"-"+str1.substring(9,11);
        }
        else {
            alert("Informe corretamente o CPF.");
            obj.focus();
            return true;
        }
    }
    return false;
}

function ValidaCPF(str1){
    soma=0;
    if(str1.length == 11){
        if (str1 == "00000000000" || str1 == "11111111111" || str1 == "22222222222" || str1 == "33333333333" || str1 == "44444444444" || str1 == "55555555555" || str1 == "66666666666" || str1 == "77777777777" || str1 == "88888888888" || str1 == "99999999999"){
            return false;
        }
        for ( i=0; i < 9; i++)
            soma += (10 - i) * (str1.charAt(i));
        soma = 11 - (soma % 11);
        if (soma > 9)
            soma = 0;
        if (soma == (str1.charAt(9) )){
            soma = 0;
            for (i=0; i < 10; i++)
                soma += (11 - i) * (str1.charAt(i) );
            soma = 11 - (soma % 11);
            if (soma > 9) soma = 0;
            if (soma == (str1.charAt(10) ))
                return true;
        }
    }
    return false;
}

function erroFindString(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (obj.value.search("[%=><$]") < 0) {
        while (obj.value.search(" ") > 0)
            obj.value = obj.value.replace(" ","%");
        obj.value = "%"+obj.value+"%";
    }
    while (obj.value.search("'") > 0)
        obj.value = obj.value.replace("'","%");
    if (false) {
        alert("erro ???");
        obj.focus();
        return true;
    }
    return false;
}
function erroFindInt(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (/^[><]?[=]?[ ]?[0-9]+([<][=][ ]?[0-9]+)?$/.test(obj.value))
    {}
    else {
        alert("Informe em "+titulo+" algo como os exemplos:\n 1234;\n >1234;\n <5555;\n >=1234 <=5555");
        obj.focus();
        return true;
    }
    return false;
}
function erroFindBoolean(obj, titulo) {
    return false;
}
function erroFindFloat(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (false) {
        alert("erro ???");
        obj.focus();
        return true;
    }
    return false;
}
function erroFindDateTime(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (/^[><]?[=]?[ ]?([0-3][0-9][/][0-1][0-9][/][1-2][0-9]{3})([<][=][ ]?([0-3][0-9][/][0-1][0-9][/][1-2][0-9]{3}))?$/.test(obj.value))
    {}
    else {
        alert("Informe em "+titulo+" algo como o exemplo:\n 01/02/2010");
        obj.focus();
        return true;
    }
    return false;
}
function erroFindCpf(obj, titulo) {
    if (erroCpf(obj, "Não")) {
        obj.focus();
        return true;
    }
    return false;
}
function erroFindEmail(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (false) {
        alert("erro ???");
        obj.focus();
        return true;
    }
    return false;
}
function erroFindCEP(obj, titulo) {
    if (fLTrim(obj.value).length == 0)
        return false;
    if (false) {
        alert("erro ???");
        obj.focus();
        return true;
    }
    return false;
}
function Mover(pag) {
    if (pag != '0') {
        document.formFind.pagina_.value= pag;
        document.formFind.submit();
    }
}
function FindObjeto(n, d) {
    var p,i,x;
    if(!d)
        d=document;
    if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document;
        n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all)
        x=d.all[n];
    for (i=0;!x&&i<d.forms.length;i++)
        x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++)
        x=FindObjeto(n,d.layers[i].document);
    if(!x && d.getElementById)
        x=d.getElementById(n);
    return x;
}

function ModificarDadoP(id, valor) {
    obj=FindObjeto(id);
    if(document.all){
        obj.innerText = valor;
    } else{
        obj.textContent = valor;
    }
}

function MostrarTag(id) {
    obj=FindObjeto(id);
    if (obj.style.display == "")
        obj.style.display = "none";
    else
        obj.style.display = "";
}

function LZeros(text, tam) {
    while (text.length < tam)
        text = '0' + text;
    return text;
}

function Valor(numero, casas) {
    numero = Math.round(numero * Math.pow(10, casas)) / Math.pow(10, casas);
    if (numero < 0)
    {
        negativo = true;
        numero = numero * (-1);
    }
    else
        negativo = false;
    inteiro = parseInt(numero, 10);
    centavos = Math.round((numero - inteiro) * Math.pow(10, casas));
    i = 3;
    numero = '';
    inteiro = inteiro.toString();
    while (i < inteiro.length)
    {
        numero = '.' + inteiro.substr(inteiro.length - i, 3) + numero;
        i += 3;
    }
    numero = inteiro.substr(0, inteiro.length - i + 3) + numero;
    if (negativo)
        numero = '-' + numero;
    return (numero + ',' + Zeros(centavos.toString(), casas));
}

function ValidaMatricula(obj){
    str=obj.value;
    for(i=0;i<11;i++){
        str = str.replace( ".", "" );
        str = str.replace( ".", "" );
        str = str.replace( "-", "" );
    }
    num = str.substring(0, str.length - 1);
    dv = str.charAt(str.length - 1);
    if ((dv == calcDVMat(num)) || (str == 99999999))
        return true;
    else{
        alert('O Dígito Verificador da Matrícula é INVÁLIDO!');
        obj.value="";
        obj.focus();
        return false;
    }
}

function calcDVMat(pValor){
    var dv = 0;
    //Recebe o número da matrícula como string sem o DV
    var soma = 0;
    var mult = pValor.length + 1;
    for (i = 0;i<pValor.length;i++)
        soma += pValor.charAt(i) * mult--;
    dv = (soma * 10) % 11;
    dv = (dv==10)?0:dv;
    return dv;
}

function RetiraPercent(obj) {
    obj.value = obj.value.replace( "%", "" );
    obj.value = obj.value.replace( "%", "" );
    return;
}

function openEd(cod) {
    p = 'edit.jsp?campo='+cod+'&form1=fEdit';
    window.open(p,'Editor','width=1012px,height=660px,maximize=yes,scrollbars=yes,top=1,left=1');
}

//============ Editor ================//
var noOverwrite=false;
var alertText;
var txtarea = null;
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
    && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
var is_safari = ((clientPC.indexOf('AppleWebKit')!=-1) && (clientPC.indexOf('spoofer')==-1));
var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
if (clientPC.indexOf('opera')!=-1) {
    var is_opera = true;
    var is_opera_preseven = (window.opera && !document.childNodes);
    var is_opera_seven = (window.opera && document.childNodes);
}

function addButton(imageFile, speedTip, tagOpen, tagClose, sampleText) {

    speedTip=escapeQuotes(speedTip);
    tagOpen=escapeQuotes(tagOpen);
    tagClose=escapeQuotes(tagClose);
    sampleText=escapeQuotes(sampleText);
    var mouseOver="";

    // we can't change the selection, so we show example texts
    // when moving the mouse instead, until the first button is clicked
    if(!document.selection && !is_gecko) {
        // filter backslashes so it can be shown in the infobox
        var re=new RegExp("\\\\n","g");
        tagOpen=tagOpen.replace(re,"");
        tagClose=tagClose.replace(re,"");
        mouseOver = "onMouseover=\"if(!noOverwrite){document.infoform.infobox.value='"+tagOpen+sampleText+tagClose+"'};\"";
    }

    document.write("<a href=\"javascript:insertTags");
    document.write("('"+tagOpen+"','"+tagClose+"','"+sampleText+"');\">");

    document.write("<img width=\"23\" height=\"22\" src=\""+imageFile+"\" border=\"0\" alt=\""+speedTip+"\" title=\""+speedTip+"\""+mouseOver+">");
    document.write("</a>");
    return;
}

function addInfobox(infoText,text_alert) {
    alertText=text_alert;
    var clientPC = navigator.userAgent.toLowerCase(); // Get client info

    var re=new RegExp("\\\\n","g");
    alertText=alertText.replace(re,"\n");

    // if no support for changing selection, add a small copy & paste field
    // document.selection is an IE-only property. The full toolbar works in IE and
    // Gecko-based browsers.
    if(!document.selection && !is_gecko) {
        infoText=escapeQuotesHTML(infoText);
        document.write("<form name='infoform' id='infoform'>"+
            "<input size=80 id='infobox' name='infobox' value=\""+
            infoText+"\" READONLY></form>");
    }

}

function escapeQuotes(text) {
    var re=new RegExp("'","g");
    text=text.replace(re,"\\'");
    re=new RegExp('"',"g");
    text=text.replace(re,'&quot;');
    re=new RegExp("\\n","g");
    text=text.replace(re,"\\n");
    return text;
}

function escapeQuotesHTML(text) {
    var re=new RegExp('"',"g");
    text=text.replace(re,"&quot;");
    return text;
}

function inTxtArea(campo) {
    txtarea = campo;
}
// apply tagOpen/tagClose to selection in textarea,
// use sampleText instead of selection if there is none
// copied and adapted from phpBB
function insertTags(tagOpen, tagClose, sampleText) {

    if (txtarea != null){
        // IE
        if(document.selection  && !is_gecko) {
            var theSelection = document.selection.createRange().text;
            if(!theSelection) {
                theSelection=sampleText;
            }
            txtarea.focus();
            if(theSelection.charAt(theSelection.length - 1) == " "){// exclude ending space char, if any
                theSelection = theSelection.substring(0, theSelection.length - 1);
                document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
            } else {
                document.selection.createRange().text = tagOpen + theSelection + tagClose;
            }

        // Mozilla
        } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
            var startPos = txtarea.selectionStart;
            var endPos = txtarea.selectionEnd;
            var scrollTop=txtarea.scrollTop;
            var myText = (txtarea.value).substring(startPos, endPos);
            if(!myText) {
                myText=sampleText;
            }
            if(myText.charAt(myText.length - 1) == " "){ // exclude ending space char, if any
                subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
            } else {
                subst = tagOpen + myText + tagClose;
            }
            txtarea.value = txtarea.value.substring(0, startPos) + subst +
            txtarea.value.substring(endPos, txtarea.value.length);
            txtarea.focus();

            var cPos=startPos+(tagOpen.length+myText.length+tagClose.length);
            txtarea.selectionStart=cPos;
            txtarea.selectionEnd=cPos;
            txtarea.scrollTop=scrollTop;

        // All others
        } else {
            var copy_alertText=alertText;
            var re1=new RegExp("\\$1","g");
            var re2=new RegExp("\\$2","g");
            copy_alertText=copy_alertText.replace(re1,sampleText);
            copy_alertText=copy_alertText.replace(re2,tagOpen+sampleText+tagClose);
            var text;
            if (sampleText) {
                text=prompt(copy_alertText);
            } else {
                text="";
            }
            if(!text) {
                text=sampleText;
            }
            text=tagOpen+text+tagClose;
            document.infoform.infobox.value=text;
            // in Safari this causes scrolling
            if(!is_safari) {
                txtarea.focus();
            }
            noOverwrite=true;
        }
        // reposition cursor if possible
        if (txtarea.createTextRange) txtarea.caretPos = document.selection.createRange().duplicate();

    } else
        alert("Você não indicou o local para a cópia!")
}
//============ Editor ================//
