window.onload = function () {
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    loadCur('', 1, 0, 1000, sessionId) == 1;
    document.getElementById("closeModal").addEventListener("click", function () {
        var modal = document.getElementById("myModal");
        var dataDelete = document.getElementById("dataDelete");
        dataDelete.innerHTML = "";
        modal.style.display = "none";
    });

    document.getElementById("closeSectionAdd").addEventListener("click", function () {
        var sectionAddCurrencie = document.getElementById("addCurrencie");
        sectionAddCurrencie.style.display = "none";
    });

    document.getElementById("arrowOrderBy").addEventListener("mouseover", function () {
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content = iconContainer.parentElement;
        content.removeChild(iconContainer);
        setTimeout(function () {
            content.appendChild(node);
        }, 2000);
    });

    document.getElementById("arrowCurrencyDecimals").addEventListener("mouseover", function () {
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content = iconContainer.parentElement;
        content.removeChild(iconContainer);
        setTimeout(function () {
            content.appendChild(node);
        }, 2000);
    });

    var selectOrderBy = document.getElementById("orderBy");
    selectOrderBy.addEventListener("change", function () {
        var nodeNoDelete = document.getElementById("noCurrencieDefine");
        if (nodeNoDelete) {
            var nodeClone = nodeNoDelete.cloneNode(true);
        }
        //var table = document.getElementById("bodyTableCurrencies").innerHTML = "";
        LoadCurrencies('', selectOrderBy.value, 0, 10, sessionId);
        //table.appendChild(nodeClone);
    });

    //Asignar evento varra de busqueda
    document.getElementById("search").addEventListener("change", function () {
        LoadCurrencies(this.value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    document.getElementById("search").addEventListener("keyup", function (e) {
        if (e.keyCode == 13) LoadCurrencies(this.value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });

    //Asignación de confirmar delete
    document.getElementById("buttonCancelModal").addEventListener("click", function () {
        var modal = document.getElementById("myModal");
        var dataDelete = document.getElementById("dataDelete");
        dataDelete.innerHTML = "";
        modal.style.display = "none";
    });

    document.getElementById("buttonAceptModal").addEventListener("click", function () {
        DeleteCurrencie(this.getAttribute("eleid"));
        var modal = document.getElementById("myModal");
        var dataDelete = document.getElementById("dataDelete");
        dataDelete.innerHTML = "";
        modal.style.display = "none";
    });

    document.getElementById("iconAddCurrencie").addEventListener("click", function () {
        var msg = document.getElementById("messageApi");
        if (document.getElementById("iconAddCurrencie").dataset.privilegeCreate == "1") {
            var sessionId = sessionStorage.getItem("sessionId");
            var inputNameAdd = document.getElementById("addCurrencieName");
            var inputSymbolAdd = document.getElementById("addCurrencieSymbol");
            var inputDecimalsAdd = document.getElementById("addCurrencieDecim");

            req = {};
            req.id = 0;
            req.date = inputNameAdd.value;
            req.amount = inputSymbolAdd.value;
            req.currencyid = inputDecimalsAdd.value;
            req.sessionid = sessionId;
            console.log(req)
            if (req.id === "" || req.id === " " || req.date === "" || req.date === " " || req.amount === "" || req.amount === " " || req.currencyid === "" || req.currencyid === " ") {
                msg.innerHTML = "Debe agregar datos válidos para crear una tasa.";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 5000);
            } else {
                sendApiUpdate(req);
            }
        } else {
            msg.innerHTML = "No posee privilegios para crear una tasa";
            msg.style.display = "block";
            msg.classList.add("msgError");
            setTimeout(function () {
                msg.classList.remove("msgError");
                msg.style.display = "none";
            }, 3000);
        }
    });



    //Pintar iconos archivo global icons
    //drawIconsList(icons);

    //MOSTRAR PRIVILEGIOS AGREGAR
    /*document.getElementById("addCurrencieIc").addEventListener("click", function(ev){
        if(ev.target != this) return false;
        var lista = this.getElementsByClassName("privList")[0];
        if(lista.style.display !== "")
            hidePopPriv();
        else
            showPopPriv(this);
    });
        
    document.getElementById("addCurrencieIc").firstElementChild.addEventListener("click",function(){
        this.parentElement.dispatchEvent(new Event("click")); 
    });
    
    document.getElementById("addCurrencieDecim").addEventListener("change",function(){
        if(this.value !== "")this.classList.remove("placehColor");
        else this.classList.add("placehColor");
    });*/

    /*funcion del ordenar**/

    var orderDirect = document.getElementById("orderDirect");
    if (orderDirect !== null) {
        orderDirect.addEventListener("change", function () {
            document.getElementById("orderBy").dispatchEvent(new Event("change"));
        });
    }
}

function LoadCurrencies(filter, order, offset, numofrec, sessionid) {
    ;
    var par = {};
    hidePopPriv();
    //Para no acomodar en todos los lugares dónde pusiste la función leo si es vacío busco en el valor del search
    //Lo correcto sería pasar el document.getElementById("search").value por el parametro.
    if (filter === "") filter = document.getElementById("search").value;
    par.filter = filter;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if (dir == "desc") order = "-" + order;
    par.order = order;
    par.offset = offset;
    par.numofrec = numofrec;
    par.sessionid = sessionid;
    callWS("GET", "rates/history", par, respuesta);
    function respuesta(status, rsp) {
        let rates = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                console.log(rates);

                if (rates.privileges.create == false || rates.privileges.create == "false") {
                    document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "0";
                } else {
                    document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "1";
                }

                if (rates.privileges.read == false || rates.privileges.read == "false") {
                    document.getElementById("noCurrencieDefine").style.display = "flex";
                    document.getElementById("msgInTable").innerHTML = "No Posee privilegios de lectura";
                } else {
                    if (rates.numofrecords === 0) {
                        /*Blanquear tabla*/
                        var nodeNoDelete = document.getElementById("noCurrencieDefine");
                        if (nodeNoDelete) {
                            var nodeClone = nodeNoDelete.cloneNode(true);
                            nodeClone.style.display = "none";
                        }
                        var table = document.getElementById("bodyTableCurrencies");
                        table.innerHTML = "";
                        if (nodeClone !== undefined && nodeClone !== null) table.appendChild(nodeClone);
                        /**-hasta aqui-**/
                        document.getElementById("noCurrencieDefine").style.display = "flex";
                        document.getElementById("msgInTable").innerHTML = "No Posee Tasas definidas";
                        document.getElementById("paginator").style.display = "none";
                    } else {

                        if (rates.numofrecords <= 10) {
                            document.getElementById("paginator").style.display = "none";
                        } else {
                            document.getElementById("paginator").style.display = "";
                            drawPags(rates.numofrecords, "numbersPaginator");
                        }
                        /*Blanquear tabla*/
                        var nodeNoDelete = document.getElementById("noCurrencieDefine");
                        if (nodeNoDelete) {
                            var nodeClone = nodeNoDelete.cloneNode(true);
                            nodeClone.style.display = "none";
                        }
                        var table = document.getElementById("bodyTableCurrencies");
                        table.innerHTML = "";
                        if (nodeClone !== undefined && nodeClone !== null) table.appendChild(nodeClone);
                        /**-hasta aqui-**/
                        //Pintar registros
                        paintRowsCurrencies(rates);
                    }
                }
                break;
            case 400:
                msg.innerHTML = currencies.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
                break;
            case 401:
                msg.innerHTML = "Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    myLogout()
                    msg.style.display = "none";
                }, 3000);
                break;
            case 403:
                var msg = document.getElementById("messageApi");
                msg.innerHTML = "No posee privilegios de lectura";
                msg.classList.add("msgError");
                msg.style.display = "block";
                break;
            case 500:
                console.log(currencies);
                msg.innerHTML = " Error Interno";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            default:
                msg.innerHTML = currencies.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
        }
    }
}
var pagerNumber = 10;
function drawPags(numofrecords, tbl) {
    var pages = Math.ceil(numofrecords / pagerNumber);
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if (numbersPaginator.getElementsByClassName("pSelect").length > 0) {
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
    }
    numbersPaginator.innerHTML = "";

    var initialPage = 0;
    var n = 8;
    if (pages > n) {  // cambio de formato en caso de mas de n paginas
        initialPage = Math.max((lastPag - Math.ceil(n / 2) + 2), 1) - 1;
    }

    // puntitos iniciales cuando son más de 10 página y no se empieza por la primera
    if (pages > n && initialPage !== 0 && initialPage !== 1) {
        spanF = document.createElement("div");
        spanF.classList.add("pages");
        spanF.innerHTML = "1 ...";
        spanF.dataset.page = 1;
        spanF.style.cursor = "pointer";
        spanF.addEventListener("click", function () {
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) pSel[0].classList.remove("pSelect");

            //Se actualiza la página seleccionada
            this.classList.add("pSelect");

            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page") - 1) * pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            LoadCurrencies(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanF);
        /*
        span = document.createElement("div");
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);*/

    }

    //Pintar paginas de table (numeros)
    for (var k = initialPage; k < pages && !(k - initialPage > n - 1); k++) {
        var p = document.createElement("div");
        p.classList.add("pages");
        p.innerHTML = k + 1;
        p.dataset.page = k + 1;
        if (lastPag == 0 && k == 0) p.classList.add("pSelect");//Se selecciona la página 1
        else if (lastPag !== 0 && (lastPag - 1) == k) p.classList.add("pSelect");

        p.addEventListener("click", function () {
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) pSel[0].classList.remove("pSelect");

            //Se actualiza la página seleccionada
            this.classList.add("pSelect");

            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page") - 1) * pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            LoadCurrencies(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        p.style.cursor = "pointer";
        numbersPaginator.appendChild(p);

    }

    // puntitos si no se ven las útlimas páginas
    if (pages > n && initialPage + n < pages) {
        /*
        span = document.createElement("div");
        span.setAttribute("title", pages+" páginas")
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);
        */

        spanL = document.createElement("div");
        spanL.classList.add("pages");
        spanL.innerHTML = "... " + pages;
        spanL.dataset.page = pages;
        spanL.style.cursor = "pointer";
        spanL.addEventListener("click", function () {
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) pSel[0].classList.remove("pSelect");

            //Se actualiza la página seleccionada
            this.classList.add("pSelect");

            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page") - 1) * pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            LoadCurrencies(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanL);
    }



    //Asignación de eventos validar que sólo se haga una vez
    if (numbersPaginator.getAttribute("arrowsEvent") == "false") {
        var leftArrow = numbersPaginator.previousElementSibling;
        var rightArrow = numbersPaginator.nextElementSibling;
        //Evento flecha izquierda
        leftArrow.addEventListener("click", function () {
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) {
                //Si el elemento anterior al seleccionado es una pagina
                if (pSel[0].previousElementSibling != undefined) {
                    if (pSel[0].previousElementSibling.classList.contains("pages")) {
                        var last = pSel[0];
                        pSel[0].previousElementSibling.classList.add("pSelect");
                        last.classList.remove("pSelect");
                        //Se repinta el listado desde el offset seleccionado
                        var offset = (pSel[0].innerHTML - 1) * pagerNumber;
                        var order = document.getElementById("orderBy").value;
                        var filter = document.getElementById("search").value;
                        LoadCurrencies(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                    }
                }
            }
        });
        //Evento flecha derecha
        rightArrow.addEventListener("click", function () {
            var pSel = document.getElementsByClassName("pSelect");
            if (pSel.length > 0) {
                //Si el elemento anterior al seleccionado es una pagina
                if (pSel[0].nextElementSibling != undefined) {
                    if (pSel[0].nextElementSibling.classList.contains("pages")) {
                        pSel[0].nextElementSibling.classList.add("pSelect");
                        pSel[0].classList.remove("pSelect");

                        //Se repinta el listado desde el offset seleccionado
                        var offset = (pSel[0].innerHTML - 1) * pagerNumber;
                        var order = document.getElementById("orderBy").value;
                        var filter = document.getElementById("search").value;
                        LoadCurrencies(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                    }
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent", true);
    }
    var leftArrow = numbersPaginator.previousElementSibling;
    var rightArrow = numbersPaginator.nextElementSibling;
    if (pages <= 1) {
        leftArrow.style.visibility = "hidden";
        rightArrow.style.visibility = "hidden";
    }

}
function loadCur(filter, order, offset, numofrec, sessionid) {
    var par = {};
    //Se pasa el document.getElementById("search").value por el parametro filter.
    par.filter = filter;
    par.order = '1'
    par.offset = offset;
    par.numofrec = numofrec;
    par.sessionid = sessionid;
    //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "currencies/list", par, respCountries);

    function respCountries(status, rsp) {
        let countries = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                console.log(countries);
                var countriesList = document.getElementById("addCurrencieDecim");
                countriesList.innerHTML = "";
                for (let i = 0; i < countries.records.length; i++) {
                    var op = document.createElement("option");
                    if (countries.records.length == 0) {
                        op.text = "No hay monedas definidos";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        countriesList.appendChild(op);
                    } else {
                        //Antes se validaban sólo los activos pero entonces en historico desaparece una si se desactiva
                        //if(countries.records[i].status.id == 1){
                        op.text = countries.records[i].symbol;
                        op.value = countries.records[i].id;
                        countriesList.appendChild(op);
                        //}
                    }
                }
                var filter = document.getElementById("search").value;
                if (filter == null || filter == undefined) {
                    filter = '';
                }
                LoadCurrencies('', -1, 0, 10, sessionid);
                break;


            case 403:
                var countriesList = document.getElementById("addCurrencieDecim");
                var op = document.createElement("option");
                op.text = "País";
                op.disabled = true;
                op.value = " ";
                op.selected = true;
                countriesList.appendChild(op);
                var filter = document.getElementById("search").value;
                if (filter == null || filter == undefined) {
                    filter = '';
                }
                LoadCurrencies('', -1, 0, 10, sessionid);
                break;
            case 400:
            /*msg.innerHTML=countries.msg;
            msg.classList.add("msgError");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError");   
                msg.style.display="none";
            }, 100000);
            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 500:
            /*msg.innerHTML=" Error Interno";
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError"); 
                msg.style.display="none";
            }, 3000);
            break;*/
            default:
            /*msg.innerHTML=countries.msg;
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError"); 
                msg.style.display="none";
            }, 3000);*/
        }
    }
}
function EditCurrencie(id) {
    let i = id.replace("liCurrencie", "");
    var parent = document.getElementById(id);
    var inputNameEdit = document.getElementById("inputName" + i);
    var inputSymbolEdit = document.getElementById("inputSymbol" + i);
    var inputStatusEdit = document.getElementById("inputStatus" + i);
    var iconDeleteClear = document.getElementById("iconDelete" + i);
    var inputInterfaceEdit = document.getElementById("inputInterface" + i);
    //var inputTransEdit = document.getElementById("inputTrans"+i);
    var inputDecimEdit = document.getElementById("inputDecim" + i);
    //var inputIcon = document.getElementById("inputPriv"+i);
    var pAvailable = document.getElementById("p" + i);
    var pDisabled = document.getElementById("pEdit" + i);
    inputNameEdit.disabled = false;
    inputSymbolEdit.disabled = false;
    inputDecimEdit.disabled = false;
    //inputTransEdit.disabled = false;
    inputInterfaceEdit.disabled = false;
    //inputIcon.style.pointerEvents = "";
    //inputStatusEdit.disabled = false;
    pAvailable.style.visibility = "hidden";
    pAvailable.style.position = "absolute";
    pDisabled.style.visibility = "visible";
    pDisabled.style.position = "relative";
    parent.style.backgroundColor = "rgba(66, 135, 206, 0.1)";
    inputNameEdit.focus();
}

function DeleteCurrencie(id) {
    var sessionId = sessionStorage.getItem("sessionId");
    var li = document.querySelectorAll('[data-id="' + id + '"]');
    var liIdx = li[0].id;
    //console.log("liIdx", liIdx)
    rowError = document.getElementById(liIdx);
    //console.log("rowError ", rowError);
    let i = liIdx.substr(liIdx.length - 1);
    //console.log("rowError id ", id);
    req = {};
    req.id = id;
    req.sessionid = sessionId;
    callWS("GET", "rates/delete", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp) {
            let respuesta = JSON.parse(rsp);
        }
        var msg = document.getElementById("messageApi")
        switch (status) {
            case 200:
                var nodeNoDelete = document.getElementById("noCurrencieDefine");
                if (nodeNoDelete) {
                    var nodeClone = nodeNoDelete.cloneNode(true);
                }
                var table = document.getElementById("bodyTableCurrencies");
                table.innerHTML = "";
                document.getElementById("addCurrencieName").value = "";
                document.getElementById("addCurrencieSymbol").value = "";
                //document.getElementById("addCurrencieStatus").value ="";
                //document.getElementById("swichUserAdd").classList.add("active");
                //document.getElementById("addCurrencieStatus").dispatchEvent(new Event("change"));
                var pageInPaginator = document.getElementsByClassName("pSelect")[0];
                let offSetDelete = 0;
                if (pageInPaginator) {
                    pageInPaginator = pageInPaginator.innerHTML;
                    offSetDelete = (pageInPaginator - 1) * 10;
                }

                LoadCurrencies('', document.getElementById("orderBy").value, offSetDelete, 10, req.sessionid);
                table.appendChild(nodeClone);
                //Mensaje SUCESS
                msg.innerHTML = "Tasa Eliminada Correctamente";
                msg.classList.add("msgSucess");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 304:
                var rowErrorColor = 'white';
                if (rowError.classList.contains('rowImpar')) {
                    rowErrorColor = "rgba(245, 246, 248, 1)"
                }
                rowError.style.backgroundColor = "#FAE5E8";
                msg = document.getElementById("msgErrorliCurrencie" + i);
                msg.innerHTML = "Existen dependencias que no permiten eliminar esta Tasa"
                msg.classList.add("msgErrorLi");
                msg.style.display = "block";
                setTimeout(function () {
                    rowError.style.backgroundColor = rowErrorColor;
                    msg.classList.remove("msgErrorLi");
                    msg.style.display = "none";
                    msg = document.getElementById("messageApi")
                }, 3000);
                break;

            case 400:
                msg.innerHTML = respuesta.msg
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                msg.innerHTML = "Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                    myLogout();
                }, 3000);
                break;

            case 403:
                msg.innerHTML = "No posee los privilegios para actualizar Tasas."
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                msg.innerHTML = "Error al actualizar Tasa, intente nuevamente."
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            default:
                msg.innerHTML = respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
        }
    }
}

function UpdateCurrencies(id) {
    var sessionId = sessionStorage.getItem("sessionId");
    let i = id.replace("liCurrencie", "");

    var parent = document.getElementById(id)
    var inputNameEdit = document.getElementById("inputName" + i);
    var inputSymbolEdit = document.getElementById("inputSymbol" + i);
    var inputDecimEdit = document.getElementById("inputDecim" + i);


    req = {};
    req.id = parent.getAttribute('data-id');
    req.date = inputNameEdit.value;
    req.amount = inputSymbolEdit.value;

    req.currencyid = inputDecimEdit.value;

    req.sessionid = sessionId;

    if (req.id === "" || req.id === " " || req.date === "" || req.date === " " || req.amount === "" || req.mount === " " || req.currencyid == "") {
        var msg = document.getElementById("messageApi");
        msg.innerHTML = "Debe agregar datos válidos para actualizar una tasa";
        msg.classList.add("msgError");
        msg.style.display = "block";
        setTimeout(function () {
            msg.classList.remove("msgError");
            msg.style.display = "none";
        }, 5000);
    } else {
        sendApiUpdate(req);
    }


}

function CancelEditCurrencie(id) {
    let i = id.replace("liCurrencie", "");
    document.getElementById("liCurrencie" + i).style.backgroundColor = "";
    var inputNameEdit = document.getElementById("inputName" + i);
    var inputSymbolEdit = document.getElementById("inputSymbol" + i);
    var inputInterfaceEdit = document.getElementById("inputInterface" + i);
    var iconDeleteClear = document.getElementById("iconDelete" + i);
    var inputTransEdit = document.getElementById("inputTrans" + i);
    var inputDecimEdit = document.getElementById("inputDecim" + i);
    var pAvailable = document.getElementById("p" + i);
    var pDisabled = document.getElementById("pEdit" + i);
    inputNameEdit.disabled = true;
    inputSymbolEdit.disabled = true;
    inputDecimEdit.disabled = true;
    inputInterfaceEdit.disabled = true;
    hidePopPriv();
    pAvailable.style.visibility = "visible";
    pAvailable.style.position = "relative";
    pDisabled.style.visibility = "hidden";
    pDisabled.style.position = "absolute";
}

function ConfirmDeleteCurrencie(id) {
    var parent = document.getElementById(id);
    var idCurrencie = parent.getAttribute('data-id');
    let i = id.replace("liCurrencie", "");

    var amount = document.getElementById("inputSymbol" + i).value;
    var selcur = document.getElementById("inputDecim" + i);
    var currency = selcur.options[selcur.selectedIndex].text;
    var sel = document.getElementById("inputInterface" + i);
    var ves = sel.options[sel.selectedIndex].text;
    var modal = document.getElementById("myModal");
    var dataDelete = document.getElementById("dataDelete");
    dataDelete.innerHTML = "";
    var curr = document.createElement("li");
    curr.innerHTML = "Tasa: " + ves + " - " + amount + " - " + currency;
    curr.style.fontWeight = "normal"
    dataDelete.appendChild(curr);
    modal.style.display = "block";

    document.getElementById("buttonAceptModal").setAttribute("eleid", idCurrencie);
}

function sendApiUpdate(req) {
    req.amount = (req.amount).replaceAll('.', '');
    req.amount = (req.amount).replace(',', '.');
    callWS("POST", "rates/update", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp !== "") var respuesta = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        // console.log("sendApiUpdate", respuesta, "status", status)
        switch (status) {
            case 200:
                if (req.id === 0) {
                    document.getElementById("addCurrencieName").value = "";
                    document.getElementById("addCurrencieSymbol").value = "";
                    //document.getElementById("swichUserAdd").classList.add("active");
                    document.getElementById("addCurrencieDecim").value = "";
                    document.getElementById("addCurrencieDecim").classList.add("placehColor");
                    //Blanco campo icono
                    hidePopPriv();

                    msg.innerHTML = "Tasa creada correctamente";
                } else {
                    msg.innerHTML = "Tasa actualizada correctamente";
                }
                msg.classList.add("msgSucess");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.style.display = "none";
                }, 3000);
                var nodeNoDelete = document.getElementById("noCurrencieDefine");
                if (nodeNoDelete) {
                    var nodeClone = nodeNoDelete.cloneNode(true);
                }
                var table = document.getElementById("bodyTableCurrencies");
                table.innerHTML = "";
                var pageInPaginator = document.getElementsByClassName("pSelect")[0];
                var offSetPageAdd = 0;
                if (pageInPaginator) {
                    pageInPaginator = pageInPaginator.innerHTML;
                    offSetPageAdd = (pageInPaginator - 1) * 10;
                }
                LoadCurrencies('', document.getElementById("orderBy").value, offSetPageAdd, 10, req.sessionid);
                table.appendChild(nodeClone);
                break;

            case 304://Registro sin modificar
                msg.innerHTML = "No se realizaron cambios a la tasa";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                var nodeNoDelete = document.getElementById("noCurrencieDefine");
                if (nodeNoDelete) {
                    var nodeClone = nodeNoDelete.cloneNode(true);
                }
                var table = document.getElementById("bodyTableCurrencies");
                table.innerHTML = "";
                var pageInPaginator = document.getElementsByClassName("pSelect")[0];
                var offSetPageAdd = 0;
                if (pageInPaginator) {
                    pageInPaginator = pageInPaginator.innerHTML;
                    offSetDelete = (pageInPaginator - 1) * 10;
                }
                LoadCurrencies('', document.getElementById("orderBy").value, offSetPageAdd, 10, req.sessionid);
                table.appendChild(nodeClone);
                break;
            case 400:
                msg.innerHTML = respuesta.msg
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                msg.innerHTML = "Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                    myLogout();
                }, 3000);
                break;

            case 403:
                msg.innerHTML = "No posee los privilegios para actualizar tasas."
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 405:
                const switchbg = document.getElementById('userStatus' + req.id);
                if (switchbg.classList.contains("active")) {
                    switchbg.classList.remove("active");
                    switchbg.firstElementChild.classList.remove("balActive");
                } else {
                    switchbg.classList.add("active");
                    switchbg.firstElementChild.classList.add("balActive");
                }
                msg.innerHTML = respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                msg.innerHTML = respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            default:
                msg.innerHTML = respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
        }
    }

}


