﻿function OpenModalDialog(url, btnName, widht, height) {
    var vReturnValue;

    if (url != null) {
        vReturnValue = window.showModalDialog(url, "#1", "dialogWidth:" + widht + "px; dialogHeight:" + height + "px; edge: Raised; center: Yes; help: No; resizable: No; status: No;");
    }
    else {
        alert("No URL passed to open");
    }
    if (vReturnValue != null && vReturnValue == true) {
        __doPostBack(btnName, '');
        return vReturnValue
    }
    else {
        return false;
    }
}

function clrObjText(vpobjeto, vpdefault) {
    var valor;
    valor = vpobjeto.value;

    if (typeof vpdefault == 'undefined' && vpdefault == null) {
        vpobjeto.value = '';
    } else {
        vpobjeto.value = vpdefault;
    }
    vpobjeto.disabled = 1;
    if (typeof vpobjeto.tag != 'undefined') { vpobjeto.tag = 0; }

    return valor;
}

function clrObjSelect(vpobjeto) {
    var valor;
    valor = vpobjeto.value;

    for (i = vpobjeto.options.length; i > 0; i--) {
        vpobjeto.options[i] = null;
    }
    vpobjeto.selectedIndex = 0;
    vpobjeto.disabled = 1;
    if (typeof vpobjeto.tag != 'undefined') { vpobjeto.tag = 0; }

    return valor;
}

function posObjSelect(vpobjeto, vpvalor) {
    var valor;
    valor = vpobjeto.value;

    for (i = 0; i < vpobjeto.options.length; i++) {
        if (vpobjeto.options[i].value == vpvalor) {
            vpobjeto.selectedIndex = i;
            return;
        }
    }
    vpobjeto.selectedIndex = 0;
}
var objBrow;
var ERRO = false;
var LAST_FIELD;
var CURRENT_FIELD = null;
var LAST_ERROR_FIELD = null;
var LAST_ERROR_VALUE = "";
var REPETITION_ERROR = false;

//CONSTANTES UTILIZADAS
SIZE_DATE = 10;
SIZE_CEP = 8
SIZE_ACCOUNT = 7;
SIZE_AG_ACCOUNT = 11;
MAX_NUMERIC = Number.MAX_VALUE;
SIZE_MONEY = 10;
SIZE_FLOAT = 10;
SIZE_CPF = 11;
SIZE_CNPJ = 14;
SIZE_PERCENT = 6;
SIZE_BRANCH = 4;
SIZE_MONTH_YEAR = 6;
SIZE_TIME = 4;
SIZE_PLACA = 7;
MAX_VALUE = 999999999.99

function validaConteudo(event, el, tipo) {
    var key;
    if (getObjBrow().isNetscape())
        key = String.fromCharCode(event.which);
    else
        key = String.fromCharCode(event.keyCode);
    if (getObjBrow().isNetscape() && event.which == 8)
        return true;
    if (isNNType(tipo, "money") || tipo == "percent" || isNNType(tipo, "float")) {
        if (isNumeric(key)) {
            return true;
        } else {
            if (key == ",")
                return (el.value.indexOf(",") == -1);
            else
                return false;
        }
        //Tipos livres de consistencia na digitacao
    } else if (tipo == "email" || tipo == "uppercase") {
        return true;
    } else if (tipo == "text") {
        return (isAlfa(key) || key == " " || key == "'");
    } else if (tipo == "alfanumeric") {
        return (isAlfaNumeric(key));
    } else {  // todos os outros tipos só aceitam números
        return isNumeric(key);
    }
}

function isUpper(key) {
    var ret = (key >= "A" && key <= "Z");
    return ret;
}

function unformatField(valor, tipo) {
    var type = "";
    var vr = String(valor);
    var ret = "";
    if (arguments.length < 1)
        type = new String("default");
    else
        type = new String(tipo);
    //-- Tipos que nao precisam de desformatacao --//
    if (type == "email" || type == "uppercase" || type == "alfanumeric" || type == "default")
        return valor;

    //--- Retira quaisquer formatacoes existentes no campo ---//
    var caracter = "", ok = false;
    for (i = 0; i < vr.length; i++) {
        caracter = vr.substring(i, i + 1);
        if (type != "text")
            ok = (caracter != '.' && caracter != '/' && caracter != '-' && caracter != ' ' && caracter != '%' && caracter != '(' && caracter != ')' && caracter != ':');
        else
            ok = isAlfa(caracter) || caracter == " " || caracter == "'";
        if (ok)
            ret += caracter;
    }
    return ret;
}

function removeCaracs(field, type) {
    var value = unformatField(field.value, type);
    if (field.value != value)
        field.value = unformatField(field.value, type);
    focusNetscape(field);
}

function focusNetscape(campo) {
    CURRENT_FIELD = campo;
    if (navigator.appName.indexOf("Netscape") != -1) {
        if (ERRO) {
            LAST_FIELD.focus();
            ERRO = false;
        }
    }
}

function formatDate(field, mensErro) {
    var valor = justNumbersStr(field.value);
    LAST_FIELD = field;
    var errMsg = "Data inválida. Digite novamente.";
    var dtObj = new DateValidation(field.value);
    if (!isNumeric(valor) || !dtObj.isDate()) {
        showError(errMsg, mensErro);
        focusCamp(field);
        return false;
    } else {
        field.value = dtObj.getDateValue();
    }
    ERRO = false;
    return true;
}

function formatTime(field, mensErro) {
    var valor = justNumbersStr(field.value);
    LAST_FIELD = field;
    var errMsg = "Hora inválida. Digite novamente.";
    switch (valor.length) {
        case 1: valor = "0" + valor + "00"; break;
        case 2: valor += "00"; break;
        case 3: valor = "0" + valor + "0"; break;
    }

    valor = repeatStr(valor, "0", 4, "right");
    if (!isNumeric(valor) || !isTime(valor)) {
        showError(errMsg, mensErro);
        focusCamp(field);
        return false;
    }
    field.value = valor.substring(0, 2) + ":" + valor.substring(2, 4);
    ERRO = false;
    return true;
}

function isTime(time) {
    var re = /^([0-1]\d[0-5]\d)|(2[0-3][0-5]\d)$/;
    return re.test(time);
}

function formatAg_Account(campo, mensErro) {
    var valor = justNumbersStr(campo.value);
    var msgError = "Agência/Conta corrente incorretos. Digite novamente.";
    LAST_FIELD = campo;
    if (valor == "" || valor == null)
        return false;

    valor = justNumbersStr(valor);
    if (!isNumeric(valor) || (valor.length < SIZE_AG_ACCOUNT)) {
        showError(msgError, mensErro);
        focusCamp(campo);
        return false;
    }
    var temp = valor.substring(0, 4) + "-" + valor.substring(4, 9) + "-" + valor.substring(9, 11);
    campo.value = temp;
    ERRO = false;
    return true;
}

function formatAg_Savings(campo, mensErro) {
    var valor = campo.value;
    var msgError = "Agência/Conta poupança incorretos. Digite novamente.";
    LAST_FIELD = campo;
    if (valor == "" || valor == null)
        return false;
    valor = justNumbersStr(valor);
    if (!isNumeric(valor) || (valor.length < SIZE_AG_ACCOUNT)) {
        showError(msgError, mensErro);
        focusCamp(campo);
        return false;
    }
    var temp = valor.substring(0, 4) + "-" + valor.substring(4, 10) + "-" + valor.substring(10, 11);
    campo.value = temp;
    ERRO = false;
    return true;
}

