var sessionId = sessionStorage.getItem("sessionId");
let editor;
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;
        console.log(editor);
        
        const viewDocument = editor.editing.view.document;

        viewDocument.on( 'blur', ( evt, data ) => {
            console.log(editor.getData());
            saveTerms(editor.getData());
        } );
    
    } )
    .catch( error => console.error( error ));
    
    initApp();
    changebutt();
    entryLevel();
} 
function changebutt(){
    document.getElementById("descript").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-Desc").classList.remove("nShow");
    })
    document.getElementById("change").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-change").classList.remove("nShow");
    })
    document.getElementById("max").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-max").classList.remove("nShow");
    });
    document.getElementById("min").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-min").classList.remove("nShow");
    });
    document.getElementById("buySold").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-buy").classList.remove("nShow");
    })
    document.getElementById("portfolio").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-portfolio").classList.remove("nShow");
    })
    document.getElementById("terms").addEventListener("click", function(){
        document.querySelectorAll('[class^="buttonchange"]').forEach(function (elmt) {
            elmt.classList.remove("activeTab");
        });
        document.querySelectorAll('[class^="SuperContainer"]').forEach(function (element) {
            element.classList.add("nShow");
        });
        this.classList.add("activeTab");
        document.getElementById("Section-terms").classList.remove("nShow");
    });
}
var reloadEntry = true;
function entryLevel(){
var par = {};
    par.sessionid = sessionId;
    callWS("GET", "preferences/entry", par, rspUserEntryLevel);
    return 0;
}
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);
            paintTerms(resp.terms);
            setTimeout(function() {
                reloadEntry = true;
            }, 4000);
            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 paintLevels(data){
    var sectLevels = document.getElementById("Section-Desc");
    sectLevels.innerHTML = "";
    for (datos of data){
        var desc = document.createElement("div"); 
        desc.classList.add("descTab");
        desc.innerHTML = '<p class="level">'+datos.name+'</p>'+
                    '<textarea class="area" id="dscLevel-'+datos.level+'" name="Text1" cols="40" rows="4" value='+datos.dsc+'></textarea>';
        
        sectLevels.appendChild(desc);
        document.getElementById("dscLevel-"+datos.level).value = datos.dsc;
    }
    document.querySelectorAll('[id^="dscLevel-"]').forEach(function (element) {
        element.addEventListener('change', function (event) {
            var id = (this.id).split("-")[1];
            saveLevel(id,this.value);
        });
    });
    
}
function saveLevel(levelid,desc){
var par = {};
    par.levelids = levelid;
    par.dsc = desc;
    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:
            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)
                        element.dispatchEvent(new Event("change"));
                }
            });
        }
    }
    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)
                        element.dispatchEvent(new Event("change"));
                }
            });
        }
    }
    
    /**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)
                        element.dispatchEvent(new Event("change"));
                }
            });
        }
    }
    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)
                        element.dispatchEvent(new Event("change"));
                }
            });
        }
    }
}
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(){
                        
                        saveMaxs(this);//Siempre que haya un change se guarda
                        
                        var refcurrid = document.getElementsByClassName("refcurr")[0].getAttribute("id");
                        var poscurr = refcurrid.split("currency")[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(inptcnt[i].getAttribute("lvlpos")+"currency"+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(this.getAttribute("lvlpos")+"currency"+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 saveMaxs(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 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 = document.getElementById(poslvl+""+poscurr+typeatr+"depamo").getAttribute("dataNumber");
        par.opmensualdeposit = document.getElementById(poslvl+""+poscurr+typeatr+"depqty").value;
        par.maxmensualwithdraw = 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"));
            
        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-buy");
    //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("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
                    
                    //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){
    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.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(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(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");
        
        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");
        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+1)+""+poscurr+typeatr+"depamo").getAttribute("dataNumber"));
            var maxwithd = parseFloat(document.getElementById((x+1)+""+poscurr+typeatr+"withdamo").getAttribute("dataNumber"));
            var maxxfer = parseFloat(document.getElementById((x+1)+""+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;
        //debugger;
        callWS("GET", "preferences/savemins", par, rspUserSaveRate);
    },50);
    
}

function paintTerms(terms){
    editor.setData(terms);
}

function saveTerms(terms){
    let params = {};
    params.sessionid = sessionId;
    params.terms = terms;
    
    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);
    }
}