function paintRowsCurrencies(rates) {
    var msg = document.getElementById("messageApi");// para errores
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if (pageInPaginator) {
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    var filas;
    if (rates.numofrecords > 10) {
        filas = parseInt(rates.numofrecords) - ((parseInt(pageInPaginator) - 1) * 10);
        if (filas > 10) {
            filas = 10;
        }
    } else {
        filas = rates.numofrecords
    }
    for (let i = 0; i < filas; i++) {
        var divCell = "";

        var divContent = document.createElement("div");
        var inputName = document.createElement("input");
        var inputSymbol = document.createElement("input");
        var inputStatus = document.createElement("select");
        var inputInterface = document.createElement("select");
        var inputTrans = document.createElement("select");
        var p = document.createElement("p");
        var p2 = document.createElement("p");
        var iconEdit = document.createElement("i");
        var iconDelete = document.createElement("i");
        var iconDone = document.createElement("i");
        var iconCancel = document.createElement("i");
        const index = i;

        divCell = document.createElement("div");
        divCell.classList.add("tableCell");
        divCell.style.width = "60px";

        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-edit");
        iconEdit.setAttribute("id", "iconEdit" + index);
        var id = rates.records[i].symbol;
        if (!(rates.privileges.update == false || rates.privileges.update == "false")) {
            iconEdit.addEventListener("click", function () {
                EditCurrencie("liCurrencie" + index)
            });
        } else {
            iconEdit.addEventListener("click", function () {
                msg.innerHTML = "No posee los privilegios para actualizar tasas.";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
            });

        }

        iconDelete.classList.add("fas");
        iconDelete.classList.add("fa-trash-alt");
        iconDelete.setAttribute("id", "iconDelete" + index);
        if (!(rates.privileges.delete == false || rates.privileges.delete == "false")) {
            iconDelete.addEventListener("click", function () {
                ConfirmDeleteCurrencie("liCurrencie" + index);
            });
        } else {
            iconDelete.addEventListener("click", function () {
                msg.innerHTML = "No posee los privilegios para eliminar tasas.";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
            });

        }

        p.setAttribute("id", "p" + index);
        p.appendChild(iconEdit);
        p.appendChild(iconDelete);
        p.classList.add("icAddCnt");
        p.style.visibility = "visible";
        p.style.position = "relative";

        iconDone.classList.add("fas");
        iconDone.classList.add("fa-check-circle");
        iconDone.style.color = "#4287CE";
        iconDone.setAttribute("id", "iconDone" + index);
        iconDone.addEventListener("click", function () {
            UpdateCurrencies("liCurrencie" + index);
        });

        iconCancel.classList.add("far");
        iconCancel.classList.add("fa-times-circle");
        iconCancel.style.color = "#4287CE";
        iconCancel.setAttribute("id", "iconCancel" + index);
        iconCancel.addEventListener("click", function () {
            CancelEditCurrencie("liCurrencie" + index);
        });

        p2.setAttribute("id", "pEdit" + index);
        p2.appendChild(iconDone);
        p2.appendChild(iconCancel);
        p2.classList.add("icAddCnt");
        p2.style.visibility = "hidden";
        p2.style.position = "absolute";

        divCell.appendChild(p);
        divCell.appendChild(p2);
        divContent.appendChild(divCell);


        var divCellNm = document.createElement("div");
        divCellNm.classList.add("tableCell");
        divCellNm.style.width = "24%";
        inputName.disabled = true;
        inputName.type = "datetime-local";
        inputName.style.textAlign = "center";
        inputName.classList.add("inputRow");
        inputName.setAttribute("id", "inputName" + index);
        inputName.value = (rates.records[i].datecreated.date).replace(" ", "T");
        divCellNm.appendChild(inputName);

        var divCellSm = document.createElement("div");
        divCellSm.classList.add("tableCell");
        divCellSm.style.width = "23%";
        inputSymbol.disabled = true;
        inputSymbol.classList.add("inputRow");
        inputSymbol.setAttribute("id", "inputSymbol" + index);
        inputSymbol.style.textAlign = "right";
        inputSymbol.value = rates.records[i].amount.formatted;
        divCellSm.appendChild(inputSymbol)

        var divCellInt = document.createElement("div");
        divCellInt.classList.add("tableCell");
        divCellInt.style.width = "18%";
        var inputInterface = document.getElementById("addInterface").cloneNode(true);
        inputInterface.classList.add("inputRow", "inputRol");
        inputInterface.classList.remove("placehColor");
        inputInterface.setAttribute("id", "inputInterface" + index);
        inputInterface.classList.add("selectOrderBy");
        //inputInterface.removeChild(inputInterface.options[0]);
        inputInterface.disabled = true;
        inputInterface.style.width = "auto";
        inputInterface.style.display = "table";
        inputInterface.style.marginLeft = "auto";
        inputInterface.style.paddingRight = "0";
        inputInterface.value = 1;
        divCellInt.appendChild(inputInterface);


        inputStatus.disabled = true;
        inputStatus.classList.add("inputRow");
        inputStatus.classList.add("selectOrderBy");
        inputStatus.setAttribute("id", "inputStatus" + index);
        var optionAct = document.createElement("option");
        var optionInact = document.createElement("option");
        optionAct.value = "1";
        optionInact.value = "0";
        optionAct.innerHTML = "Activo";
        optionInact.innerHTML = "Inactivo";
        inputStatus.appendChild(optionAct);
        inputStatus.appendChild(optionInact);
        inputStatus.value = rates.records[i].status;


        var divCellDcm = document.createElement("div");
        divCellDcm.classList.add("tableCell");
        divCellDcm.style.width = "18%";
        var inputDecim = document.getElementById("addCurrencieDecim").cloneNode(true);
        inputDecim.classList.add("inputRow", "inputRol");
        inputDecim.classList.remove("placehColor");
        inputDecim.setAttribute("id", "inputDecim" + index);
        inputDecim.classList.add("selectOrderBy");
        inputDecim.disabled = true;
        inputDecim.style.width = "100%";
        inputDecim.style.minWidth = "85px";
        inputDecim.value = rates.records[i].currency.id;
        divCellDcm.appendChild(inputDecim);

        divContent.classList.add("rowCurrencie");
        if (i % 2 === 0) {
            divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liCurrencie" + index);
        divContent.dataset.id = rates.records[i].id;

        divContent.appendChild(divCellDcm);
        //divContent.appendChild(divCellSwch);
        divContent.appendChild(divCellNm);
        divContent.appendChild(divCellSm);
        //divContent.appendChild(divCellTrans);

        divContent.appendChild(divCellInt);
        //divContent.appendChild(divCellIc);
        divContent.appendChild(divCell);

        rowCurrencie.appendChild(divContent);
        var msgRow = document.createElement("p");
        msgRow.setAttribute("id", "msgErrorliCurrencie" + index);
        msgRow.classList.add("msgError");
        rowCurrencie.appendChild(msgRow);
    }

    for (let j = rates.numofrecords; j < 10; j++) {
        var divContent = document.createElement("div");
        var inputName = document.createElement("input");
        var inputSymbol = document.createElement("input");
        var inputStatus = document.createElement("select");
        const index = j;

        inputName.disabled = true;
        inputName.classList.add("inputRow");
        inputName.value = " ";

        inputSymbol.disabled = true;
        inputSymbol.classList.add("inputRow");
        inputSymbol.value = " ";

        inputStatus.disabled = true;
        inputStatus.classList.add("inputRow");
        inputStatus.classList.add("selectOrderBy");

        divContent.classList.add("rowCurrencie");
        if (j % 2 === 0) {
            divContent.classList.add("rowImpar");
        }
        divContent.appendChild(inputName);
        divContent.appendChild(inputSymbol);
        divContent.appendChild(inputStatus);
        divContent.style.display = "flex";
        divContent.style.cursor = "none";

        rowCurrencie.appendChild(divContent);
    }
}
function showPopPriv(ele) {
    var list = document.getElementsByClassName("privList");
    for (var i = 0; i < list.length; i++) {
        var privtbl = list[i];
        privtbl.style.opacity = "";
        privtbl.style.display = "";
    }

    var privtbl = ele.getElementsByClassName("privList")[0];
    privtbl.style.display = "block";
    setTimeout(function () {
        privtbl.style.opacity = "1";
    }, 300);
}
function hidePopPriv() {
    var list = document.getElementsByClassName("privList");
    for (var i = 0; i < list.length; i++) {
        if (list[i].style.display !== "") {
            list[i].style.opacity = "";
            var privtbl = list[i];
            setTimeout(function () {
                privtbl.style.display = "";
            }, 500);
        }
    }
}
function drawIconsList(rsp) {
    var tbl = document.getElementById("tblAddPriv");
    var node = tbl.firstElementChild.cloneNode(true);
    var tmp = null; tmp = node.cloneNode(true);
    tbl.innerHTML = "";
    if (!(rsp.length > 0)) {
        var ele = null;
        ele = tmp.cloneNode(true);
        ele.style.display = "none";
        tbl.appendChild(ele);
    } else {
        for (var i = 0; i < rsp.length; i++) {
            var ele = null;
            ele = tmp.cloneNode(true);
            ele.style.display = "";

            //Var icon
            var icon = "";
            icon = ele.firstElementChild;
            icon.setAttribute("style", "background-image:url('" + rsp[i].url + "')");
            icon.setAttribute("ref", rsp[i].name);
            icon.addEventListener("click", function () {
                var icCol = document.getElementById("addCurrencieIc").firstElementChild;
                var iconSel = icCol.parentElement.getElementsByClassName("iconSel");
                if (this.classList.contains("iconSel")) {
                    this.classList.remove("iconSel");

                    icCol.innerHTML = "Icon";
                    icCol.removeAttribute("style");
                } else {
                    if (iconSel.length > 0) iconSel[0].classList.remove("iconSel");
                    this.classList.add("iconSel");

                    icCol.innerHTML = "";
                    icCol.setAttribute("style", this.getAttribute("style"));

                }
            });

            tbl.appendChild(ele);
        }
    }
}