function formatBranch(campo, mensErro) {
    var errMsg = "Agência inválida. Digite novamente.";
    var valor = campo.value;
    if (valor == "" || valor == null)
        return false;
    valor = justNumbersStr(valor);
    LAST_FIELD = campo;
    if (!isNumeric(valor) || (valor.length < SIZE_BRANCH)) {
        showError(errMsg, mensErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatAccount(campo, mensErro) {
    var errMsg = "Conta corrente inválida. Digite novamente.";
    var valor = campo.value;
    if (valor == "" || valor == null)
        return false;
    valor = justNumbersStr(valor);
    LAST_FIELD = campo;
    if (!isNumeric(valor) || (valor.length < SIZE_ACCOUNT)) {
        showError(errMsg, mensErro);
        focusCamp(campo);
        return false;
    }
    var temp = valor.substring(0, 5) + "-" + valor.substring(5, 7);
    campo.value = temp;
    ERRO = false;
    return true;
}

function formatCEP(campo, mensErro) {
    var valor = campo.value;
    if (valor == "" || valor == null)
        return false;
    valor = justNumbersStr(valor);
    var errMsg = "CEP inválido. Digite novamente.";
    LAST_FIELD = campo;
    if (!isNumeric(valor) || (valor.length != SIZE_CEP)) {
        showError(errMsg, mensErro);
        focusCamp(campo);
        return false;
    } else {
        var temp = valor.substring(0, 5) + "-" + valor.substring(5, 8);
        campo.value = temp;
    }
    ERRO = false;
    return true;
}

function formatPlaca(campo, mensErro) {
    var valor = campo.value;
    if (valor == "" || valor == null)
        return false;
    var valornumerico = justNumbersStr(valor);
    var valoralfa = campo.value.substring(0, 3);
    valor = valoralfa + valornumerico
    var errMsg = "Placa inválida. Digite novamente.";
    LAST_FIELD = campo;
    if (!isNumeric(valornumerico) || (valor.length != SIZE_PLACA) || !isAlfa(valoralfa)) {
        showError(errMsg, mensErro);
        focusCamp(campo);
        return false;
    } else {
        var temp = valoralfa + "-" + valornumerico
        campo.value = temp;
    }
    ERRO = false;
    return true;
}

function formatNumeric(campo, mensErro) {
    var msgError = "Valor inválido. Digite novamente.";
    var valor = campo.value;
    if (valor == "" || valor == null)
        return false;
    valor = justNumbersStr(valor);
    LAST_FIELD = campo;
    if (!isNumeric(valor)) {
        showError(msgError, mensErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatPercent(campo, mensErro) {
    return formatFloat(campo, mensErro, 2);
}

function formatEmail(campo, msgErro) {
    var errMsg = "E-mail incorreto. Digite novamente.";
    var email = trim(campo.value);
    LAST_FIELD = campo;

    if (email == "" || email == null)
        return false;
    if (!isEmail(email)) {
        showError(errMsg, msgErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatText(campo, msgErro) {
    var texto = new String(campo.value);
    LAST_FIELD = campo;
    if (texto == "" || texto == null)
        return false;
    if (!isAlfa(removeStr(texto, new Array(" ", "'")))) {
        showError("Valor inválido.\nPor favor, digite apenas letras neste campo.", msgErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatUpperCase(campo, msgErro) {
    var texto = String(campo.value);
    LAST_FIELD = campo;
    if (texto == "" || texto == null)
        return false;
    campo.value = texto.toUpperCase();
    ERRO = false;
    return true;
}

function formatFloat(field, mensErro, numdec) {
    var errMsg = "Valor inválido. Digite novamente.";
    var numDecimais = (numdec ? numdec : 2);
    var vr = toFloat(trim(field.value), numDecimais);
    LAST_FIELD = field;

    if (!isFloatNumber(vr)) {
        showError(errMsg, mensErro);
        focusCamp(field);
        return false;
    }
    field.value = vr;
    ERRO = false;
    return true;
}

function formatMoney(field, mensErro, numdec) {
    var errMsg = "Valor inválido. Digite novamente.";
    var numDecimais = (numdec ? numdec : 2);
    var vr = toFloat(trim(field.value), numDecimais);
    LAST_FIELD = field;

    if (!isFloatNumber(vr)) {
        showError(errMsg, mensErro);
        focusCamp(field);
        return false;
    } else {
        if (verifyMaxValue(vr)) {
            field.value = "0,00";
            ERRO = true;
            return false;
        }
    }

    // -- Codigo para formatacao do campo --
    var vraux = "", caracter = "";
    var posDec = vr.indexOf(",");
    var valorDec = vr.substring(posDec + 1);
    // Da dir. p/ esq. vai formatando o numero com separadores de milhar.
    for (i = posDec; i > 0; i--) {
        pos = i - posDec;
        if (i != posDec && (pos % 3 == 0))
            vraux += ".";
        vraux += vr.substring(i, i - 1);
    }
    vrfinal = invertStr(vraux);
    field.value = vrfinal + "," + valorDec;

    ERRO = false;
    return true;
}

function setMaxValue(value) {
    MAX_VALUE = value;
}

function verifyMaxValue(v) {
    var vr = String(v);
    if (vr.length > 0) {
        if (parseFloat(vr) > MAX_VALUE)
            return true;
    }
    return false;
}

function repeatNStr(value, num) {
    var ret = "";
    for (var i = 0; i < num; i++) ret += value;
    return ret;
}

function toFloat(src, numdec) {
    var source = trim(src);
    var tam = source.length;
    var posDec = source.indexOf(",");

    if (source.length == 0) source = "0"; // previne erro em valores vazios.

    /* Se nao tiver ponto decimal inclui zeros */
    if (posDec == -1)
        return removeStr(source, ".") + "," + repeatNStr("0", numdec);
    else {
        source = removeStr(source, ".");
        if (posDec == 0)                        // ponto decimal eh o primeiro?
            return "0" + source + repeatNStr("0", numdec + 1 - source.length);
        else {
            if ((posDec > tam - numdec - 1))         // Nao tem decimais suficientes?
                source += repeatNStr("0", posDec - (tam - numdec - 1));
            posDec = source.indexOf(",");
            return parseInt(source.substring(0, posDec), 10) + source.substring(posDec, posDec + numdec + 1);
        }
    }
}

function formatCPF(campo, mensErro) {
    var valor = repeatStr(justNumbersStr(campo.value), "0", SIZE_CPF);
    var msgError = "CPF inválido. Digite novamente.";
    LAST_FIELD = campo;
    if (valor == "" || valor == null)
        return false;
    if (!isCPF(valor)) {
        showError(msgError, mensErro);
        focusCamp(campo);
        return false;
    } else {
        var temp = new String("");
        temp = valor.substring(0, 3) + "." + valor.substring(3, 6) + "." + valor.substring(6, 9) + "-" + valor.substring(9, 11)
        campo.value = temp;
    }
    ERRO = false;
    return true;
}

function formatCNPJ(campo, mensErro) {
    var valor = repeatStr(justNumbersStr(campo.value), "0", SIZE_CNPJ);
    var msgError = "CNPJ inválido! Digite novamente.";
    LAST_FIELD = campo;

    if (valor == "" || valor == null)
        return false;

    if (!isCNPJ(valor)) {
        showError(msgError, mensErro);
        focusCamp(campo);
        return false;
    } else {
        var temp = new String("");
        temp = valor.substring(0, 2) + "." + valor.substring(2, 5) + "." + valor.substring(5, 8) + "/" + valor.substring(8, 12) + "-" + valor.substring(12, 14);
        campo.value = temp;
    }
    ERRO = false;
    return true;
}

function formatCPF_CNPJ(campo, mensErro) {
    var valor = justNumbersStr(campo.value);
    var msgErro;
    msgErro = mensErro ? mensErro : 'CPF/CNPJ inválido. Digite novamente.';
    if (valor.length <= SIZE_CPF)
        return formatCPF(campo, msgErro);
    else
        return formatCNPJ(campo, msgErro);
}

function formatInterval(campo, minimo, maximo, mensErro) {
    var valor = justNumbersStr(campo.value);
    var msgError = "Valor inválido. Digite novamente.";
    LAST_FIELD = campo;
    if (valor == "" || valor == null)
        return false;
    if (!isNumeric(campo.value)) {
        showMessage(msgError, mensErro);
        focusCamp(campo);
        return false;
    } else if ((parseInt(valor, 10) < minimo) || (parseInt(valor, 10) > maximo)) {
        showError("Valor inválido. Digite um valor entre " + minimo + " e " + maximo + ".", mensErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatMonthYear(campo, msgError) {
    valor = justNumbersStr(campo.value);
    LAST_FIELD = campo;

    var errMsg = "Mês e ano inválidos. Digite novamente.";
    if (valor == "" || valor == null)
        return false;
    if (!isNumeric(valor)) {
        showError(errMsg, msgError);
        focusCamp(campo);
        return false;
    } else {
        var vr = vr = "01" + valor;
        var dtObj = new DateValidation(vr);
        if (!dtObj.isDate()) {
            showError(errMsg, msgError);
            focusCamp(campo);
            return false;
        } else {
            campo.value = dtObj.getMonthDateValue();
        }
    }
    ERRO = false;
    return true;
}

function formatAlfaNumeric(campo, msgErro) {
    var texto = new String(campo.value);
    LAST_FIELD = campo;

    if (texto == "" || texto == null)
        return false;
    if (!isAlfaNumeric(texto)) {
        showError("Valor inválido.\nPor favor, digite apenas letras ou números neste campo.", msgErro);
        focusCamp(campo);
        return false;
    }
    ERRO = false;
    return true;
}

function formatCamp(campo, tipo, par1, par2, par3) {
    var numArgs = formatCamp.arguments.length;
    var ret = false;
    ERRO = false;
    var b = getObjBrow();
    //-- IE 4 apresenta problema de loop no onblur --// 
    if (b.isIE() && parseInt(b.getMajorver(), 10) < 5) {
        if (LAST_ERROR_FIELD == campo && LAST_ERROR_VALUE == campo.value) {
            REPETITION_ERROR = true;
        } else {
            LAST_ERROR_FIELD = campo;
            LAST_ERROR_VALUE = campo.value;
            REPETITION_ERROR = false;
        }
    }
    if (isFieldEmpty(campo, tipo))
        return false;
    if (numArgs == 2)
        par1 = "";
    if (tipo == "account")
        ret = formatAccount(campo, par1);
    else if (tipo == "branch")
        ret = formatBranch(campo, par1);
    else if (tipo == "ag_account")
        ret = formatAg_Account(campo, par1);
    else if (tipo == "ag_savings")
        ret = formatAg_Savings(campo, par1);
    else if (tipo == "cpf")
        ret = formatCPF(campo, par1);
    else if (tipo == "cnpj")
        ret = formatCNPJ(campo, par1);
    else if (tipo == "cpf_cnpj")
        ret = formatCPF_CNPJ(campo, par1);
    else if (tipo == "date")
        ret = formatDate(campo, par1);
    else if (tipo == "time")
        ret = formatTime(campo, par1);
    else if (isNNType(tipo, "money"))
        ret = formatMoney(campo, par1, parseInt(tipo.substring(5), 10));
    else if (isNNType(tipo, "float"))
        ret = formatFloat(campo, par1, parseInt(tipo.substring(5), 10));
    else if (tipo == "numeric")
        ret = formatNumeric(campo, par1);
    else if (tipo == "cep")
        ret = formatCEP(campo, par1);
    else if (tipo == "placa")
        ret = formatPlaca(campo, par1);
    else if (tipo == "email")
        ret = formatEmail(campo, par1);
    else if (tipo == "percent")
        ret = formatPercent(campo, par1);
    else if (tipo == "month_year")
        ret = formatMonthYear(campo);
    else if (tipo == "interval") {
        if (numArgs <= 4)
            par3 = "";
        ret = formatInterval(campo, par1, par2, par3);
    }
    else if (tipo == "text")
        ret = formatText(campo, par1);
    else if (tipo == "uppercase")
        ret = formatUpperCase(campo, par1);
    else if (tipo == "alfanumeric")
        ret = formatAlfaNumeric(campo, par1);
    else
        alert("Tipo passado para formatação é inválido: " + tipo);
    //-- Controlando problema com onblur no IE 4 --// 
    if (b.isIE() && parseInt(b.getMajorver(), 10) < 5) {
        if (REPETITION_ERROR) {
            campo.value = "";
            REPETITION_ERROR = false;
            ret = false;
        }
        if (!ERRO) {
            LAST_ERROR_FIELD = null;
            LAST_ERROR_VALUE = "";
        }
    }
    return ret;
}

function isFieldEmpty(field, type) {
    var empty = false;
    var value

    if (field) {
        value = trim(field.value);
        if (!field || value.length == 0)
            empty = true;
        if (isNNType(type, "money")) {
            if (empty) {
                field.value = "0,00";
                empty = true;
            }
        }
    } else {
        empty = true;
    }
    return empty;
}

function saltaCampo(evento, field, tipo, tamanho) {
    var tecla;
    var maxSize;
    var fieldSize;
    if (isNNType(tipo, "float")) tipo = "float";
    if (isNNType(tipo, "money")) tipo = "money";

    switch (tipo) {
        case "date": maxSize = SIZE_DATE; break;
        case "time": maxSize = SIZE_TIME; break;
        case "cpf": maxSize = SIZE_CPF; break;
        case "cnpj": maxSize = SIZE_CNPJ; break;
        case "cpf_cnpj": maxSize = SIZE_CNPJ; break;
        case "cep": maxSize = SIZE_CEP; break;
        case "account": maxSize = SIZE_ACCOUNT; break;
        case "branch": maxSize = SIZE_BRANCH; break;
        case "percent": maxSize = SIZE_PERCENT; break;
        case "ag_account":
        case "ag_savings":
            maxSize = SIZE_AG_ACCOUNT; break;
        case "month_year": maxSize = SIZE_MONTH_YEAR; break;
        case "float":
            if (saltaCampo.arguments.length > 3)  // Tamanho foi informado?
                maxSize = tamanho;
            else
                maxSize = SIZE_FLOAT;
            break;
        case "money":
            if (!verifyMaxValue(field.value)) {
                if (saltaCampo.arguments.length > 3)  // Tamanho foi informado?
                    maxSize = tamanho;
                else
                    maxSize = SIZE_MONEY;
            } else {
                field.value = "0,00";
            }
            break;
        case "text":
        case "uppercase":
        case "interval":
        case "alfanumeric":
        case "default":
        case "numeric":
        case "email":
            maxSize = tamanho;
    }
    (getObjBrow().isNetscape()) ? tecla = evento.which : tecla = evento.keyCode;
    fieldSize = String(field.value).length;
    if (fieldSize >= maxSize && tecla >= 48) {
        autoSkip(field);
        return true;
    } else return false;
}

function showError(msgInfra, msgUsuario) {
    ERRO = true;
    if (typeof msgUsuario != "undefined" && msgUsuario != "" && msgUsuario != null)
        alert(msgUsuario);
    else
        alert(msgInfra);
}

function focusCamp(campo) {
    if (getObjBrow().isNetscape())
        campo.value = "";
    else
        campo.focus();
    ERRO = true;
}

function getObjBrow() {
    if (typeof objBrow != "object")
        objBrow = new Browser();
    return objBrow;
}

function unformatFields() {
    var field = null;
    var form = null;
    for (var c = 0; c < arguments.length; c++) {
        var form = arguments[c];
        if (!form || (typeof form != "object")) {
            alert("Argument " + (c + 1) + " is not a form object!");
            return;
        }
        for (var i = 0; i < form.length; i++) {
            field = form.elements[i];
            var type = "";
            if (field.type == "text") {
                type = getValidationType(field);
                if (type) {
                    valor = unformatField(field.value, type);
                    field.value = (!valor ? "" : valor);
                }
            }
        }
    }
}

function getValidationType(field) {
    if (!field.onblur) return null;
    var blurCode = changeStr(removeStr(field.onblur.toString(), " "), "\'", "\"");
    blurCode = removeStr(removeStr(blurCode, "\n"), "\t").toLowerCase();
    var re = /^.*formatcamp\((.*)\).*$/;
    var result = (re.exec(blurCode))[1];
    return (result.split("\"")[1]);
}

function isNNType(fieldType, type) {
    return (fieldType.indexOf(type) == 0);
}


function ValidaTeclaInteiro() {
    var strTecla = String.fromCharCode(event.keyCode);
    var blnRetorno = ValidaDigitoInteiro(strTecla);
    event.returnValue = blnRetorno;
}

function ValidaDigitoInteiro(strCaracter) {
    return ("0123456789".indexOf(strCaracter) >= 0);
}


function ValidaPasteInteiro(objCampo) {
    var strTexto = RetornaClipBoard();
    LimpaClipBoard();
    if (strTexto != '') {
        strTexto = SoNumero(strTexto);
        if (objCampo.maxLength > 0) {
            if (objCampo.maxLength >= strTexto.length) {
                objCampo.value = strTexto;
            }
            else {
                objCampo.value = strTexto.substr(0, objCampo.maxLength);
            }
        }
        else {
            objCampo.value = strTexto;
        }
    }
}

function RetornaClipBoard() {
    return (window.clipboardData.getData('Text')).replace(/\t/g, '');
}

function LimpaClipBoard() {
    return window.clipboardData.setData('Text', '');
}

function SoNumero(strTexto) {
    var intContador;
    var strRetorno;
    strRetorno = '';
    for (intContador = 0; intContador < strTexto.length; intContador++) {
        if (!isNaN(strTexto.substr(intContador, 1)) && strTexto.substr(intContador, 1) != ' ')
            strRetorno = strRetorno + strTexto.substr(intContador, 1);
    }
    return strRetorno;
}

function DesformataCNPJ_CPF(strDocumento) {
    var lngTamString;
    var bytAuxCont;
    strDocumento = strDocumento.replace(".", "");
    strDocumento = strDocumento.replace(".", "");
    strDocumento = strDocumento.replace("/", "");
    strDocumento = strDocumento.replace("-", "");
    return strDocumento;
}

function Verifica_CPFouCNPJ(CPFouCNPJ) {
    if (CPFouCNPJ.value.length > 11) {
        return ValidaCNPJ(CPFouCNPJ);
    }

    else {
        return ValidaCPF(CPFouCNPJ);
    }
}

function ValidaCNPJ(objCampo) {
    objCampo.value = DesformataCNPJ_CPF(objCampo.value);
    if (objCampo.value.length > 0) {
        if (objCampo.value.length != 14) {
            alert("CNPJ inválido !");
            objCampo.focus();
            objCampo.select();
            return false;
        }
        else {
            if (ConsistirCNPJ_CPF(objCampo.value) != 0) {
                objCampo.value = FormataCNPJ(objCampo.value);
            }
            else {
                alert("CNPJ inválido !")
                objCampo.focus();
                objCampo.select();
                return false;
            }
        }
    }
}

function ValidaCPF(objCampo) {
    objCampo.value = DesformataCNPJ_CPF(objCampo.value);
    if (objCampo.value.length > 0) {
        if (objCampo.value.length != 11) {
            alert("CPF inválido !");
            objCampo.focus();
            objCampo.select();
            return false;
        }
        else {
            if (ConsistirCNPJ_CPF(objCampo.value) != 0) {
                objCampo.value = FormataCPF(objCampo.value);
            }
            else {
                alert("CPF inválido !")
                objCampo.focus();
                objCampo.select();
                return false;
            }
        }
    }
}

/*function ConsistirCNPJ_CPF(strDocumento) 
{ 
var va_digito; 
var numero = new Array(15); 
var va_resto; 
var va_resultado; 
var as_somadigito10; 
va_cnpj_cpf = strDocumento; 
if (strDocumento.length != 14) 
{ 
var tam_cgc_cpf = strDocumento.length; 
for (tam_cgc_cpf; tam_cgc_cpf < 14; tam_cgc_cpf++) 
{ 
va_cnpj_cpf = '0' + va_cnpj_cpf; 
} 
} 
va_digito = va_cnpj_cpf.substring(13,2); 
numero[1] = parseInt(va_cnpj_cpf.substr(0,1)); 
numero[2] = parseInt(va_cnpj_cpf.substr(1,1)); 
numero[3] = parseInt(va_cnpj_cpf.substr(2,1)); 
numero[4] = parseInt(va_cnpj_cpf.substr(3,1)); 
numero[5] = parseInt(va_cnpj_cpf.substr(4,1)); 
numero[6] = parseInt(va_cnpj_cpf.substr(5,1)); 
numero[7] = parseInt(va_cnpj_cpf.substr(6,1)); 
numero[8] = parseInt(va_cnpj_cpf.substr(7,1)); 
numero[9] = parseInt(va_cnpj_cpf.substr(8,1)); 
numero[10] = parseInt(va_cnpj_cpf.substr(9,1)); 
numero[11] = parseInt(va_cnpj_cpf.substr(10,1)); 
numero[12] = parseInt(va_cnpj_cpf.substr(11,1)); 
numero[13] = parseInt(va_cnpj_cpf.substr(12,1)); 
numero[14] = parseInt(va_cnpj_cpf.substr(13,1)); 
if (strDocumento.length > 11) 
{ 
if (parseInt(va_cnpj_cpf.substr(0,8)) == 0 || parseInt(va_cnpj_cpf.substr(8,4)) == 0) 
{ 
return false; 
} 
va_resultado = (numero[1]*5) + (numero[2]*4) + (numero[3]*3) + (numero[4]*2) + (numero[5]*9) + (numero[6]*8) + (numero[7]*7) + (numero[8]*6) + (numero[9]*5) + (numero[10]*4) + (numero[11]*3) + (numero[12]*2); 
} 
else 
{ 
if (parseInt(va_cnpj_cpf.substr(0,9)) == 0) 
{ 
return false; 
} 
va_resultado = (numero[4]*10) + (numero[5]*9) + (numero[6]*8) + (numero[7]*7) + (numero[8]*6) + (numero[9]*5) + (numero[10]*4) + (numero[11]*3) + (numero[12]*2); 
} 
va_resto = 11 - (va_resultado % 11); 
if (va_resto > 9) 
{ 
va_resto = 0; 
} 
if (va_resto != numero[13]) 
{ 
return false; 
} 
if (strDocumento.length > 11) 
{ 
va_resultado = (numero[1]*6) + (numero[2]*5) + (numero[3]*4) + (numero[4]*3) + (numero[5]*2) + (numero[6]*9) + (numero[7]*8) + (numero[8]*7) + (numero[9]*6) + (numero[10]*5) + (numero[11]*4) + (numero[12]*3) + (numero[13]*2); 
} 
else 
{ 
va_resultado = (numero[4]*11) + (numero[5]*10) + (numero[6]*9) + (numero[7]*8) + (numero[8]*7) + (numero[9]*6) + (numero[10]*5) + (numero[11]*4) + (numero[12]*3) + (numero[13]*2); 
} 
va_resto = 11 - (va_resultado % 11); 
if (va_resto > 9) 
{ 
va_resto = 0; 
} 
if (va_resto != numero[14]) 
{ 
return false; 
} 
if (strDocumento.length > 11) 
{ 
return 1; 
} 
else 
{ 
return 2; 
} 
} */

function ConsistirCNPJ_CPF(strDocumento) {
    if (strDocumento.length <= 11) {
        return cpf(strDocumento);
    } else {
        return cnpj(strDocumento);
    }
}

function FormataCPF(strCPF) {
    if (strCPF.length == 0) {
        return "";
    }
    var bytAuxCont;
    var bytTamStr;
    var strResultado = '';
    if (strCPF.length > 11) {
        strCPF = strCPF.substr(0, 11);
    }
    else {
        if (strCPF.length < 11) {
            bytTamStr = 11 - strCPF.length;
            for (bytAuxCont = 1; bytAuxCont <= bytTamStr; bytAuxCont++) {
                strCPF = '0' + strCPF;
            }
        }
    }
    for (bytAuxCont = 0; bytAuxCont <= 12; bytAuxCont++) {
        if (bytAuxCont == 3 | bytAuxCont == 6) {
            strResultado = strResultado + '.';
        }
        if (bytAuxCont == 9) {
            strResultado = strResultado + '-';
        }
        strResultado = strResultado + strCPF.substr(bytAuxCont, 1);
    }
    return strResultado;
}

function FormataCNPJ(strCNPJ) {
    if (strCNPJ.length == 0) {
        return "";
    }
    var bytAuxCont;
    var bytTamStr;
    var strResultado = '';
    if (strCNPJ.length > 14) {
        strCNPJ = strCNPJ.substr(0, 14);
    }
    else {
        if (strCNPJ.length < 14) {
            bytTamStr = 14 - strCNPJ.length;
            for (bytAuxCont = 1; bytAuxCont <= bytTamStr; bytAuxCont++) {
                strCNPJ = '0' + strCNPJ;
            }
        }
    }
    for (bytAuxCont = 0; bytAuxCont <= 13; bytAuxCont++) {
        if (bytAuxCont == 2 | bytAuxCont == 5) {
            strResultado = strResultado + '.';
        }
        if (bytAuxCont == 8) {
            strResultado = strResultado + '/';
        }
        if (bytAuxCont == 12) {
            strResultado = strResultado + '-';
        }
        strResultado = strResultado + strCNPJ.substr(bytAuxCont, 1);
    }
    return strResultado;
}

function fncValidaData(strForm, strData) {
    var vpData = eval(strForm + '.' + strData)
    if (fvalidadata(vpData) != true) {
        alert(' Data inválida !')
        vpData.value = '';
        vpData.focus();
        return false;
    }
}
function cpf(cpfNum) {

    if (cpfNum.length != 11) { return false; }

    Digitos = cpfNum.substring(9);
    cpfNum = cpfNum.substring(0, 9);

    cpfDig1 = cpfNum.slice(8); a1 = eval(cpfDig1);
    cpfDig2 = cpfNum.slice(7, 8); a2 = eval(cpfDig2);
    cpfDig3 = cpfNum.slice(6, 7); a3 = eval(cpfDig3);
    cpfDig4 = cpfNum.slice(5, 6); a4 = eval(cpfDig4);
    cpfDig5 = cpfNum.slice(4, 5); a5 = eval(cpfDig5);
    cpfDig6 = cpfNum.slice(3, 4); a6 = eval(cpfDig6);
    cpfDig7 = cpfNum.slice(2, 3); a7 = eval(cpfDig7);
    cpfDig8 = cpfNum.slice(1, 2); a8 = eval(cpfDig8);
    cpfDig9 = cpfNum.slice(0, 1); a9 = eval(cpfDig9);

    cpfPriDig = (a1 * 9 + a2 * 8 + a3 * 7 + a4 * 6 + a5 * 5 + a6 * 4 + a7 * 3 + a8 * 2 + a9) % 11;
    if (cpfPriDig == 10) { cpfPriDig = 0; }
    cpfSegDig = (cpfPriDig * 9 + a1 * 8 + a2 * 7 + a3 * 6 + a4 * 5 + a5 * 4 + a6 * 3 + a7 * 2 + a8) % 11;
    if (cpfSegDig == 10) { cpfSegDig = 0; }
    cpfDV = cpfPriDig * 10 + cpfSegDig;
    if (cpfDV == 0) { cpfDV = "00"; }
    if (cpfDV > 0 && cpfDV < 10) { cpfDV = "0" + cpfDV; }

    return (Digitos == cpfDV);
}


function cnpj(cgcNum) {
    if (cgcNum.length != 14) { return false; }

    Digitos = cgcNum.substring(12);
    cgcNum = cgcNum.substring(0, 12);

    cgcDig1 = cgcNum.slice(11); b1 = eval(cgcDig1);
    cgcDig2 = cgcNum.slice(10, 11); b2 = eval(cgcDig2);
    cgcDig3 = cgcNum.slice(9, 10); b3 = eval(cgcDig3);
    cgcDig4 = cgcNum.slice(8, 9); b4 = eval(cgcDig4);
    cgcDig5 = cgcNum.slice(7, 8); b5 = eval(cgcDig5);
    cgcDig6 = cgcNum.slice(6, 7); b6 = eval(cgcDig6);
    cgcDig7 = cgcNum.slice(5, 6); b7 = eval(cgcDig7);
    cgcDig8 = cgcNum.slice(4, 5); b8 = eval(cgcDig8);
    cgcDig9 = cgcNum.slice(3, 4); b9 = eval(cgcDig9);
    cgcDig10 = cgcNum.slice(2, 3); b10 = eval(cgcDig10);
    cgcDig11 = cgcNum.slice(1, 2); b11 = eval(cgcDig11);
    cgcDig12 = cgcNum.slice(0, 1); b12 = eval(cgcDig12);


    //cgcPriDig=(b1*9+b2*8+b3*7+b4*6+b5*5+b6*4+b7*3+b8*2+b9*9+b10*8+b11*7+b12*6)%11;
    d1 = (b1 * 2 + b2 * 3 + b3 * 4 + b4 * 5 + b5 * 6 + b6 * 7 + b7 * 8 + b8 * 9 + b9 * 2 + b10 * 3 + b11 * 4 + b12 * 5)
    d1 = 11 - (d1 % 11);
    if (d1 >= 10) d1 = 0;
    d2 = d1 * 2 + b1 * 3 + b2 * 4 + b3 * 5 + b4 * 6 + b5 * 7 + b6 * 8 + b7 * 9 + b8 * 2 + b9 * 3 + b10 * 4 + b11 * 5 + b12 * 6;
    d2 = 11 - (d2 % 11);
    if (d2 >= 10) d2 = 0;
    cgcDV = new String(d1) + new String(d2);
    return (Digitos == cgcDV);
}
/*	DETECT.JS  -> Deteccao do browser do cliente
Ver documentacao em ./doc/detect.txt
*/
function Browser() {
    this.name = "Unknown";
    this.platform = "Unknown";
    this.version = "";
    this.majorver = "";
    this.minorver = "";
    this.init = Init;
    this.getName = GetName;
    this.getMinorver = GetMinorver;
    this.getMajorver = GetMajorver;
    this.getVersion = GetVersion;
    this.getPlatform = GetPlatform;
    this.isIE = IsIE;
    this.isNetscape = IsNetscape;
    this.isWindows = IsWindows;
    this.isWinNT = IsWinNT;
    this.isWin95 = IsWin95;
    this.isWin98 = IsWin98;
    this.isLinux = IsLinux;
    this.isMac = IsMac;
    this.init();
}

function Init() {
    var ua = navigator.userAgent;

    uaLen = ua.length;

    //separa o que vem antes do parentesis do que esta
    //dentro do parentesis
    var preparens = new String("");
    var parenthesized = new String("");

    i = ua.indexOf("(");

    if (i >= 0) {
        preparens = removeSpc(ua.substring(0, i));
        parenthesized = ua.substring(i + 1, uaLen);
        j = parenthesized.indexOf(")");
        if (j >= 0)
            parenthesized = parenthesized.substring(0, j);
    }
    else
        preparens = ua;
    //primeiro assume que a versao e o browser estao em preparens
    //depois, sobrescrevemos se encontrarmos em parenthesized
    var browVer = preparens;
    var s = new String(parenthesized);
    var tokens = new Array;
    tokens = s.split(";");
    var token = "";
    //Tratamento dos Tokens em parenthesized
    for (var i = 0; i < tokens.length; i++) {
        token = removeSpc(tokens[i]);
        //compatible - nao aparece no netscape
        if (token == "compatible") {
            //se este string esta na primeira posicao de tokens, 
            //entao a versao do browser aparecera em uma posicao
            //subsequente, dessa forma ignoramos este token.
        }
        else if (token.indexOf("MSIE") >= 0) {
            browVer = token;
        } else if (token.indexOf("Opera") >= 0) {
            browVer = token;
        }
        //plataforma: testamos para X11, SunOS, Win, Mac, PPC
        else if ((token.indexOf("X11") >= 0) || (token.indexOf("SunOS") >= 0) || (token.indexOf("Linux") >= 0)) {
            this.platform = "Unix";
        } else if (token.indexOf("Win") >= 0) {
            this.platform = token;
        } else if ((token.indexOf("Mac") >= 0) || (token.indexOf("PPC") >= 0)) {
            this.platform = token;
        }
    }
    var msieIndex = browVer.indexOf("MSIE");
    if (msieIndex >= 0) {
        browVer = browVer.substring(msieIndex, browVer.length);
    }
    var leftover = "";
    if (browVer.substring(0, "Mozilla".length) == "Mozilla") {
        this.name = "Netscape";
        leftover = browVer.substring("Mozilla".length + 1, browVer.length);
    }
    else if (browVer.substring(0, "Lynx".length) == "Lynx") {
        this.name = "Lynx";
        leftover = browVer.substring("Lynx".length + 1, browVer.length);
    }
    else if (browVer.substring(0, "MSIE".length) == "MSIE") {
        this.name = "IE";
        leftover = browVer.substring("MSIE".length + 1, browVer.length);
    }
    else if (browVer.substring(0, "Microsoft Internet Explorer".length) == "Microsoft Internet Explorer") {
        this.name = "IE"
        leftover = browVer.substring("Microsoft Internet Explorer".length + 1,
		browVer.length);
    }
    else if (browVer.substring(0, "Opera".length) == "Opera") {
        this.name = "Opera"
        leftover = browVer.substring("Opera".length + 1, browVer.length);
    }
    leftover = removeSpc(leftover);
    //tentamos pegar a versao fora do leftover
    i = leftover.indexOf(" ");
    if (i >= 0) {
        this.version = leftover.substring(0, i);
    }
    else {
        this.version = leftover;
    }
    j = this.version.indexOf(".");
    if (j >= 0) {
        this.majorver = this.version.substring(0, j);
        this.minorver = this.version.substring(j + 1, this.version.length);
    } else {
        this.majorver = this.version;
    }
} //Fim de Browser

function GetName() {
    return this.name;
}

function GetMajorver() {
    return this.majorver;
}

function GetMinorver() {
    return this.minorver;
}

function GetVersion() {
    return parseFloat(this.version, 10);
}

function GetPlatform() {
    return this.platform;
}

function IsIE() {
    return (this.name == 'IE');
}

function IsNetscape() {
    return (this.name == 'Netscape');
}

function IsWinNT() {
    return ((this.platform.indexOf('WinNT') != -1) || (this.platform.indexOf('Windows NT') != -1));
}

function IsWindows() {
    return ((this.platform.indexOf('Windows') != -1) || (this.platform.indexOf('WinNT') != -1));
}

function IsWin95() {
    return (this.platform.indexOf('Windows 95') != -1);
}

function IsWin98() {
    return (this.platform.indexOf('Windows 98') != -1);
}

function IsLinux() {
    return (this.platform.indexOf('Linux') != -1);
}

function IsMac() {
    return (this.platform.substring(0, 3) == 'Mac');
}

//----- funcoes internas auxiliares -----//

function push(item) {
    this[this.length] = item;
    return this.length;
}
Array.prototype.push = push;

function split(separador) {
    var retorno = new Array;
    var temp = new String("");
    if (this.length == 0) return null;
    for (var i = 0; i < this.length; i++) {
        var ch = this.substring(i, i + 1);
        if (ch == separador) {
            retorno.push(temp);
            temp = "";
        } else {
            temp += ch;
        }
    }
    retorno.push(temp);
    return retorno;
}
String.prototype.split = split;
//---------------------------------------//

function removeSpc(s) {
    var retVal = "";
    var start = 0;
    var str = String(s);
    if (str == null || str.length == 0)
        return "";
    while ((start < str.length) && (str.charAt(start) == ' ')) {
        ++start;
    }
    var end = str.length;
    while ((end > 0) && (str.charAt(end - 1) == ' ')) {
        --end;
    }
    retVal = str.substring(start, end);
    return retVal;
}

function popup(url, janela, atributos) {
    var w = window.open(url, janela, removeStr(atributos, " "));
}

function popupPrint(url, width, height) {
    var w, h;
    if (arguments.length < 2) {
        w = 640; h = 480;
    } else {
        w = width; h = height;
    }
    popup(url, 'PrintWind' + random(1, 9999), 'left=0,top=0,width=' + w + ',height=' + h + ',directories=no,location=no,menubar=no,resizable=no,scrollbars=yes,status=no');
}

function popupPrintAuto(arg1, arg2, arg3, arg4) {
    var print_logo, width, height, css;
    var nargs = arguments.length;

    if (arg1) {
        if (isNaN(parseInt(arg1, 10)))  // is not a number?
        {
            print_logo = arg1;
            width = arg2;
            if (arg3) height = arg3;
            if (arg4) css = arg4;
        } else {
            width = arg1;
            if (arg2) height = arg2;
            if (arg3) css = arg3;
        }
    }
    var b = new Browser();
    if (b.isIE()) {
        var pagePrintIE = "/ITE/common/print_ie/printIE.html?rand=" + random(1, 9999);
        if (print_logo)
            pagePrintIE = pagePrintIE + "&print_logo=" + print_logo;
        if (css)
            pagePrintIE = pagePrintIE + "&css=" + css;
        var call = "popupPrint(\"" + pagePrintIE + "\"" +
		        (arguments.length > 0 ? "," + width + "," + height : "") + ")";
        eval(call);
    } else {
        var href = String(document.location.href);
        /********************************************************/
        /* Codigo especifico para desenvolvimento via Transform */
        /********************************************************/
        var i;
        var pesq = "/ITE/servlets/Transform?xml=";
        if ((i = href.indexOf(pesq)) != -1) {
            var iXsl = href.indexOf("&xsl=");
            var change = href.substring(i + pesq.length, iXsl);
            href = changeStr(href, change, change + "_print");
            href = changeStr(href, ".xml_print", "_print.xml");
        }
        /***********************************************************/
        href += (href.indexOf("?") == -1) ? "?media=print" : "&media=print";
        var call = "popupPrint(\"" + href + "\"" +
		          (arguments.length > 0 ? "," + width + "," + height : "") + ")";
        eval(call);
    }
}

function random(r1, r2) {
    if (r2 > r1) return (Math.round(Math.random() * (r2 - r1)) + r1);
    else return (Math.round(Math.random() * (r1 - r2)) + r2);
}

function trim(s) {
    var retVal = "";
    var start = 0;
    var str = String(s);
    if (str == null || str.length == 0)
        return "";
    while ((start < str.length) && (str.charAt(start) == ' ')) {
        ++start;
    }
    var end = str.length;
    while ((end > 0) && (str.charAt(end - 1) == ' ')) {
        --end;
    }
    retVal = str.substring(start, end);
    return retVal;
}

function autoSkip(field, orientation) {
    var indCampo = -1;
    var form = field.form;
    // Obtendo posicao do campo no formulario
    for (i = 0; i < form.elements.length; i++) {
        if (field == form.elements[i]) {
            indCampo = i; break;
        }
    }
    focusCampByPos(form, indCampo, orientation);
}

function autoFocus(form) {
    var formulario = arguments.length == 0 ? document.forms[0] : form;
    focusCampByPos(formulario, -1);
}

function focusCampByPos(form, indCampo, orientation) {
    var orient = (orientation ? orientation : "down");
    var indNext = (orient == "down" ? 1 : -1);

    // Caso seja o ultimo componente nao foca em ninguem.
    if ((typeof form.elements[indCampo + indNext]) == "undefined") {
        if (indCampo != -1) form.elements[indCampo].blur();
        return;
    }
    //Procurando proximo campo para setar foco.
    for (i = indCampo + indNext; i < form.elements.length; i = i + indNext) {
        tipo = form.elements[i].type;
        if ((tipo == 'text' || tipo == 'password' || tipo == 'select-one') && !form.elements[i].disabled) {
            form.elements[i].focus();
            return;
        }
    }
    // Caso nao consiga focar em ninguem, sai do campo...
    form.elements[indCampo].blur();
}

function isNumeric(value) {
    var reNumeric = new RegExp("^[0-9]+$");
    return reNumeric.test(value);
}

function isAlfaNumeric(value) {
    return isAlfaOrAlfaNumeric(value, true);
}

function isAlfa(value) {
    return isAlfaOrAlfaNumeric(value, false);
}

function isAlfaOrAlfaNumeric(value, alfanumeric) {
    var valor = String(value);
    //--
    var acentosMinusc = 'áéíóúçãõâêôà';
    var acentosMaiusc = 'ÁÉÍÓÚÇÃÕÂÊÔÀ';
    var reNumeric = new RegExp("[0-9]");
    var reAlfa = new RegExp("[A-Za-z]");
    for (var i = 0; i < valor.length; i++) {
        var letra = new String(valor.charAt(i));
        if (!reAlfa.test(letra)) {
            if ((acentosMinusc.indexOf(letra) == -1) &&
				 (acentosMaiusc.indexOf(letra) == -1)) {
                if (alfanumeric) // Se tipo e' alfanumerico, ainda pode ser numero.
                {
                    if (!reNumeric.test(letra)) return false;
                } else return false;
            }
        }
    }
    return true;
}

function invertStr(str) {
    // Inverte o string S
    var temp = "";
    for (var i = 0; i < str.length; i++) {
        temp = str.charAt(i) + temp
    }
    return temp;
}

function removeStr(source, arg) {
    var ind, tam, values;
    var dst = String(source);
    if (typeof arg == "string")
        values = new Array(arg);
    else
        values = arg;
    for (var i = 0; i < values.length; i++) {
        tam = String(values[i]).length;
        while ((ind = dst.indexOf(values[i])) != -1)
            dst = dst.substring(0, ind) + dst.substring(ind + tam);
    }
    return dst;
}

function isFloatNumber(number) {
    var re = /^\d+(,\d+|\d*)$/;
    return re.test(number);
}

function repeatStr(source, str, size, direction) {
    var ret = String(source);
    if (!direction) direction = "left";
    //-- Preenche com a string "str" a esquerda --//
    while (ret.length < size) {
        if (String(direction).toLowerCase() == "right")
            ret += str;
        else
            ret = str + ret;
    }
    return ret;
}

function changeStr(source, strOrig, strDest) {
    var ind;
    var lastind = 0;
    var lengthOrig = String(strOrig).length;
    var dst = new String("");
    while ((ind = source.indexOf(strOrig, lastind)) != -1) {
        dst += (source.substring(lastind, ind) + strDest);
        lastind = ind + lengthOrig;
    }
    dst += source.substring(lastind);
    return dst;
}

function justNumbersStr(str) {
    // Deixa so' os digitos no numero
    var digitos = "0123456789";
    var temp = "";
    var digito = "";
    for (var i = 0; i < str.length; i++) {
        digito = str.charAt(i);
        if (digitos.indexOf(digito) != -1) {
            temp += digito;
        }
    }
    return temp;
}

function onlySameNumber(str) {
    var prim = str.charAt(0);
    var numbers = new String("0123456789");
    if (numbers.indexOf(prim) == -1)
        return false;
    for (var i = 1; i < str.length; i++) {
        if (str.charAt(i) != prim)
            return false;
    }
    return true;
}

function NumberTo(str) {
    var wrkCampo = '';
    var wrkCaracter = '';

    for (var i = 0; i < str.length; i++) {
        wrkCaracter = str.substring(i, i + 1);
        if (wrkCaracter == '.')
            continue;

        wrkCampo += wrkCaracter;
    }
    return (Number(virgulaToponto(wrkCampo)));
}

function FloatTo(str) {
    var wrkCampo = '';
    var wrkCaracter = '';

    for (var i = 0; i < str.length; i++) {
        wrkCaracter = str.substring(i, i + 1);
        if (wrkCaracter == '.') {
            wrkCaracter = '';
        }
        if (wrkCaracter == ',') {
            wrkCaracter = '.'
        }
        wrkCampo += wrkCaracter;
    }
    return wrkCampo;
}

function virgulaToponto(expr) {
    var localvir = expr.indexOf(',');
    if (localvir == -1) {
        return expr;
    } else {
        return expr.substring(0, localvir) + '.' + expr.substring(localvir + 1, expr.length);
    }
}

function pontoTovirgula(expr) {
    var localpt = expr.indexOf('.');
    if (localpt == -1) {
        return expr;
    } else {
        return expr.substring(0, localpt) + ',' + expr.substring(localpt + 1, expr.length);
    }
}
/**************************************************************
FormatNumber: Returns an expression formatted as a number.

Parameters:
Expression            = Expression to be formatted.
NumDigitsAfterDecimal = Numeric value indicating how
many places to the right of the
decimal are displayed.

Returns: String
***************************************************************/
function FormatNumber(Expression, NumDigitsAfterDecimal) {
    var iNumDecimals = NumDigitsAfterDecimal;
    var dbInVal = Expression;
    var bNegative = false;
    var iInVal = 0;
    var strInVal
    var strWhole = "", strDec = "";
    var strTemp = "", strOut = "";
    var iLen = 0;

    if (dbInVal < 0) {
        bNegative = true;
        dbInVal *= -1;
    }

    dbInVal = dbInVal * Math.pow(10, iNumDecimals)
    iInVal = parseInt(dbInVal);
    if ((dbInVal - iInVal) >= .5) {
        iInVal++;
    }
    strInVal = iInVal + "";
    strWhole = strInVal.substring(0, (strInVal.length - iNumDecimals));
    strDec = strInVal.substring((strInVal.length - iNumDecimals), strInVal.length);
    while (strDec.length < iNumDecimals) {
        strDec = "0" + strDec;
    }
    iLen = strWhole.length;

    if (iLen >= 3) {
        while (iLen > 0) {
            strTemp = strWhole.substring(iLen - 3, iLen);
            if (strTemp.length == 3) {
                strOut = "." + strTemp + strOut;
                iLen -= 3;
            }
            else {
                strOut = strTemp + strOut;
                iLen = 0;
            }
        }
        if (strOut.substring(0, 1) == ".") {
            strWhole = strOut.substring(1, strOut.length);
        }
        else {
            strWhole = strOut;
        }
    }

    if (bNegative) {
        return "-" + strWhole + "," + strDec;
    }
    else {
        return strWhole + "," + strDec;
    }
}
function DateValidation(dateSrc) {
    this.dtSrc = dateSrc;
    this.dtValue = "";
    this.isDate = _isDate;
    this.getDateValue = _getDateValue;
    this.getMonthDateValue = _getMonthDateValue;
}

function _getDateValue() { return (this.dtValue); }
function _getMonthDateValue() { return (String(this.dtValue).substring(3)); }

function _isDate() {
    var vr = trim(this.dtSrc);
    if (vr.length >= 6 && vr.length <= 10) {
        token = new Array();
        i = 0;
        j = 0;
        nBar = 0;
        nDig = 0;
        while (i < vr.length) {
            if (vr.substring(i, i + 1) >= '0' && vr.substring(i, i + 1) <= '9') {
                str = "" + vr.substring(i, i + 1);
                i++;
                while (vr.substring(i, i + 1) >= '0' && vr.substring(i, i + 1) <= '9' && i < vr.length) {
                    str = str + vr.substring(i, i + 1);
                    i++;
                }
                token[j] = str;
                j++;
                nDig++;
            } else if (vr.substring(i, i + 1) == "/") {
                str = "" + vr.substring(i, i + 1);
                token[j] = str;
                j++;
                i++;
                nBar++;
            } else {
                i++;
            }
        }
        //verifica quantas barras e digitos foram reconhecidos
        //nBar == 0 e nDig == 1  - formato 01012000
        //nBar == 2 e nDig == 3  - formato 01/10/2000
        //para quaisquer outros formatos não faz formatação, ocasionando em erro
        if ((nBar == 0 && nDig == 1) || (nBar == 2 && nDig == 3)) {
            if (token.length == 1) { //um token de tamanho minimo 6, maximo 8
                dia = token[0].substring(0, 2);
                mes = token[0].substring(2, 4);

                if (token[0].length == 6) {
                    if (eval(token[0].substring(4, 6)) < 30)
                        ano = "20" + token[0].substring(4, 6);
                    else
                        ano = "19" + token[0].substring(4, 6);
                }
                else
                    if (token[0].length == 8)
                    ano = token[0].substring(4, 8);
                else
                    ano = token[0].substring(4, token[0].length);

                //alert(dia + "/" + mes + "/" + ano);
                this.dtValue = dia + "/" + mes + "/" + ano;
            } else
                if (token.length == 5) { //5 tokens indicam data no formato dd/mm/aa
                if (token[0].length == 1 && eval(token[0]) < 10)
                    dia = "0" + token[0];
                else
                //pega os dois primeiros digitos e ignora o restante se houver
                    dia = token[0].substring(0, 2);
                barra1 = token[1]; //pega barra
                if (token[2].length == 1 && eval(token[2]) < 10)
                    mes = "0" + token[2];
                else
                //pega os dois primeiros digitos e ignora o restante se houver
                    mes = token[2].substring(0, 2);

                barra2 = token[3]; //pega barra

                if (token[4].length == 2) {
                    if (eval(token[4]) < 30)
                        ano = "20" + token[4];
                    else
                        ano = "19" + token[4];
                }
                else
                    ano = token[4];
                //alert(dia + barra1 + mes + barra2 + ano);
                this.dtValue = dia + barra1 + mes + barra2 + ano;
            }
        }
    }
    var err = 0;
    var psj = 0;

    if (this.dtValue.length != 10)
        err = 4;
    else {
        dia = this.dtValue.substring(0, 2); // day 
        barra1 = this.dtValue.substring(2, 3); // '/' 
        mes = this.dtValue.substring(3, 5); // month 
        barra2 = this.dtValue.substring(5, 6); // '/' 
        ano = this.dtValue.substring(6, 10); // year 
        //basic error checking 
        if (mes < 1 || mes > 12) err = 1;
        if (barra1 != '/') err = 4;
        if (dia < 1 || dia > 31) err = 2;
        if (barra2 != '/') err = 4
        if (ano < 1900 || ano > 2100) err = 3
        if (mes == 4 || mes == 6 || mes == 9 || mes == 11) {
            //advanced error checking 
            // months with 30 days 
            if (dia == 31) err = 4
        }
        if (mes == 2) {
            // february, leap year 
            var g = parseInt(ano / 4)
            if (isNaN(g)) {
                err = 4
            }
            if (dia > 29) err = 4
            if (dia == 29 && ((ano / 4) != parseInt(ano / 4))) err = 4
        }
    }
    if (err > 0)
        return false;
    else
        return true;
}

/*Objeto que contém métodos úteis para validação de datas*/
function DateObj(dt) {
    if (typeof (dt) == 'string' && dt.length == 10) {
        this.isValid = true;
        this.day = dt.substring(0, 2);
        this.month = dt.substring(3, 5);
        this.year = dt.substring(6, 10);
        this.daysTo = _DaysTo;
        this.lesserThan = _LesserThan;
    }
    else {
        this.isValid = false;
    }
}
function _LesserThan(dt) {
    var start = Number(this.year + this.month + this.day);
    var finish = Number(dt.year + dt.month + dt.day);
    if (start < finish) return true;
    else return false;
}
function _DaysTo(dt) {
    var msDay = 24 * 60 * 60 * 1000; //Milisegundo existentes em um dia
    var start = new Date(this.month + "/" + this.day + "/" + this.year);
    var finish = new Date(dt.month + "/" + dt.day + "/" + dt.year);
    var time = (finish.getTime() - start.getTime());
    return (Math.floor(time / msDay));
}
//Essa função verifica se duas datas são válidas, verificando se a primeira é  //
//maior que a segunda e se as duas estão dentro de um período pré determinado  //
function isInInterval(dtInicial, dtFinal, pInicial, pFinal) {
    var sDate = new DateObj(dtInicial);
    var fDate = new DateObj(dtFinal);
    var sPer = new DateObj(pInicial);
    var fPer = new DateObj(pFinal);
    if (sDate.isValid && fDate.isValid && sPer.isValid && fPer.isValid) {
        if (fDate.lesserThan(sDate)) {
            alert('Data inicial maior que a data final. Verifique!');
            return false;
        }
        else if (sDate.lesserThan(sPer) || fPer.lesserThan(fDate)) {
            alert('Data está fora do período disponível');
            return false;
        }
        return true;
    }
}
//Essa função verifica se o intervalo entre duas datas é igual ou inferior ao  //
//limite pré-determinado:                                                      //
function isInDaysLimit(dtInicial, dtFinal, dias) {
    var sDate = new DateObj(dtInicial);
    var fDate = new DateObj(dtFinal);
    if (sDate.isValid && fDate.isValid) {
        if ((sDate.daysTo(fDate) + 1) > dias) {
            alert('O intervalo é maior que o número de dias permitido para este relatório(' + dias + ' dias).');
            return false;
        }
        return true;
    }
}

function getNextYear(vpDate) {
    var myDate;
    var myDay;
    var myYear;
    var myMonth;

    if (vpDate != '') {
        if (vpDate.length == 8) {
            vpDate = vpDate.substr(0, 2) + '/' + vpDate.substr(2, 2) + '/' + vpDate.substr(4);
        }

        myDate = new DateObj(vpDate);
        myDay = parseFloat(myDate.day);
        myMonth = parseFloat(myDate.month);
        myYear = parseFloat(myDate.year) + 1;

        if (myDay == 29) {
            if (myMonth == 2) {
                myDay = '01';
                myMonth = 3;
            }
        }
        else if (myDay < 10) {
            myDay = '0' + myDay;
        }

        if (myMonth < 10) {
            myMonth = '0' + myMonth;
        }

        return myDay + '/' + myMonth + '/' + myYear;
    }
    else {
        return 0;
    }
}

function getNextMonth(vpDate) {
    var myDate;
    var myDay;
    var myYear;
    var myMonth;

    if (vpDate != '') {
        if (vpDate.length == 8) {
            vpDate = vpDate.substr(0, 2) + '/' + vpDate.substr(2, 2) + '/' + vpDate.substr(4);
        }

        myDate = new DateObj(vpDate);
        myDay = parseFloat(myDate.day);
        myMonth = parseFloat(myDate.month);
        myYear = parseFloat(myDate.year);

        switch (myMonth) {
            case 4:
            case 6:
            case 9:
            case 11:
                {
                    myMonth = myMonth + 1;
                    break;
                }
            case 2:
                {
                    if (myYear % 4 == 0) {
                        myDay++;
                    }
                    else {
                        myDay = myDay + 2;
                    }
                    myMonth = myMonth + 1;
                    break;
                }
            case 12:
                {
                    if (myDay == 1) {
                        myDay = 31;
                    }
                    else {
                        myDay--;
                        myMonth = 1;
                        myYear++;
                    }
                    break;
                }
            default:
                {
                    if (myDay == 1) {
                        myDay = 31;
                    }
                    else {
                        myDay--;
                        myMonth = myMonth + 1;
                    }
                }
        }
        if (myDay < 10) {
            myDay = '0' + myDay;
        }
        if (myMonth < 10) {
            myMonth = '0' + myMonth;
        }
        return myDay + '/' + myMonth + '/' + myYear;
    }
}

function getDays(vpDate, vpDays) {
    var myDays = 86400000 * vpDays;
    var myDate;
    var myDay;
    var myYear;
    var myMonth;

    if (vpDate.length == 8) {
        vpDate = vpDate.substr(0, 2) + '/' + vpDate.substr(2, 2) + '/' + vpDate.substr(4);
    }

    myDate = new Date(parseFloat(vpDate.substr(6)), parseFloat(vpDate.substr(3, 2)) - 1, parseFloat(vpDate.substr(0, 2)));
    myDate.setMilliseconds(myDays);
    myDay = myDate.getDate();

    myMonth = myDate.getMonth();
    myMonth++;

    myYear = myDate.getYear();

    if (myDay < 10) {
        myDay = '0' + myDay;
    }
    if (myMonth < 10) {
        myMonth = '0' + myMonth;
    }
    return myDay + '/' + myMonth + '/' + myYear;
} function conv_maiusculo(texto) {
    texto.value = texto.value.toUpperCase();
}

function conv_minusculo(texto) {
    texto.value = texto.value.toLowerCase();
}


function fncAbreJanela(oUrl, oWidth, oHeight) {
    //Variáveis para centralizar a tela
    var oTop = window.screen.availHeight
    var oLeft = window.screen.availwidth

    oTop = (oTop - oHeight) / 2
    oLeft = (oLeft - oWidth) / 2

    /*alert(oUrl)
    alert(oWidth)
    alert(oHeight)
    alert(oTop)
    alert(oLeft)*/

    window.open(oUrl, "LibertyAffinity", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=" + oTop + " ,left=" + oLeft + ",width=" + oWidth + ",height=" + oHeight)
}

function fncAbreDialogo(oUrl, oWidth, oHeight, oArgument) {
    var oRetorno

    return window.showModalDialog(oUrl, oArgument, "dialogHeight: " + oHeight + "; dialogWidth: " + oWidth + "; center: Yes; resizable: No; scroll: No; status: No;");
    //	oRetorno = window.showModalDialog(oUrl,oArgument,"dialogHeight: oHeight; dialogWidth: oHeight; dialogTop: px; dialogLeft: px; edge: Sunken; center: Yes; help: Yes; resizable: No; status: No;");
    //	window.open(oUrl,"LibertyAffinity","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=" + oTop +" ,left=" + oLeft + ",width="+ oWidth +",height=" + oHeight)
}

function fncAbreDialogoScroll(oUrl, oWidth, oHeight, oArgument) {
    var oRetorno

    return window.showModalDialog(oUrl, oArgument, "dialogHeight: " + oHeight + "; dialogWidth: " + oWidth + "; center: Yes; resizable: Yes;  status: No;");
    //	oRetorno = window.showModalDialog(oUrl,oArgument,"dialogHeight: oHeight; dialogWidth: oHeight; dialogTop: px; dialogLeft: px; edge: Sunken; center: Yes; help: Yes; resizable: No; status: No;");
    //	window.open(oUrl,"LibertyAffinity","toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=" + oTop +" ,left=" + oLeft + ",width="+ oWidth +",height=" + oHeight)
}

function confirmar(vpURL, vpMsg) {
    var objRetorno = false;
    objRetorno = fncAbreDialogo(vpURL, '450px', '160px', vpMsg);
    return objRetorno;
}

function fvalidadata(vpobjeto) {
    vdata = vpobjeto.value;
    var inum = '';
    var rstr = '0123456789';
    var itam = vdata.length;

    for (cont = 0; cont < vdata.length; cont++) {
        tchar = vdata.charAt(cont);
        if (rstr.indexOf(tchar) != -1)
            inum = inum + tchar;
    };

    itam = inum.length;
    if (itam != 8)
        return false;

    dia = inum.substring(0, 2);
    mes = inum.substring(2, 4);
    ano = inum.substring(4, 8);

    if ((mes < 1) || (mes > 12))
        return false;

    if ((dia < 1) || (dia > 31))
        return false;

    if ((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11))
        if (dia > 30) {
        return false;
    };

    if (mes == 2)
        if (((ano % 4) == 0) || ((ano % 4) == 100) || ((ano % 400) == 0)) {
        if (dia > 29)
            return false;
    }
    else {
        if (dia > 28)
            return false;
    };

    return true;
}

function InStr(String1, String2) {
    var a = 0;

    if (String1 == null || String2 == null)
    { return (false); }

    String1 = String1.toLowerCase();
    String2 = String2.toLowerCase();

    a = String1.indexOf(String2);
    if (a == -1)
    { return 0; }
    else
    { return a + 1; }
}
