var sessionId = sessionStorage.getItem("sessionId");
let editor;
let editor2;
window.onload = function () {

    ClassicEditor
        .create(document.querySelector('#editor'), {
            toolbar: ['bold', 'italic', 'underline', '|', 'alignment:left', 'alignment:center', 'alignment:justify', 'alignment:right', '|', 'numberedList', 'bulletedList', '|', 'heading'],
            language: 'es',
        })
        .then(ed => {
            editor = ed;
            const viewDocument = editor.editing.view.document;

            viewDocument.on('blur', (evt, data) => {
                saveTerms(editor.getData(), editor2.getData());
            });

        })
        .catch(error => console.error(error));

    ClassicEditor
        .create(document.querySelector('#editor2'), {
            toolbar: ['bold', 'italic', 'underline', '|', 'alignment:left', 'alignment:center', 'alignment:justify', 'alignment:right', '|', 'numberedList', 'bulletedList', '|', 'heading'],
            language: 'es',
        })
        .then(ed => {
            editor2 = ed;
            const viewDocument = editor2.editing.view.document;

            viewDocument.on('blur', (evt, data) => {
                saveTerms(editor.getData(), editor2.getData());
            });

        })
        .catch(error => console.error(error));

    document.getElementById('engTerms').addEventListener("click", function () {
        setLang("engTerms", "terms", 'right');
        document.getElementById('editor1esp').style.display = "none";
        document.getElementById('editor2eng').style.display = "block";
    });
    document.getElementById('espTerms').addEventListener("click", function () {
        setLang("espTerms", "terms", 'left');
        document.getElementById('editor2eng').style.display = "none";
        document.getElementById('editor1esp').style.display = "block";
    });

    initApp();
    changebutt();
    entryLevel();
}
function validChange() {

}
function savePmPref() {
    var par = {};
    var currid = 1; //Default 1 para cuando esté apagado
    var withdbanks = document.getElementsByClassName("switchWith");
    var withactv = 0;
    for (var x = 0; x < withdbanks.length; x++) {
        if (withdbanks[x].classList.contains("active")) withactv = withdbanks[x].getAttribute("bankid");
    }

    var depbanks = document.getElementsByClassName("switchDep");
    var depactv = 0;
    for (var x = 0; x < depbanks.length; x++) {
        if (depbanks[x].classList.contains("active")) {
            depactv = depbanks[x].getAttribute("bankid");
            currid = depbanks[x].parentElement.parentElement.parentElement.getAttribute("currid");
        }
    }

    par.withdrawalsbankinterface = withactv;
    par.depositsbankinterface = depactv;
    par.currencyid = currid;
    par.sessionid = sessionId;
    callWS("POST", "preferences/savepagomovil", par, rspUserSaveLevel);
    return 0;
}
//Esta función pinta la lista de bancos autorizados para los pago movil
function drawPmBanks(rsp) {
    var tbl = document.getElementById("pmBanksTbl");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var nwnode;
    var banks = rsp.banks;
    if (banks.length > 0) {
        clone.style.display = "";
        tbl.innerHTML = "";
        for (var i = 0; i < banks.length; i++) {
            for (var y = 0; y < banks[i].accepts.length; y++) {
                nwnode = clone.cloneNode(true);
                nwnode.getElementsByClassName("pmBankCell")[0].innerHTML = banks[i].name + " (" + banks[i].accepts[y].currency.name + ")";

                nwnode.setAttribute("currid", banks[i].accepts[y].currency.id);

                if (banks[i].active) {
                    if (banks[i].accepts[y].deposits) {
                        var switchs = nwnode.getElementsByClassName("switchDep");
                        for (var x = 0; x < switchs.length; x++) {
                            switchs[x].setAttribute("bankid", banks[i].id);
                            switchs[x].addEventListener("click", function () {
                                if (this.classList.contains("active")) {
                                    this.classList.remove("active");
                                    this.firstElementChild.classList.remove("balActive");
                                } else {
                                    //Siempre se blanquean todos y se marca el que se le da click, sólo puede haber uno marcado
                                    var all = document.getElementById("pmBanksTbl").getElementsByClassName("switchDep");
                                    for (var z = 0; z < all.length; z++) {
                                        all[z].classList.remove("active");
                                        all[z].firstElementChild.classList.remove("balActive");
                                    }
                                    this.classList.add("active");
                                    this.firstElementChild.classList.add("balActive");
                                }
                                savePmPref();
                            });
                            if (rsp.default[0].deposits == banks[i].id) {
                                switchs[x].classList.add("active");
                                switchs[x].firstElementChild.classList.add("balActive");
                            }
                        }
                    }
                    if (banks[i].accepts[y].withdrawals) {
                        var switchs = nwnode.getElementsByClassName("switchWith");
                        for (var x = 0; x < switchs.length; x++) {
                            switchs[x].setAttribute("bankid", banks[i].id);
                            switchs[x].addEventListener("click", function () {
                                if (this.classList.contains("active")) {
                                    this.classList.remove("active");
                                    this.firstElementChild.classList.remove("balActive");
                                } else {
                                    //Siempre se blanquean todos y se marca el que se le da click, sólo puede haber uno marcado
                                    var all = document.getElementById("pmBanksTbl").getElementsByClassName("switchWith");
                                    for (var z = 0; z < all.length; z++) {
                                        all[z].classList.remove("active");
                                        all[z].firstElementChild.classList.remove("balActive");
                                    }
                                    this.classList.add("active");
                                    this.firstElementChild.classList.add("balActive");
                                }
                                savePmPref();
                            });
                            if (rsp.default[0].withdrawals == banks[i].id) {
                                switchs[x].classList.add("active");
                                switchs[x].firstElementChild.classList.add("balActive");
                            }
                        }
                    }
                }
                tbl.appendChild(nwnode);
            }
        }
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
//Esta función pinta las preferencias de comisiones y topes para pago movil natural y jurídico por nivel 
//Recibe un arreglo con los niveles
function drawPmPrefs(rsp) {
    var tbl = document.getElementById("Section-pagomovil");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var levels = (rsp == null || rsp == undefined) ? [] : rsp;
    if (levels.length > 0) {
        var levelstbl = tbl.getElementsByClassName("currencybars1pm")[0];
        var clonelvl = levelstbl.children[0].cloneNode(true);
        levelstbl.innerHTML = "";

        var natmaxtbl = tbl.getElementsByClassName("maxLineBar")[1];
        var clonemax = natmaxtbl.children[0].cloneNode(true); //Se copia uno solo y se reutiliza la variable
        natmaxtbl.innerHTML = "";

        var jurmaxtbl = tbl.getElementsByClassName("maxLineBar")[3];
        jurmaxtbl.innerHTML = "";

        var natfeetbl = tbl.getElementsByClassName("maxLineBar")[0];
        var clonefee = natfeetbl.children[0].cloneNode(true);//Se copia uno solo y se reutiliza la variable
        natfeetbl.innerHTML = "";

        var jurfeetbl = tbl.getElementsByClassName("maxLineBar")[2];
        jurfeetbl.innerHTML = "";

        for (var i = 0; i < levels.length; i++) {
            //Levels
            nwlvl = clonelvl.cloneNode(true);
            nwlvl.innerHTML = levels[i].name;
            nwlvl.style.display = "";
            levelstbl.appendChild(nwlvl);

            //Max natural
            nwmax = clonemax.cloneNode(true);
            nwmax.style.display = "";
            nwmax.getElementsByTagName("input")[0].value = levels[i].pagomovil.natural.maxperday.formatted;
            nwmax.getElementsByTagName("input")[0].setAttribute("levelid", levels[i].level);
            var lvlrows = document.getElementById("Section-max").getElementsByClassName("maxpag");
            for (var x = 0; x < lvlrows.length; x++) {
                var lvlidrow = lvlrows[x].getElementsByClassName("levelCell")[0].getAttribute("levelid");
                if (lvlidrow == nwmax.getElementsByTagName("input")[0].getAttribute("levelid")) {
                    nwmax.getElementsByTagName("input")[0].setAttribute("lvlpos", x);
                    nwmax.getElementsByTagName("input")[0].setAttribute("id", "maxpmnatlvl" + x);
                }
            }
            var currmaxstbl = document.getElementById("Section-max").getElementsByClassName("currencybars1")[0];
            var currmaxs = currmaxstbl.getElementsByTagName("span");
            for (var x = 0; x < currmaxs.length; x++) {
                var currencies = currmaxs[x].getAttribute("currencyid");
                if (currencies == 1) {
                    nwmax.getElementsByTagName("input")[0].setAttribute("currpos", x);
                }

            }
            nwmax.getElementsByTagName("input")[0].setAttribute("dataNumber", levels[i].pagomovil.natural.maxperday.number);
            natmaxtbl.appendChild(nwmax);
            //----------------

            //Fee natural
            nwfee = clonefee.cloneNode(true);
            nwfee.style.display = "";
            nwfee.getElementsByTagName("input")[0].value = levels[i].pagomovil.natural.pctfee.formatted;
            nwfee.getElementsByTagName("input")[0].setAttribute("levelid", levels[i].level);
            var lvlrows = document.getElementById("Section-max").getElementsByClassName("maxpag");
            for (var x = 0; x < lvlrows.length; x++) {
                var lvlidrow = lvlrows[x].getElementsByClassName("levelCell")[0].getAttribute("levelid");
                if (lvlidrow == nwfee.getElementsByTagName("input")[0].getAttribute("levelid")) {
                    nwfee.getElementsByTagName("input")[0].setAttribute("lvlpos", x);
                    nwfee.getElementsByTagName("input")[0].setAttribute("id", "feepmnatlvl" + x);
                }
            }
            var currmaxstbl = document.getElementById("Section-max").getElementsByClassName("currencybars1")[0];
            var currmaxs = currmaxstbl.getElementsByTagName("span");
            for (var x = 0; x < currmaxs.length; x++) {
                var currencies = currmaxs[x].getAttribute("currencyid");
                if (currencies == 1) {
                    nwfee.getElementsByTagName("input")[0].setAttribute("currpos", x);
                }
            }
            nwfee.getElementsByTagName("input")[0].setAttribute("dataNumber", levels[i].pagomovil.natural.pctfee.number);
            natfeetbl.appendChild(nwfee);
            //-----------------

            //Max jurídico
            nwmax = clonemax.cloneNode(true);
            nwmax.style.display = "";
            nwmax.getElementsByTagName("input")[0].value = levels[i].pagomovil.juridic.maxperday.formatted;
            nwmax.getElementsByTagName("input")[0].setAttribute("levelid", levels[i].level);
            var lvlrows = document.getElementById("Section-max").getElementsByClassName("maxpag");
            for (var x = 0; x < lvlrows.length; x++) {
                var lvlidrow = lvlrows[x].getElementsByClassName("levelCell")[0].getAttribute("levelid");
                if (lvlidrow == nwmax.getElementsByTagName("input")[0].getAttribute("levelid")) {
                    nwmax.getElementsByTagName("input")[0].setAttribute("lvlpos", x);
                    nwmax.getElementsByTagName("input")[0].setAttribute("id", "maxpmjudlvl" + x);
                }
            }
            var currmaxstbl = document.getElementById("Section-max").getElementsByClassName("currencybars1")[0];
            var currmaxs = currmaxstbl.getElementsByTagName("span");
            for (var x = 0; x < currmaxs.length; x++) {
                var currencies = currmaxs[x].getAttribute("currencyid");
                if (currencies == 1) {
                    nwmax.getElementsByTagName("input")[0].setAttribute("currpos", x);
                }

            }
            nwmax.classList.remove("nat");//Quitamos esta clase para identificar que son juridicos al guardar
            nwmax.getElementsByTagName("input")[0].setAttribute("dataNumber", levels[i].pagomovil.juridic.maxperday.number);
            jurmaxtbl.appendChild(nwmax);
            //-----------------

            //Fee jurídico
            nwfee = clonefee.cloneNode(true);
            nwfee.style.display = "";
            nwfee.getElementsByTagName("input")[0].value = levels[i].pagomovil.juridic.pctfee.formatted;
            nwfee.getElementsByTagName("input")[0].setAttribute("levelid", levels[i].level);
            var lvlrows = document.getElementById("Section-max").getElementsByClassName("maxpag");
            for (var x = 0; x < lvlrows.length; x++) {
                var lvlidrow = lvlrows[x].getElementsByClassName("levelCell")[0].getAttribute("levelid");
                if (lvlidrow == nwfee.getElementsByTagName("input")[0].getAttribute("levelid")) {
                    nwfee.getElementsByTagName("input")[0].setAttribute("lvlpos", x);
                    nwfee.getElementsByTagName("input")[0].setAttribute("id", "feepmjudlvl" + x);
                }
            }
            var currmaxstbl = document.getElementById("Section-max").getElementsByClassName("currencybars1")[0];
            var currmaxs = currmaxstbl.getElementsByTagName("span");
            for (var x = 0; x < currmaxs.length; x++) {
                var currencies = currmaxs[x].getAttribute("currencyid");
                if (currencies == 1) {
                    nwfee.getElementsByTagName("input")[0].setAttribute("currpos", x);
                }
            }
            nwfee.classList.remove("nat");//Quitamos esta clase para identificar que son juridicos al guardar
            nwfee.getElementsByTagName("input")[0].setAttribute("dataNumber", levels[i].pagomovil.juridic.pctfee.number);
            jurfeetbl.appendChild(nwfee);
        }

        //Se recorren los campos y se les da formato y funcionamiento
        let inputevents = (campos) => {
            var list = [];
            var fds = campos;
            for (var y = 0; y < fds.length; y++) {
                fds[y].setAttribute("type", "text");
                fds[y].addEventListener("focusin", function () {
                    decimCoin = 2;
                });
                list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto               

                fds[y].addEventListener("keydown", function (e) {
                    if (e.keyCode == 13) {
                        this.setAttribute("dataNumber", this.value);
                    }
                });
                //Guardar
                fds[y].addEventListener("change", function () {
                    saveMaxs(this, true);
                });
            }
            formatAmount(list);
        }
        //Evento de guardar max natural
        var fds = natmaxtbl.getElementsByTagName("input");
        inputevents(fds);
        //Evento de guardar max juridico
        var fds = jurmaxtbl.getElementsByTagName("input");
        inputevents(fds);

        //Se recorren los campos y se les da formato y funcionamiento
        let inputeventspct = (campos) => {
            var list = [];
            var fds = campos;
            for (var y = 0; y < fds.length; y++) {
                fds[y].setAttribute("type", "text");
                fds[y].addEventListener("focusin", function () {
                    decimCoin = 2;
                });
                list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto               

                fds[y].addEventListener("keydown", function (e) {
                    if (e.keyCode == 13) {
                        this.setAttribute("dataNumber", (this.value));
                    }
                });
                fds[y].addEventListener("keyup", function (e) {
                    if (this.value != "" && this.value != "0" && (this.getAttribute("type") == "number")) {
                        if (e.keyCode !== 190 && e.keyCode !== 188 && e.keyCode !== 110 && e.keyCode !== 229 && e.keyCode !== 8) {
                            this.value = (this.value <= 100) ? this.value : 100;
                        }
                    }
                });
                //Guardar
                fds[y].addEventListener("change", function () {
                    saveBalFees(this, true);
                });
            }
            formatAmount(list);
        }
        //Evento de guardar fee natural
        var fds = natfeetbl.getElementsByTagName("input");
        inputeventspct(fds);
        //Evento de guardar fee juridico
        var fds = jurfeetbl.getElementsByTagName("input");
        inputeventspct(fds);
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        var levelstbl = tbl.getElementsByClassName("currencybars1pm")[0];
        var clonelvl = levelstbl.children[0].cloneNode(true);
        levelstbl.innerHTML = "";
        nwlvl = clonelvl.cloneNode(true);
        nwlvl.style.display = "none";
        levelstbl.appendChild(nwlvl);

        var natmaxtbl = tbl.getElementsByClassName("maxLineBar")[1];
        var clonemax = natmaxtbl.children[0].cloneNode(true);
        natmaxtbl.innerHTML = "";
        nwmax = clonemax.cloneNode(true);
        nwmax.style.display = "none";
        natmaxtbl.appendChild(nwmax);

        var natfeetbl = tbl.getElementsByClassName("maxLineBar")[0];
        var clonefee = natfeetbl.children[0].cloneNode(true);
        natfeetbl.innerHTML = "";
        nwfee = clonefee.cloneNode(true);
        nwfee.style.display = "none";
        natfeetbl.appendChild(nwfee);

        var jurmaxtbl = tbl.getElementsByClassName("maxLineBar")[3];
        var clonemax = jurmaxtbl.children[0].cloneNode(true);
        jurmaxtbl.innerHTML = "";
        nwmax = clonemax.cloneNode(true);
        nwmax.style.display = "none";
        jurmaxtbl.appendChild(nwmax);

        var jurfeetbl = tbl.getElementsByClassName("maxLineBar")[2];
        var clonefee = jurfeetbl.children[0].cloneNode(true);
        jurfeetbl.innerHTML = "";
        nwfee = clonefee.cloneNode(true);
        nwfee.style.display = "none";
        jurfeetbl.appendChild(nwfee);
    }
}
function changebutt() {
    var gotosection = (button) => {
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        button.classList.add("activeTab");
        document.getElementById("Section-" + button.getAttribute("id")).classList.remove("nShow");
    }
    /*
    document.getElementById("descript").addEventListener("click", function () {
        gotosection("Section-Desc");
    });
    document.getElementById("min").addEventListener("click", function () {
        gotosection("Section-min");
    });
    document.getElementById("max").addEventListener("click", function () {
        gotosection("Section-max");
    });
    document.getElementById("change").addEventListener("click", function () {
        gotosection("Section-change");
    });
    document.getElementById("portfolio").addEventListener("click", function () {
        gotosection("Section-portfolio");
    });
    document.getElementById("buySold").addEventListener("click", function () {
        gotosection("Section-buySold");
    });
    document.getElementById("terms").addEventListener("click", function () {
        gotosection("Section-terms");
    });
    document.getElementById("pay").addEventListener("click", function () {
        gotosection("Section-pay");
    }); 
    */


    document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
        elmt.addEventListener("click", function () {
            gotosection(this);
        });
    });

    var payTbl = document.getElementById("payvalbars");
    payTbl.getElementsByTagName("input")[4].addEventListener("keyup", function (e) {
        if (this.value != "" && this.value != "0" && (this.getAttribute("type") == "number")) {
            if (e.keyCode !== 190 && e.keyCode !== 188 && e.keyCode !== 110 && e.keyCode !== 229 && e.keyCode !== 8) {
                this.value = (this.value <= 100) ? this.value : 100;
            }
        }
    })

    //Evento change guardar pay
    var payTbl = document.getElementById("payvalbars");
    var inpts = payTbl.getElementsByTagName("input");
    var select = payTbl.getElementsByTagName("select");
    for (var i = 0; i < inpts.length; i++) {
        inpts[i].addEventListener("change", function () {
            savepay();
        });
    }
    for (var i = 0; i < select.length; i++) {
        select[i].addEventListener("change", function () {
            savepay();
        });
    }
}
var reloadEntry = true;
function entryLevel() {
    var par = {};
    par.sessionid = sessionId;
    callWS("GET", "preferences/entry", par, rspUserEntryLevel);
    return 0;
}
function savepay() {
    var par = {};
    var payTbl = document.getElementById("payvalbars");
    par.maxtimereverse = payTbl.getElementsByTagName("input")[0].value;
    par.maxamountsend = payTbl.getElementsByTagName("input")[3].value;
    par.pctreverse = payTbl.getElementsByTagName("input")[4].value;
    par.sessidtime = payTbl.getElementsByTagName("input")[1].value;; rspUserSaveLevel
    par.optime = payTbl.getElementsByTagName("input")[2].value;;
    par.payrefcurrid = payTbl.getElementsByTagName("select")[0].value;;
    par.sessionid = sessionId;
    callWS("GET", "preferences/savepay", par, rspUserSaveLevel);
    return 0;
}
function paintPay(rsp) {
    //6 casos especificos de preferencias de pay
    var payTbl = document.getElementById("payvalbars");
    //Vencimiento op pendientes
    payTbl.getElementsByTagName("input")[0].value = rsp.pay.maxtimereverse.number;
    payTbl.getElementsByTagName("input")[0].setAttribute("type", "number");
    //Tiempo de inactividad
    payTbl.getElementsByTagName("input")[1].value = rsp.pay.sessidtime.number;
    payTbl.getElementsByTagName("input")[1].setAttribute("type", "number");
    //Vencimiento cobra-pago
    payTbl.getElementsByTagName("input")[2].value = rsp.pay.optime.number;
    payTbl.getElementsByTagName("input")[2].setAttribute("type", "number");
    //Tope de envío a usuarios nuevos
    payTbl.getElementsByTagName("input")[3].value = rsp.pay.maxamountsend.number;
    payTbl.getElementsByTagName("input")[3].setAttribute("type", "number");
    //Moneda de balances
    var paycurr = "";
    for (var i = 0; i < rsp.rates.currencies.length; i++) {
        if (rsp.rates.currencies[i].payref == '1') {
            paycurr = rsp.rates.currencies[i].id;
        }
    }
    drawSelect(payTbl.getElementsByTagName("select")[0], 'symbol', rsp.rates.currencies, paycurr, first = "");

    //Comisión de monto no cobrado
    payTbl.getElementsByTagName("input")[4].value = rsp.pay.pctreverse.number;

    payTbl.getElementsByTagName("input")[4].setAttribute("type", "number");
}
function rspUserEntryLevel(status, rsp) {
    switch (status) {
        case 200:
            console.log(JSON.parse(rsp));
            var resp = JSON.parse(rsp).entry;
            paintLevels(resp.levels);
            paintRates(resp.rates)
            paintMaxs(resp);
            paintMins(resp);
            paintFeesPairs(resp.levels);
            paintFeesCurr(resp.levels);
            paintPay(resp);//Preferencias de pay
            drawPmBanks(resp.pagomovil);//Se carga la lista de los bancos pago movil
            drawPmPrefs(resp.levels);//Se arman las comisiones y topes por nivel del pago movil
            var eng, esp = "";
            eng = resp.terms_eng;
            esp = resp.terms;
            if (eng == null) eng = "";
            if (esp == null) esp = "";
            paintTerms(esp, eng);
            setTimeout(function () {
                reloadEntry = true;
            }, 4000);
            setLang('espTerms', "terms", "left");
            setLang('espLevels', "levels", "left");
            document.getElementById('editor2eng').style.display = "none";
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}

function setLang(elementSelect, group, borderSide = "") {
    let selectedEl = document.getElementsByClassName('selectedLang');

    if (selectedEl.length > 0) {
        Array.prototype.forEach.call(selectedEl, function (el) {
            //console.log(el);
            if (el.getAttribute('data-group') == group) {
                el.classList.remove("selectedLang");
            }
        });
    }


    document.getElementById(elementSelect).classList.add("selectedLang");

    if (borderSide != "") {

        if (borderSide == 'right') {
            document.getElementById(elementSelect).style.borderBottomRightRadius = "10px";
            document.getElementById(elementSelect).style.borderTopRightRadius = "10px";
        } else {
            document.getElementById(elementSelect).style.borderBottomLeftRadius = "10px";
            document.getElementById(elementSelect).style.borderTopLeftRadius = "10px";
        }

    }
}

function paintLevels(data) {
    var sectLevels = document.getElementById("Section-descript");
    sectLevels.innerHTML += "";
    for (datos of data) {
        var desc = document.createElement("div");
        desc.classList.add('dscsEsp');
        desc.classList.add("descTab");
        desc.innerHTML = '<p class="level">' + datos.name + '</p>' +
            '<textarea class="area" id="dscLevelEsp-' + datos.level + '" name="Text1" cols="40" rows="4" value=' + datos.dsc + '></textarea>';

        sectLevels.appendChild(desc);
        document.getElementById("dscLevelEsp-" + datos.level).value = datos.dsc;
    }
    document.querySelectorAll('[id^="dscLevelEsp-"]').forEach(function (element) {
        element.addEventListener('change', function (event) {
            var id = (this.id).split("-")[1];
            saveLevel(id, this.value, document.getElementById('dscLevelEng-' + id).value);
        });
    });

    for (datos of data) {
        var desc = document.createElement("div");
        desc.classList.add('dscsEng');
        desc.style.display = "none";
        desc.classList.add("descTab");
        desc.innerHTML = '<p class="level">' + datos.name + '</p>' +
            '<textarea class="area" id="dscLevelEng-' + datos.level + '" name="Text1" cols="40" rows="4" value=""></textarea>';

        sectLevels.appendChild(desc);
        document.getElementById("dscLevelEng-" + datos.level).value = datos.dsc_eng;
    }

    document.querySelectorAll('[id^="dscLevelEng-"]').forEach(function (element) {
        element.addEventListener('change', function (event) {
            var id = (this.id).split("-")[1];
            saveLevel(id, document.getElementById('dscLevelEsp-' + id).value, this.value);
        });
    });

    document.getElementById('espLevels').addEventListener("click", function (e) {
        setLang("espLevels", "levels", 'left');

        var tonotshow = document.getElementsByClassName('dscsEng');
        var toshow = document.getElementsByClassName('dscsEsp');

        Array.prototype.forEach.call(tonotshow, function (el) {
            el.style.display = "none";
        });

        Array.prototype.forEach.call(toshow, function (el) {
            el.style.display = "block";
        });
    });

    document.getElementById('engLevels').addEventListener("click", function (e) {
        setLang("engLevels", "levels", 'right');

        var tonotshow = document.getElementsByClassName('dscsEsp');
        var toshow = document.getElementsByClassName('dscsEng');

        Array.prototype.forEach.call(tonotshow, function (el) {
            el.style.display = "none";
        });

        Array.prototype.forEach.call(toshow, function (el) {
            el.style.display = "block";
        });

    });

}
function saveLevel(levelid, desc, desc_eng) {
    var par = {};
    par.levelids = levelid;
    par.dsc = desc;
    par.dsc_eng = desc_eng
    par.sessionid = sessionId;
    callWS("GET", "preferences/savedsclevels", par, rspUserSaveLevel);
    return 0;
}
function rspUserSaveLevel(status, rsp) {
    switch (status) {
        case 200:
            //console.log(JSON.parse(rsp));
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            entryLevel();
            console.log(rsp);
    }
}
function paintRates(data) {
    var sectRates = document.getElementById("currencybars");
    var sectBars = document.getElementById("tasBars");
    var i = 0;
    sectBars.innerHTML = "";
    sectRates.innerHTML = "";
    var list = [];
    for (datos of data.currencies) {
        var desc = document.createElement("div");
        desc.classList.add("currencyTab");
        desc.innerHTML = '<span>' + datos.symbol + '</span>';

        sectRates.appendChild(desc);

        desc = document.createElement("div");
        desc.classList.add("tasBar");
        var dis = "";
        if (datos.id < 0) {
            dis = "disabled";
            desc.style.backgroundColor = "rgba(153, 153, 153, 0.3)";
        }
        desc.innerHTML = '<input id="changeTas-' + datos.id + '" decim="' + datos.decimals + '" currpos=' + i + ' ' + dis + ' dataNumber="' + datos.rate.number + '" value="' + datos.rate.formatted + '">';


        sectBars.appendChild(desc);
        i++;
        list.push('changeTas-' + datos.id);
    }

    document.querySelectorAll('[id^="changeTas-"]').forEach(function (element) {
        //Se definen los decimales que dan valor al campo
        element.addEventListener("focusin", function () {
            decimCoin = this.getAttribute("decim");
        });

        element.addEventListener('change', function (event) {
            var id = (this.id).split("-")[1];
            this.dispatchEvent(new Event("focusout"));
            this.dispatchEvent(new Event("focusin"));
            saveRate(id, this);
        });

        element.addEventListener('keydown', function (event) {
            if (event.keyCode == 13) {
                this.dispatchEvent(new Event("focusout"));
                this.dispatchEvent(new Event("focusin"));
                var id = (this.id).split("-")[1];
                saveRate(id, this);
            }
        });
    });
    formatAmount(list);
}
function saveRate(currencies, rates) {
    var par = {};
    par.currencies = currencies;
    par.rates = rates.getAttribute("dataNumber");
    par.sessionid = sessionId;
    callWS("GET", "preferences/saverates", par, rspUserSaveRate);

    /**Repintar máximos si hay ajuste de tasa*/
    var max = document.getElementById("Section-max");
    var pos = rates.getAttribute("currpos");
    var posref = max.getElementsByClassName("refcurr")[0].getAttribute("id").split("currency")[1]; //posicion de la moneda de referencia id -1
    /***Ajusto la tasa al nuevo valor***/
    max.querySelectorAll('[class^="currencyTab"]').forEach(function (element) {
        var element = element.children[0];
        if (element.getAttribute("id").indexOf("currency" + pos) > 0) {
            element.setAttribute("rate", rates.getAttribute("dataNumber"));
        }
    });
    /**Ubico las lineas columnas natural***/
    var lines = max.getElementsByClassName("Natural");
    for (var x = 0; x < lines.length; x++) {
        var list = lines[x].getElementsByClassName("maxLineBar");
        for (var i = 0; i < list.length; i++) {
            var save = false;
            //Si está en la última columna se guarda
            if ((i + 1) == list.length) save = true;

            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == posref) refval = parseFloat(element.getAttribute("dataNumber"));
            });
            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == pos && element.getAttribute("id").indexOf("amo") > 0) {
                    var newval = (parseFloat(rates.getAttribute("dataNumber")) * refval);
                    element.setAttribute("dataNumber", newval);
                    element.dispatchEvent(new Event("focusin")); element.dispatchEvent(new Event("focusout"));
                    if (save) saveMaxs(element);//Siempre que haya un change se guarda
                }
            });
        }
    }
    var lines = max.getElementsByClassName("Juridic");
    for (var x = 0; x < lines.length; x++) {
        var list = lines[x].getElementsByClassName("maxLineBar");
        for (var i = 0; i < list.length; i++) {
            var save = false;
            //Si está en la última columna se guarda
            if ((i + 1) == list.length) save = true;

            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == posref) refval = parseFloat(element.getAttribute("dataNumber"));
            });
            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == pos && element.getAttribute("id").indexOf("amo") > 0) {
                    var newval = (parseFloat(rates.getAttribute("dataNumber")) * refval);
                    element.setAttribute("dataNumber", newval);
                    element.dispatchEvent(new Event("focusin")); element.dispatchEvent(new Event("focusout"));
                    if (save) saveMaxs(element);
                }
            });
        }
    }

    /**Repintar mínimos si hay ajuste de tasa*/
    var min = document.getElementById("Section-min");
    var pos = rates.getAttribute("currpos");
    var posref = min.getElementsByClassName("refcurrMin")[0].getAttribute("id").split("currencyMin")[1]; //posicion de la moneda de referencia id -1
    /***Ajusto la tasa al nuevo valor***/
    min.querySelectorAll('[class^="currencyTab"]').forEach(function (element) {
        var element = element.children[0];
        if (element.getAttribute("id").indexOf("currencyMin" + pos) > 0) {
            element.setAttribute("rate", rates.getAttribute("dataNumber"));
        }
    });
    var lines = min.getElementsByClassName("Natural");
    for (var x = 0; x < lines.length; x++) {
        var list = lines[x].getElementsByClassName("maxLineBar");
        for (var i = 0; i < list.length; i++) {
            var save = false;
            //Si está en la última columna se guarda
            if ((i + 1) == list.length) save = true;

            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == posref) refval = parseFloat(element.getAttribute("dataNumber"));
            });
            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == pos && element.getAttribute("id").indexOf("min") > 0) {
                    var newval = (parseFloat(rates.getAttribute("dataNumber")) * refval);
                    element.setAttribute("dataNumber", newval);
                    element.dispatchEvent(new Event("focusin")); element.dispatchEvent(new Event("focusout"));
                    if (save) saveMins(element);
                }
            });
        }
    }
    var lines = min.getElementsByClassName("Juridic");
    for (var x = 0; x < lines.length; x++) {
        var list = lines[x].getElementsByClassName("maxLineBar");
        for (var i = 0; i < list.length; i++) {
            var save = false;
            //Si está en la última columna se guarda
            if ((i + 1) == list.length) save = true;

            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == posref) refval = parseFloat(element.getAttribute("dataNumber"));
            });
            list[i].querySelectorAll('[class^="maxBar"]').forEach(function (element) {
                var element = element.children[0];
                if (element.getAttribute("currpos") == pos && element.getAttribute("id").indexOf("min") > 0) {
                    var newval = (parseFloat(rates.getAttribute("dataNumber")) * refval);
                    element.setAttribute("dataNumber", newval);
                    element.dispatchEvent(new Event("focusin")); element.dispatchEvent(new Event("focusout"));
                    if (save) saveMins(element);
                }
            });
        }
    }
}
function rspUserSaveRate(status, rsp) {
    switch (status) {
        case 200:
            //console.log(JSON.parse(rsp));
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}

/**JAVIER**/
function paintMaxs(data) {
    var tbl = document.getElementById("Section-max").lastElementChild;
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data.levels;
    var rates = data.rates.currencies;
    var nwnode;
    if (levels.length > 0) {
        clone.style.display = "";
        tbl.innerHTML = "";
        for (var i = 0; i < levels.length; i++) {
            if (levels[i].currencies !== null && levels[i].currencies !== undefined) {
                nwnode = clone.cloneNode(true);
                //Se elminan los headers de lines siguientes
                if (tbl.children.length > 0) {
                    //Natural y juridico
                    var tit = nwnode.getElementsByClassName("reference2");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Depositos,retiros,xfer
                    var tit = nwnode.getElementsByClassName("reference");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Mensual/op
                    var tit = nwnode.getElementsByClassName("dscr");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }

                    //Agregar clase cont
                    nwnode.classList.add("maxpag1");

                    //Agregar clase de niveles y monedas
                    nwnode.children[0].classList.add("level2");
                    nwnode.children[1].classList.add("currencybars2");
                }
                nwnode.getElementsByClassName("levelCell")[0].innerHTML = levels[i].name;
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("id", "levelref" + i);
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("levelid", levels[i].level);
                //Monedas
                var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
                currcnt.innerHTML = "";

                //Ubicamos las tablas a llenar (juridic)
                var juridic = nwnode.getElementsByClassName("Juridic")[0];
                //Depositos
                var jdeposit = juridic.getElementsByClassName("maxBars")[0];
                var jamountsCnt = jdeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCnt.innerHTML = "";
                var joptsCnt = juridic.getElementsByClassName("dualbar1")[0].getElementsByClassName("maxLineBar")[0];
                joptsCnt.innerHTML = "";
                //Retiro
                var jwithdraw = juridic.getElementsByClassName("maxBars2")[0];
                var jamountsCntwd = jwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCntwd.innerHTML = "";
                var joptsCntwd = jwithdraw.getElementsByClassName("dualbar1")[0].getElementsByClassName("maxLineBar")[0];
                joptsCntwd.innerHTML = "";
                //Transferencia
                var jxfer = juridic.getElementsByClassName("maxBars1")[0];
                var jamountsCntx = jxfer.getElementsByClassName("maxLineBar")[0];
                jamountsCntx.innerHTML = "";


                //Ubicamos las tablas a llenar (natural)
                var natural = nwnode.getElementsByClassName("Natural")[0];
                //Depositos
                var ndeposit = natural.getElementsByClassName("maxBars")[0];
                var namountsCnt = ndeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCnt.innerHTML = "";
                var noptsCnt = natural.getElementsByClassName("dualbar1")[0].getElementsByClassName("maxLineBar")[0];
                noptsCnt.innerHTML = "";
                //Retiro
                var nwithdraw = natural.getElementsByClassName("maxBars2")[0];
                var namountsCntwd = nwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCntwd.innerHTML = "";
                var noptsCntwd = nwithdraw.getElementsByClassName("dualbar1")[0].getElementsByClassName("maxLineBar")[0];
                noptsCntwd.innerHTML = "";
                //Transferencia
                var nxfer = natural.getElementsByClassName("maxBars1")[0];
                var namountsCntx = nxfer.getElementsByClassName("maxLineBar")[0];
                namountsCntx.innerHTML = "";
                for (var x = 0; x < levels[i].currencies.length; x++) {
                    //Moneda
                    var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
                    var span = document.createElement("span");
                    span.innerHTML = levels[i].currencies[x].symbol;
                    span.setAttribute("id", i + "currency" + x);
                    span.setAttribute("currencyid", levels[i].currencies[x].id);
                    for (var j = 0; j < rates.length; j++) {
                        if (levels[i].currencies[x].id == rates[j].id) {
                            span.setAttribute("rate", rates[j].rate.number);
                        }
                    }
                    span.setAttribute("decim", levels[i].currencies[x].decimals);
                    if (levels[i].currencies[x].id < 0) span.classList.add("refcurr");
                    maxbar.appendChild(span);
                    currcnt.appendChild(maxbar);
                    /*****NATURAL***/
                    /**Deposito**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.natural.deposits.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.natural.deposits.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "natdepamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    namountsCnt.appendChild(maxbar);
                    //Crear linea cantidad de operaciones
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.value = levels[i].currencies[x].max.natural.deposits.operations.formatted;
                    input.setAttribute("id", (i + "" + x + "natdepqty"));
                    maxbar.appendChild(input);
                    noptsCnt.appendChild(maxbar);

                    /**Retiro**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.natural.withdrawals.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.natural.withdrawals.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "natwithdamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    namountsCntwd.appendChild(maxbar);
                    //Crear linea cantidad de operaciones
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.value = levels[i].currencies[x].max.natural.withdrawals.operations.formatted;
                    input.setAttribute("id", (i + "" + x + "natwithdqty"));
                    maxbar.appendChild(input);
                    noptsCntwd.appendChild(maxbar);

                    /**Transferencia**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.natural.xfer.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.natural.xfer.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "natxferamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    namountsCntx.appendChild(maxbar);


                    /*******JURIDICO*******/
                    /**Deposito**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.juridic.deposits.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.juridic.deposits.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "juddepamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    jamountsCnt.appendChild(maxbar);
                    //Crear linea cantidad de operaciones
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.value = levels[i].currencies[x].max.juridic.deposits.operations.formatted;
                    input.setAttribute("id", (i + "" + x + "juddepqty"));
                    maxbar.appendChild(input);
                    joptsCnt.appendChild(maxbar);

                    /**Retiro**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.juridic.withdrawals.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.juridic.withdrawals.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "judwithdamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    jamountsCntwd.appendChild(maxbar);
                    //Crear linea cantidad de operaciones
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.value = levels[i].currencies[x].max.juridic.withdrawals.operations.formatted;
                    input.setAttribute("id", (i + "" + x + "judwithdqty"));
                    maxbar.appendChild(input);
                    joptsCntwd.appendChild(maxbar);

                    /**Transferencia**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("dataNumber", levels[i].currencies[x].max.juridic.xfer.amount.number);//Funcionamiento campos amount
                    input.value = levels[i].currencies[x].max.juridic.xfer.amount.formatted;
                    input.setAttribute("id", (i + "" + x + "judxferamo"));
                    if (levels[i].currencies[x].id > 0) {
                        input.setAttribute("disabled", "");
                        maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
                    }
                    maxbar.appendChild(input);
                    jamountsCntx.appendChild(maxbar);
                }
                tbl.appendChild(nwnode);

                //Se recorren los campos y se les da formato y funcionamiento
                var fds = nwnode.getElementsByTagName("input");
                var list = [];
                for (var y = 0; y < fds.length; y++) {
                    fds[y].setAttribute("type", "text");
                    fds[y].addEventListener("focusin", function () {
                        decimCoin = document.getElementById(this.getAttribute("lvlpos") + "currency" + this.getAttribute("currpos")).getAttribute("decim");
                    });
                    if (!(fds[y].getAttribute("id").indexOf("qty") > 0))
                        list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto
                    else {
                        fds[y].setAttribute("type", "number");//Se convierte a numerico simple

                    }


                    fds[y].addEventListener("keydown", function (e) {
                        if (e.keyCode == 13) {
                            this.setAttribute("dataNumber", this.value);
                        }
                    });
                    //Guardar
                    fds[y].addEventListener("change", function () {
                        var refcurrid = document.getElementsByClassName("refcurr")[0].getAttribute("id");
                        var poscurr = refcurrid.split("currency")[1];
                        if (this.getAttribute("currpos") == poscurr || ((this.getAttribute("id").indexOf('qty')) > -1)) {
                            //Si es el primero se recalcula el resto según las tasas
                            var cnt = this.parentElement.parentElement;
                            var inptcnt = cnt.getElementsByTagName("input");
                            for (var i = 0; i < inptcnt.length; i++) {
                                if (inptcnt[i].getAttribute("id") !== this.getAttribute("id")) {
                                    var rate = document.getElementById(inptcnt[i].getAttribute("lvlpos") + "currency" + inptcnt[i].getAttribute("currpos")).getAttribute("rate");
                                    var newval = this.value * rate;
                                    inptcnt[i].setAttribute("dataNumber", newval);

                                    decimCoin = document.getElementById(inptcnt[i].getAttribute("lvlpos") + "currency" + inptcnt[i].getAttribute("currpos")).getAttribute("decim");
                                    inptcnt[i].dispatchEvent(new Event("focusin")); inptcnt[i].dispatchEvent(new Event("focusout"));
                                    saveMaxs(inptcnt[i]);//Siempre que haya un change se guarda
                                } else {
                                    decimCoin = document.getElementById(this.getAttribute("lvlpos") + "currency" + this.getAttribute("currpos")).getAttribute("decim");
                                    saveMaxs(this);
                                }
                            }
                        }
                    });
                }
                formatAmount(list);
            }
        }
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
function saveMaxs(ele, pm = false) {
    setTimeout(function () {
        var par = {};
        if (!pm) {
            var cnt = ele.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
            var usertype = "";
            var typeatr = "";
            if (cnt.classList.contains("Natural")) {
                usertype = "1";
                typeatr = "nat";
            } else {
                usertype = "2";
                typeatr = "jud";
            }
        } else {
            var usertype = "";
            var typeatr = "";
            if (ele.parentElement.classList.contains("nat")) {
                usertype = "1";
                typeatr = "nat";
            } else {
                usertype = "2";
                typeatr = "jud";
            }
        }
        par.usertype = usertype;
        var poscurr = ele.getAttribute("currpos");
        var poslvl = ele.getAttribute("lvlpos");
        par.currencyid = document.getElementById(poslvl + "currency" + poscurr).getAttribute("currencyid");
        par.levelid = document.getElementById("levelref" + poslvl).getAttribute("levelid");
        //Valores inputs
        par.maxmensualdeposit = parseFloat(document.getElementById(poslvl + "" + poscurr + typeatr + "depamo").getAttribute("dataNumber"));
        par.opmensualdeposit = document.getElementById(poslvl + "" + poscurr + typeatr + "depqty").value;
        par.maxmensualwithdraw = parseFloat(document.getElementById(poslvl + "" + poscurr + typeatr + "withdamo").getAttribute("dataNumber"));
        par.opmensualwithdraw = document.getElementById(poslvl + "" + poscurr + typeatr + "withdqty").value;
        par.maxmensualxfer = document.getElementById(poslvl + "" + poscurr + typeatr + "xferamo").getAttribute("dataNumber");



        //Valores de minimos relativos a la moneda
        var mindep = parseFloat(document.getElementById(poscurr + typeatr + "depmin").getAttribute("dataNumber"));
        var minwithd = parseFloat(document.getElementById(poscurr + typeatr + "withdmin").getAttribute("dataNumber"));
        var minxfer = parseFloat(document.getElementById(poscurr + typeatr + "xfermin").getAttribute("dataNumber"));

        //#NEW
        //if (pm) {
        if (document.getElementById("maxpm" + typeatr + "lvl" + poslvl).getAttribute("type") == "text")
            par.maxpagomovil = document.getElementById("maxpm" + typeatr + "lvl" + poslvl).getAttribute("dataNumber");
        else
            par.maxpagomovil = document.getElementById("maxpm" + typeatr + "lvl" + poslvl).value;
        //}
        if (parseFloat(par.maxmensualdeposit) < mindep || parseFloat(par.maxmensualwithdraw) < minwithd || parseFloat(par.maxmensualxfer) < minxfer) {
            var msg = document.getElementById("messageApiMax");
            msg.innerHTML = "El monto máximo no puede ser menor que el monto mínimo";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.innerHTML = "";
                msg.classList.remove("msgError");
                msg.style.display = "none";
            }, 4000);
            if (reloadEntry) {
                entryLevel();
                reloadEntry = false;
            }
            return;
        }

        par.sessionid = sessionId;

        callWS("GET", "preferences/savelimits", par, rspUserSaveRate);
    }, 50);

}
function paintFeesPairs(data) {
    var tbl = document.getElementById("Section-buySell");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data;
    var nwnode;
    if (levels.length > 0) {
        clone.style.display = "";
        tbl.innerHTML = "";
        for (var i = 0; i < levels.length; i++) {
            if (levels[i].pairs !== null && levels[i].pairs !== undefined) {
                nwnode = clone.cloneNode(true);
                if (tbl.children.length > 0) {
                    //Se elminan los headers de lines siguientes
                    //Natural y juridico
                    var tit = nwnode.getElementsByClassName("reference2");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Depositos,retiros,xfer
                    var tit = nwnode.getElementsByClassName("reference");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Mensual/op
                    var tit = nwnode.getElementsByClassName("dscr");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }

                    //Agregar clase cont
                    nwnode.classList.add("maxpag1");

                    //Agregar clase de niveles y monedas
                    nwnode.children[0].classList.add("level2");
                    nwnode.children[1].classList.add("currencybars2");
                }
                nwnode.getElementsByClassName("levelCell")[0].innerHTML = levels[i].name;
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("id", "levelrefpair" + i);
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("levelid", levels[i].level);
                //Monedas
                var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
                currcnt.innerHTML = "";

                //Ubicamos las tablas a llenar (juridic)
                var juridic = nwnode.getElementsByClassName("Juridic")[0];
                //Oreden Limit
                var jdeposit = juridic.getElementsByClassName("maxBars6")[0];
                var jamountsCnt = jdeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCnt.innerHTML = "";
                /*
                var joptsCnt = juridic.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                joptsCnt.innerHTML = "";
                */
                //Orden Market
                var jwithdraw = juridic.getElementsByClassName("maxBars5")[0];
                var jamountsCntwd = jwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCntwd.innerHTML = "";
                /*
                var joptsCntwd = jwithdraw.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                joptsCntwd.innerHTML = "";
                */

                //Ubicamos las tablas a llenar (natural)
                var natural = nwnode.getElementsByClassName("Natural")[0];
                //Depositos
                var ndeposit = natural.getElementsByClassName("maxBars6")[0];
                var namountsCnt = ndeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCnt.innerHTML = "";
                /*
                var noptsCnt = natural.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                noptsCnt.innerHTML = "";*/
                //Retiro
                var nwithdraw = natural.getElementsByClassName("maxBars5")[0];
                var namountsCntwd = nwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCntwd.innerHTML = "";
                /*
                var noptsCntwd = nwithdraw.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                noptsCntwd.innerHTML = "";
                */
                for (var x = 0; x < levels[i].pairs.length; x++) {
                    //Moneda
                    var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
                    var span = document.createElement("span");
                    span.innerHTML = levels[i].pairs[x].name;
                    span.setAttribute("id", i + "currencyPair" + x);
                    span.setAttribute("pairid", levels[i].pairs[x].id);
                    span.setAttribute("basedecim", levels[i].pairs[x].basedecimals);
                    maxbar.appendChild(span);
                    currcnt.appendChild(maxbar);
                    /*****NATURAL***/
                    /**LIMITE**/
                    //Crear linea porcentual
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    if (levels[i].pairs[x].fees.natural.limit.nmalfee.number == null) {
                        input.value = levels[i].pairs[x].fees.natural.limit.pctfee.number;
                        input.setAttribute("dataNumber", levels[i].pairs[x].fees.natural.limit.pctfee.number);//Funcionamiento campos amount
                    } else {
                        input.setAttribute("dataNumber", "");
                    }
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("id", (i + "natlmtpct" + x));
                    maxbar.appendChild(input);
                    namountsCnt.appendChild(maxbar);
                    //Crear linea nominal
                    /*
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    if(levels[i].pairs[x].fees.natural.limit.pctfee.number == null){
                        input.value = levels[i].pairs[x].fees.natural.limit.nmalfee.formatted;
                        input.setAttribute("dataNumber",levels[i].pairs[x].fees.natural.limit.nmalfee.number);//Funcionamiento campos amount
                    }else{
                        input.setAttribute("dataNumber","");
                    }
                    input.setAttribute("currpos",x);
                    input.setAttribute("lvlpos",i);
                    input.setAttribute("id",(i+"natlmtnml"+x));
                    maxbar.appendChild(input);
                    noptsCnt.appendChild(maxbar);
                    */

                    /**MARKET**/
                    //Crear linea porcentual
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    if (levels[i].pairs[x].fees.natural.market.nmalfee.number == null) {
                        input.value = levels[i].pairs[x].fees.natural.market.pctfee.number;
                        input.setAttribute("dataNumber", levels[i].pairs[x].fees.natural.market.pctfee.number);//Funcionamiento campos amount
                    } else {
                        input.setAttribute("dataNumber", "");
                    }
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("id", (i + "natmktpct" + x));
                    maxbar.appendChild(input);
                    namountsCntwd.appendChild(maxbar);
                    //Crear linea nominal
                    /*
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    if(levels[i].pairs[x].fees.natural.market.pctfee.number == null){
                        input.value = levels[i].pairs[x].fees.natural.market.nmalfee.formatted;
                        input.setAttribute("dataNumber",levels[i].pairs[x].fees.natural.market.nmalfee.number);//Funcionamiento campos amount
                    }else{
                        input.setAttribute("dataNumber","");
                    }
                    input.setAttribute("currpos",x);
                    input.setAttribute("lvlpos",i);
                    input.setAttribute("id",(i+"natmktnml"+x));
                    maxbar.appendChild(input);
                    noptsCntwd.appendChild(maxbar);
                    */

                    /*******JURIDICO*******/
                    /**LIMITE**/
                    //Crear linea porcentual
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    if (levels[i].pairs[x].fees.juridic.limit.nmalfee.number == null) {
                        input.value = levels[i].pairs[x].fees.juridic.limit.pctfee.number;
                        input.setAttribute("dataNumber", levels[i].pairs[x].fees.juridic.limit.pctfee.number);//Funcionamiento campos amount
                    } else {
                        input.setAttribute("dataNumber", "");
                    }
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("id", (i + "judlmtpct" + x));
                    maxbar.appendChild(input);
                    jamountsCnt.appendChild(maxbar);
                    //Crear linea nominal
                    /*
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    if(levels[i].pairs[x].fees.juridic.limit.pctfee.number == null){
                        input.value = levels[i].pairs[x].fees.juridic.limit.nmalfee.formatted;
                        input.setAttribute("dataNumber",levels[i].pairs[x].fees.juridic.limit.nmalfee.number);//Funcionamiento campos amount
                    }else{
                        input.setAttribute("dataNumber","");
                    }
                    input.setAttribute("currpos",x);
                    input.setAttribute("lvlpos",i);
                    input.setAttribute("id",(i+"judlmtnml"+x));
                    maxbar.appendChild(input);
                    joptsCnt.appendChild(maxbar);
                    */
                    /**MARKET**/
                    //Crear linea amount
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                    var input = document.createElement("input");
                    if (levels[i].pairs[x].fees.juridic.market.nmalfee.number == null) {
                        input.value = levels[i].pairs[x].fees.juridic.market.pctfee.number;
                        input.setAttribute("dataNumber", levels[i].pairs[x].fees.juridic.market.pctfee.number);//Funcionamiento campos amount
                    } else {
                        input.setAttribute("dataNumber", "");
                    }
                    input.setAttribute("currpos", x);
                    input.setAttribute("lvlpos", i);
                    input.setAttribute("id", (i + "judmktpct" + x));
                    maxbar.appendChild(input);
                    jamountsCntwd.appendChild(maxbar);
                    //Crear linea cantidad de operaciones
                    /*
                    var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                    var input = document.createElement("input");
                    if(levels[i].pairs[x].fees.juridic.market.pctfee.number == null){
                        input.value = levels[i].pairs[x].fees.juridic.market.nmalfee.formatted;
                        input.setAttribute("dataNumber",levels[i].pairs[x].fees.juridic.market.nmalfee.number);//Funcionamiento campos amount
                    }else{
                        input.setAttribute("dataNumber","");
                    }
                    input.setAttribute("currpos",x);
                    input.setAttribute("lvlpos",i);
                    input.setAttribute("id",(i+"judmktnml"+x));
                    maxbar.appendChild(input);
                    joptsCntwd.appendChild(maxbar);
                    */
                }

                tbl.appendChild(nwnode);
                //Se recorren los campos y se les da formato y funcionamiento
                var fds = nwnode.getElementsByTagName("input");
                var list = [];
                for (var y = 0; y < fds.length; y++) {
                    fds[y].setAttribute("type", "text");
                    fds[y].addEventListener("focusin", function () {
                        decimCoin = document.getElementById(this.getAttribute("lvlpos") + "currencyPair" + this.getAttribute("currpos")).getAttribute("basedecim");
                    });
                    if (!(fds[y].getAttribute("id").indexOf("pct") > 0)) {
                        list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto
                        fds[y].addEventListener("keydown", function (e) {
                            if (e.keyCode == 13) {
                                this.dispatchEvent(new Event("focusout"));
                                this.dispatchEvent(new Event("focusin"));
                                this.dispatchEvent(new Event("change"));
                            }
                        });
                    } else {
                        fds[y].setAttribute("type", "number");//Se convierte a numerico simple

                        fds[y].addEventListener("keyup", function (e) {
                            if (this.value != "" && this.value != "0" && (this.getAttribute("type") == "number")) {
                                if (e.keyCode !== 190 && e.keyCode !== 188 && e.keyCode !== 110 && e.keyCode !== 229 && e.keyCode !== 8) {
                                    this.value = (this.value <= 100) ? this.value : 100;
                                }
                            }
                        })
                    }
                    /*   
                    fds[y].addEventListener("focusout",function(){
                        blankOpositFee(this);
                    });*/
                    //Guardar

                    fds[y].addEventListener("change", function () {
                        savePairFees(this);//Siempre que haya un change se guarda
                    });

                }
                formatAmount(list);
            }
        }
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
function blankOpositFee(ele) {
    if (ele.value !== "" && ele.value !== null) {
        var id = "";
        if ((ele.getAttribute("id").indexOf("nml") > 0)) {
            id = ele.getAttribute("id").replace("nml", "pct");
            if (parseFloat(ele.getAttribute("dataNumber")) > -1 && parseFloat(ele.getAttribute("dataNumber")) !== 0) {
                document.getElementById(id).value = "";
                document.getElementById(id).setAttribute("dataNumber", "");
            } else if (parseFloat(document.getElementById(id).value) > -1 &&
                parseFloat(document.getElementById(id).value) !== 0) {
                ele.value = "";
                ele.setAttribute("dataNumber", "");
            } else {
                ele.value = "0";
                ele.setAttribute("dataNumber", "0");
                document.getElementById(id).value = "";
                document.getElementById(id).setAttribute("dataNumber", "");
            }
        } else {
            id = ele.getAttribute("id").replace("pct", "nml");
            if (parseFloat(ele.value) > -1 && parseFloat(ele.value) !== 0) {
                document.getElementById(id).value = "";
                document.getElementById(id).setAttribute("dataNumber", "");
            } else if (parseFloat(document.getElementById(id).getAttribute("dataNumber")) > -1 &&
                parseFloat(document.getElementById(id).getAttribute("dataNumber")) !== 0) {
                ele.value = "";
                ele.setAttribute("dataNumber", "");
            } else {
                document.getElementById(id).value = "0";
                document.getElementById(id).setAttribute("dataNumber", "0");
                ele.value = "";
                ele.setAttribute("dataNumber", "");
            }
        }
    }
}
function savePairFees(ele) {
    setTimeout(function () {
        //blankOpositFee(ele);
        var par = {};
        var cnt = ele.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
        var usertype = "";
        var typeatr = "";
        if (cnt.classList.contains("Natural")) {
            usertype = "1";
            typeatr = "nat";
        } else {
            usertype = "2";
            typeatr = "jud";
        }
        par.usertype = usertype;
        var poscurr = ele.getAttribute("currpos");
        var poslvl = ele.getAttribute("lvlpos");
        par.pairid = document.getElementById(poslvl + "currencyPair" + poscurr).getAttribute("pairid");
        par.levelid = document.getElementById("levelrefpair" + poslvl).getAttribute("levelid");

        //Valores inputs
        if (document.getElementById(poslvl + typeatr + "mktpct" + poscurr).value !== "")
            par.pctfeemkt = document.getElementById(poslvl + typeatr + "mktpct" + poscurr).value;
        else
            par.pctfeemkt = 0;

        if (document.getElementById(poslvl + typeatr + "lmtpct" + poscurr).value !== "")
            par.pctfeelimit = document.getElementById(poslvl + typeatr + "lmtpct" + poscurr).value;
        else
            par.pctfeelimit = 0;

        par.sessionid = sessionId;

        callWS("GET", "preferences/saveexchangefees", par, rspUserSaveRate);
    }, 50);

}
function paintFeesCurr(data) {
    var tbl = document.getElementById("Section-portfolio");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data;
    var nwnode;
    if (levels.length > 0) {
        clone.style.display = "";
        tbl.innerHTML = "";
        for (var i = 0; i < levels.length; i++) {
            if (levels[i].currencies !== null && levels[i].currencies !== undefined) {
                nwnode = clone.cloneNode(true);
                if (tbl.children.length > 0) {
                    //Se elminan los headers de lines siguientes
                    //Natural y juridico
                    var tit = nwnode.getElementsByClassName("reference2");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Depositos,retiros,xfer
                    var tit = nwnode.getElementsByClassName("reference");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }
                    //Mensual/op
                    var tit = nwnode.getElementsByClassName("dscr");
                    var sz = tit.length;
                    for (var y = 0; y < sz; y++) {
                        tit[0].parentElement.removeChild(tit[0]);
                    }

                    //Agregar clase cont
                    nwnode.classList.add("maxpag1");

                    //Agregar clase de niveles y monedas
                    nwnode.children[0].classList.add("level2");
                    nwnode.children[1].classList.add("currencybars2");
                }
                nwnode.getElementsByClassName("levelCell")[0].innerHTML = levels[i].name;
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("id", "levelrefbal" + i);
                nwnode.getElementsByClassName("levelCell")[0].setAttribute("levelid", levels[i].level);
                //Monedas
                var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
                currcnt.innerHTML = "";

                //Ubicamos las tablas a llenar (juridic)
                var juridic = nwnode.getElementsByClassName("Juridic")[0];
                //Depositos
                var jdeposit = juridic.getElementsByClassName("maxBars3")[0];
                var jamountsCnt = jdeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCnt.innerHTML = "";
                var joptsCnt = juridic.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                joptsCnt.innerHTML = "";
                //Retiro
                var jwithdraw = juridic.getElementsByClassName("maxBars4")[0];
                var jamountsCntwd = jwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCntwd.innerHTML = "";
                var joptsCntwd = jwithdraw.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                joptsCntwd.innerHTML = "";
                //Transferencia
                var jxfer = juridic.getElementsByClassName("maxBars3")[1];
                var jamountsCntx = jxfer.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                jamountsCntx.innerHTML = "";
                var joptsCntx = jxfer.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                joptsCntx.innerHTML = "";


                //Ubicamos las tablas a llenar (natural)
                var natural = nwnode.getElementsByClassName("Natural")[0];
                //Depositos
                var ndeposit = natural.getElementsByClassName("maxBars3")[0];
                var namountsCnt = ndeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCnt.innerHTML = "";
                var noptsCnt = natural.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                noptsCnt.innerHTML = "";
                //Retiro
                var nwithdraw = natural.getElementsByClassName("maxBars4")[0];
                var namountsCntwd = nwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCntwd.innerHTML = "";
                var noptsCntwd = nwithdraw.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                noptsCntwd.innerHTML = "";
                //Transferencia
                var nxfer = natural.getElementsByClassName("maxBars3")[1];
                var namountsCntx = nxfer.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
                namountsCntx.innerHTML = "";
                var noptsCntx = nxfer.getElementsByClassName("dualbar2")[0].getElementsByClassName("maxLineBar")[0];
                noptsCntx.innerHTML = "";
                for (var x = 0; x < levels[i].currencies.length; x++) {
                    if (levels[i].currencies[x].id > 0) {

                        //Moneda
                        var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
                        var span = document.createElement("span");
                        span.innerHTML = levels[i].currencies[x].symbol;
                        span.setAttribute("id", i + "currencyBal" + x);
                        span.setAttribute("currencyid", levels[i].currencies[x].id);
                        /*
                        for(var j=0;j<rates.length;j++){
                            if(levels[i].currencies[x].id == rates[j].id){
                                span.setAttribute("rate",rates[j].rate.number);
                            }
                        }*/
                        span.setAttribute("decim", levels[i].currencies[x].decimals);
                        if (levels[i].currencies[x].id < 0) span.classList.add("refcurr");
                        maxbar.appendChild(span);
                        currcnt.appendChild(maxbar);
                        /*****NATURAL***/
                        /**Deposito**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.deposits.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.deposits.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.deposits.pctfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natdeppct" + x));
                        maxbar.appendChild(input);
                        namountsCnt.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.deposits.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.deposits.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.deposits.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natdepnml" + x));
                        maxbar.appendChild(input);
                        noptsCnt.appendChild(maxbar);

                        /**Retiro**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.withdrawals.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.withdrawals.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.withdrawals.pctfee.number);//Funcionamiento campos amount
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natwithdpct" + x));
                        maxbar.appendChild(input);
                        namountsCntwd.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.withdrawals.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.withdrawals.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.withdrawals.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natwithdnml" + x));
                        maxbar.appendChild(input);
                        noptsCntwd.appendChild(maxbar);

                        /**Transferencia**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.xfer.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.xfer.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.xfer.pctfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natxferpct" + x));
                        maxbar.appendChild(input);
                        namountsCntx.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.natural.xfer.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.natural.xfer.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.natural.xfer.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "natxfernml" + x));
                        maxbar.appendChild(input);
                        noptsCntx.appendChild(maxbar);

                        /*******JURIDICO*******/
                        /**Deposito**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.deposits.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.deposits.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.deposits.pctfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "juddeppct" + x));
                        maxbar.appendChild(input);
                        jamountsCnt.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.deposits.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.deposits.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.deposits.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "juddepnml" + x));
                        maxbar.appendChild(input);
                        joptsCnt.appendChild(maxbar);

                        /**Retiro**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.withdrawals.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.withdrawals.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.withdrawals.pctfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "judwithdpct" + x));
                        maxbar.appendChild(input);
                        jamountsCntwd.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.withdrawals.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.withdrawals.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.withdrawals.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "judwithdnml" + x));
                        maxbar.appendChild(input);
                        joptsCntwd.appendChild(maxbar);

                        /**Transferencia**/
                        //Porcentual
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.xfer.nmlfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.xfer.pctfee.number;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.xfer.pctfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "judxferpct" + x));
                        maxbar.appendChild(input);
                        jamountsCntx.appendChild(maxbar);
                        //Nominal
                        var maxbar = document.createElement("div"); maxbar.classList.add("maxBar1");
                        var input = document.createElement("input");
                        if (levels[i].currencies[x].fees.juridic.xfer.pctfee.number == null) {
                            input.value = levels[i].currencies[x].fees.juridic.xfer.nmlfee.formatted;
                            input.setAttribute("dataNumber", levels[i].currencies[x].fees.juridic.xfer.nmlfee.number);//Funcionamiento campos amount
                        } else {
                            input.setAttribute("dataNumber", "");
                        }
                        input.setAttribute("currpos", x);
                        input.setAttribute("lvlpos", i);
                        input.setAttribute("id", (i + "judxfernml" + x));
                        maxbar.appendChild(input);
                        joptsCntx.appendChild(maxbar);

                    }
                }
                tbl.appendChild(nwnode);

                //Se recorren los campos y se les da formato y funcionamiento
                var fds = nwnode.getElementsByTagName("input");
                var list = [];
                for (var y = 0; y < fds.length; y++) {
                    fds[y].setAttribute("type", "text");
                    fds[y].addEventListener("focusin", function () {
                        decimCoin = document.getElementById(this.getAttribute("lvlpos") + "currencyBal" + this.getAttribute("currpos")).getAttribute("decim");
                    });
                    if (!(fds[y].getAttribute("id").indexOf("pct") > 0)) {
                        list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto

                        fds[y].addEventListener("keydown", function (e) {
                            if (e.keyCode == 13) {
                                this.dispatchEvent(new Event("focusout"));
                                this.dispatchEvent(new Event("focusin"));
                                this.dispatchEvent(new Event("change"));
                            }
                        });

                    } else {
                        fds[y].setAttribute("type", "number");//Se convierte a numerico simple
                        fds[y].addEventListener("keyup", function (e) {
                            if (this.value != "" && this.value != "0" && (this.getAttribute("type") == "number")) {
                                if (e.keyCode !== 190 && e.keyCode !== 188 && e.keyCode !== 110 && e.keyCode !== 229 && e.keyCode !== 8) {
                                    this.value = (this.value <= 100) ? this.value : 100;
                                }
                            }
                        })
                    }

                    //Guardar
                    fds[y].addEventListener("change", function () {
                        saveBalFees(this);//Siempre que haya un change se guarda
                    });
                }
                formatAmount(list);
            }
        }
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
function saveBalFees(ele, pm = false) {
    setTimeout(function () {
        var par = {};
        var usertype = "";
        var typeatr = "";
        if (!pm) {
            blankOpositFee(ele);
            var cnt = ele.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
            if (cnt.classList.contains("Natural")) {
                usertype = "1";
                typeatr = "nat";
            } else {
                usertype = "2";
                typeatr = "jud";
            }
        } else {
            if (ele.parentElement.classList.contains("nat")) {
                usertype = "1";
                typeatr = "nat";
            } else {
                usertype = "2";
                typeatr = "jud";
            }
        }
        par.usertype = usertype;
        var poscurr = ele.getAttribute("currpos");
        var poslvl = ele.getAttribute("lvlpos");
        par.currencyid = document.getElementById(poslvl + "currencyBal" + poscurr).getAttribute("currencyid");
        par.levelid = document.getElementById("levelrefbal" + poslvl).getAttribute("levelid");

        //Valores inputs
        if (document.getElementById(poslvl + typeatr + "deppct" + poscurr).value !== "")
            par.pctfeedeposit = document.getElementById(poslvl + typeatr + "deppct" + poscurr).value;
        if (document.getElementById(poslvl + typeatr + "depnml" + poscurr).getAttribute("dataNumber") !== "")
            par.nmlfeedeposit = document.getElementById(poslvl + typeatr + "depnml" + poscurr).getAttribute("dataNumber");
        if (par.pctfeedeposit == undefined && par.nmlfeedeposit == undefined) {
            par.nmlfeedeposit = 0;
        }

        if (document.getElementById(poslvl + typeatr + "withdpct" + poscurr).value !== "")
            par.pctfeewidthdraw = document.getElementById(poslvl + typeatr + "withdpct" + poscurr).value;
        if (document.getElementById(poslvl + typeatr + "withdnml" + poscurr).getAttribute("dataNumber") !== "")
            par.nmlfeewidthdraw = document.getElementById(poslvl + typeatr + "withdnml" + poscurr).getAttribute("dataNumber");
        if (par.pctfeewidthdraw == undefined && par.nmlfeewidthdraw == undefined) {
            par.nmlfeewidthdraw = 0;
        }

        if (document.getElementById(poslvl + typeatr + "xferpct" + poscurr).value !== "")
            par.pctfeexfer = document.getElementById(poslvl + typeatr + "xferpct" + poscurr).value;
        if (document.getElementById(poslvl + typeatr + "xfernml" + poscurr).getAttribute("dataNumber") !== "")
            par.nmlfeexfer = document.getElementById(poslvl + typeatr + "xfernml" + poscurr).getAttribute("dataNumber");
        if (par.pctfeexfer == undefined && par.nmlfeexfer == undefined) {
            par.nmlfeexfer = 0;
        }
        //#NEW
        //if (pm) {
        if (document.getElementById("maxpm" + typeatr + "lvl" + poslvl).getAttribute("type") == "text")
            par.pagomovilpctfee = document.getElementById("feepm" + typeatr + "lvl" + poslvl).getAttribute("dataNumber");
        else
            par.pagomovilpctfee = document.getElementById("feepm" + typeatr + "lvl" + poslvl).value;
        //}

        par.sessionid = sessionId;
        callWS("GET", "preferences/savebalancefees", par, rspUserSaveRate);
    }, 50);

}
function paintMins(data) {
    var tbl = document.getElementById("Section-min").lastElementChild;
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data.levels;
    var rates = data.rates.currencies;
    var nwnode;
    if (rates.length > 0) {
        clone.style.display = "";
        tbl.innerHTML = "";
        nwnode = clone.cloneNode(true);
        //Se elminan los headers de lines siguientes
        nwnode.getElementsByClassName("levelCell")[0].innerHTML = "";

        //Monedas
        var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
        currcnt.innerHTML = "";

        //Ubicamos las tablas a llenar (juridic)
        var juridic = nwnode.getElementsByClassName("Juridic")[0];
        //Depositos
        var jdeposit = juridic.getElementsByClassName("maxBars")[0];
        var jamountsCnt = jdeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        jamountsCnt.innerHTML = "";
        //Retiro
        var jwithdraw = juridic.getElementsByClassName("maxBars2")[0];
        var jamountsCntwd = jwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        jamountsCntwd.innerHTML = "";
        //Transferencia
        var jxfer = juridic.getElementsByClassName("maxBars1")[0];
        var jamountsCntx = jxfer.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        jamountsCntx.innerHTML = "";
        //Intercambios
        var jexchg = juridic.getElementsByClassName("maxBars2")[1];
        var jamountsCntexchg = jexchg.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        jamountsCntexchg.innerHTML = "";


        //Ubicamos las tablas a llenar (natural)
        var natural = nwnode.getElementsByClassName("Natural")[0];
        //Depositos
        var ndeposit = natural.getElementsByClassName("maxBars")[0];
        var namountsCnt = ndeposit.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        namountsCnt.innerHTML = "";
        //Retiro
        var nwithdraw = natural.getElementsByClassName("maxBars2")[0];
        var namountsCntwd = nwithdraw.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        namountsCntwd.innerHTML = "";
        //Transferencia
        var nxfer = natural.getElementsByClassName("maxBars1")[0];
        var namountsCntx = nxfer.getElementsByClassName("maxLineBar")[0];
        namountsCntx.innerHTML = "";
        //Intercambios
        var nexchg = natural.getElementsByClassName("maxBars2")[1];
        var namountsCntexchg = nexchg.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
        namountsCntexchg.innerHTML = "";

        for (var i = 0; i < rates.length; i++) {
            //Moneda
            var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
            var span = document.createElement("span");
            span.innerHTML = rates[i].symbol;
            span.setAttribute("id", "currencyMin" + i);
            span.setAttribute("currencyid", rates[i].id);
            span.setAttribute("rate", rates[i].rate.number);
            span.setAttribute("decim", rates[i].decimals);
            if (rates[i].id < 0) span.classList.add("refcurrMin");
            maxbar.appendChild(span);
            currcnt.appendChild(maxbar);

            /*****NATURAL***/
            /**Deposito**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minnatural.deposits.numeric);//Funcionamiento campos amount
            input.value = rates[i].minnatural.deposits.formatted;
            input.setAttribute("id", (i + "natdepmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            namountsCnt.appendChild(maxbar);

            /**Retiro**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minnatural.withdrawals.numeric);//Funcionamiento campos amount
            input.value = rates[i].minnatural.withdrawals.formatted;
            input.setAttribute("id", (i + "natwithdmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            namountsCntwd.appendChild(maxbar);

            /**Transferencia**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minnatural.xfer.numeric);//Funcionamiento campos amount
            input.value = rates[i].minnatural.xfer.formatted;
            input.setAttribute("id", (i + "natxfermin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            namountsCntx.appendChild(maxbar);

            /**Intercambios**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minnatural.exchanges.numeric);//Funcionamiento campos amount
            input.value = rates[i].minnatural.exchanges.formatted;
            input.setAttribute("id", (i + "natexchgmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            namountsCntexchg.appendChild(maxbar);

            /*******JURIDICO*******/
            /**Deposito**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minjuridic.deposits.numeric);//Funcionamiento campos amount
            input.value = rates[i].minjuridic.deposits.formatted;
            input.setAttribute("id", (i + "juddepmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            jamountsCnt.appendChild(maxbar);
            /**Retiro**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minjuridic.withdrawals.numeric);//Funcionamiento campos amount
            input.value = rates[i].minjuridic.withdrawals.formatted;
            input.setAttribute("id", (i + "judwithdmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            jamountsCntwd.appendChild(maxbar);
            /**Transferencia**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minjuridic.xfer.numeric);//Funcionamiento campos amount
            input.value = rates[i].minjuridic.xfer.formatted;
            input.setAttribute("id", (i + "judxfermin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            jamountsCntx.appendChild(maxbar);
            /**Intercambios**/
            //Crear linea amount
            var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
            var input = document.createElement("input");

            input.setAttribute("currpos", i);
            input.setAttribute("dataNumber", rates[i].minjuridic.exchanges.numeric);//Funcionamiento campos amount
            input.value = rates[i].minjuridic.exchanges.formatted;
            input.setAttribute("id", (i + "judexchgmin"));
            if (rates[i].id > 0) {
                input.setAttribute("disabled", "");
                maxbar.style.backgroundColor = "rgb(153 153 153 / 0.3)";
            }
            maxbar.appendChild(input);
            jamountsCntexchg.appendChild(maxbar);
        }
        tbl.appendChild(nwnode);

        //Se recorren los campos y se les da formato y funcionamiento
        var fds = nwnode.getElementsByTagName("input");
        var list = [];
        for (var y = 0; y < fds.length; y++) {
            fds[y].setAttribute("type", "text");
            fds[y].addEventListener("focusin", function () {
                decimCoin = document.getElementById("currencyMin" + this.getAttribute("currpos")).getAttribute("decim");
            });
            list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto

            fds[y].addEventListener("keydown", function (e) {
                if (e.keyCode == 13) {
                    this.setAttribute("dataNumber", this.value);
                }
            });
            //Guardar
            fds[y].addEventListener("change", function () {
                saveMins(this);//Siempre que haya un change se guarda
                var refcurrid = document.getElementsByClassName("refcurrMin")[0].getAttribute("id");
                var poscurr = refcurrid.split("currencyMin")[1];
                if (this.getAttribute("currpos") == poscurr) {
                    //Si es el primero se recalcula el resto según las tasas
                    var cnt = this.parentElement.parentElement;
                    var inptcnt = cnt.getElementsByTagName("input");
                    for (var i = 0; i < inptcnt.length; i++) {
                        if (inptcnt[i].getAttribute("id") !== this.getAttribute("id")) {
                            var rate = document.getElementById("currencyMin" + inptcnt[i].getAttribute("currpos")).getAttribute("rate");
                            var newval = this.value * rate;
                            inptcnt[i].setAttribute("dataNumber", newval);
                            inptcnt[i].dispatchEvent(new Event("focusin")); inptcnt[i].dispatchEvent(new Event("focusout"));
                            inptcnt[i].dispatchEvent(new Event("change"));
                        }
                    }
                    decimCoin = document.getElementById("currencyMin" + this.getAttribute("currpos")).getAttribute("decim");
                }
            });
        }
        formatAmount(list);

    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
function saveMins(ele) {
    setTimeout(function () {
        var par = {};
        var cnt = ele.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
        var usertype = "";
        var typeatr = "";
        if (cnt.classList.contains("Natural")) {
            usertype = "1";
            typeatr = "nat";
        } else {
            usertype = "2";
            typeatr = "jud";
        }
        par.usertype = usertype;
        var poscurr = ele.getAttribute("currpos");
        var levelpos = ele.getAttribute("currpos");
        par.currencyid = document.getElementById("currencyMin" + poscurr).getAttribute("currencyid");


        par.mindeposit = document.getElementById(poscurr + typeatr + "depmin").getAttribute("dataNumber");
        par.minexchange = document.getElementById(poscurr + typeatr + "exchgmin").getAttribute("dataNumber");
        par.minwithdraw = document.getElementById(poscurr + typeatr + "withdmin").getAttribute("dataNumber");
        par.minxfer = document.getElementById(poscurr + typeatr + "xfermin").getAttribute("dataNumber");

        //Validar que el minimo no sea mayor que ningún tope máximo
        var tbl = document.getElementById("Section-max");
        var rows = tbl.getElementsByClassName("maxpag");
        for (var x = 0; x < rows.length; x++) {
            //Valores de maximos relativos al que se guarda (en todos los niveles)
            var maxdep = parseFloat(document.getElementById((x) + "" + poscurr + typeatr + "depamo").getAttribute("dataNumber"));
            var maxwithd = parseFloat(document.getElementById((x) + "" + poscurr + typeatr + "withdamo").getAttribute("dataNumber"));
            var maxxfer = parseFloat(document.getElementById((x) + "" + poscurr + typeatr + "xferamo").getAttribute("dataNumber"));

            if (parseFloat(par.mindeposit) > maxdep || parseFloat(par.minwithdraw) > maxwithd || parseFloat(par.minxfer) > maxxfer) {
                var msg = document.getElementById("messageApiMin");
                msg.innerHTML = "El monto mínimo no puede ser mayor a los montos máximos";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 4000);
                if (reloadEntry) {
                    entryLevel();
                    reloadEntry = false;
                }
                return;
            }

        }

        par.sessionid = sessionId;

        callWS("GET", "preferences/savemins", par, rspUserSaveRate);
    }, 50);

}

function paintTerms(terms, termsEng) {
    editor.setData(terms);
    editor2.setData(termsEng);
}

function saveTerms(termsEsp, termsEng) {
    let params = {};
    params.sessionid = sessionId;
    params.terms = termsEsp;
    params.terms_eng = termsEng;

    if (terms != '') {
        callWS('POST', 'preferences/saveterms', params, rspUserSaveTerms);
    }
}

function rspUserSaveTerms(status, rsp) {
    switch (status) {
        case 200:
            console.log(JSON.parse(rsp));
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}
