window.onload = function(){
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    LoadCurrencies('', 0, 0, 10, sessionId);
    
    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);
    });
    
    //Add Currencie status formato de place holder
    /*document.getElementById("addCurrencieStatus").addEventListener("change",function(){
        if(this.value !== "")this.classList.remove("placehColor");
        else this.classList.add("placehColor");
    });*/
    
    //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 inputInterface = document.getElementById("addInterface");
            var inputDecimalsAdd = document.getElementById("addCurrencieDecim");
            var inputIconName = document.getElementById("iconListAdd").getElementsByClassName("iconSel");
            if(inputIconName.length>0)inputIconName = inputIconName[0].getAttribute("ref");
            //var inputStatusAdd = document.getElementById("addCurrencieStatus");
            var status = document.getElementById("swichUserAdd");
                        
            req = {};
            req.id = 0;
            req.name = inputNameAdd.value;
            req.symbol = inputSymbolAdd.value;
            req.interface = inputInterface.value;
            req.decimals = inputDecimalsAdd.value;
            req.icon = inputIconName;
            if(status.classList.contains("active")){
                req.status = 1;
            } else {
                req.status = 0;
            }
            req.sessionid = sessionId;
            if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.symbol === "" || req.symbol === " " || req.status === "" || req.status === " "
            || req.decimals === "" || req.decimals === " " || req.interface === "" || req.interface === " "){
                msg.innerHTML= "Debe agregar datos v\u00E1lidos para crear una moneda";
                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 moneda";
            msg.style.display="block";
            msg.classList.add("msgError");
            setTimeout(function() {
                msg.classList.remove("msgError");
                msg.style.display="none";
            }, 3000);
        }
    });
    
    //Swich de status del agregar moneda
    document.getElementById("swichUserAdd").addEventListener("click",function(){
        if(this.classList.contains("active")){
            this.classList.remove("active");
            this.firstElementChild.classList.remove("balActive");
        }else{
            this.classList.add("active");
            this.firstElementChild.classList.add("balActive");
        } 
    });
    
    
    //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", "currencies/list", par, respuesta);
        function respuesta(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    console.log(currencies);
                    
                    if( currencies.privileges.create == false || currencies.privileges.create == "false"){
                        document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "0";
                    } else {
                        document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "1";
                    }
                    
                    if(currencies.privileges.read == false || currencies.privileges.read == "false"){
                        document.getElementById("noCurrencieDefine").style.display= "flex";
                        document.getElementById("msgInTable").innerHTML="No Posee privilegios de lectura";
                    } else {
                        if (currencies.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 Monedas definidas";
                            document.getElementById("paginator").style.display= "none";
                        } else {
                            
                            if(currencies.numofrecords <= 10){
                                document.getElementById("paginator").style.display= "none";    
                            } else {
                                document.getElementById("paginator").style.display= ""; 
                                drawPags(currencies.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(currencies);
                        }
                    }
                    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 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=currencies.msg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
        }
}

function drawPags(numofrecords, tbl){
    var pages = Math.ceil( numofrecords / 10 );
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if(numbersPaginator.getElementsByClassName("pSelect").length>0){
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
    }
    numbersPaginator.innerHTML = "";
    for(let k=0; k<pages; 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.innerHTML-1)*10;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            LoadCurrencies(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
        });
        p.style.cursor="pointer";
        numbersPaginator.appendChild(p);
                                
    }
    //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.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)*10;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    LoadCurrencies(filter, order, offset, 10, 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.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)*10;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    LoadCurrencies(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
                }
            }
        });
        
        //Evento flecha doble
        
        
        //Evento flecha doble derecha
        
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
}

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 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;
    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", "currencies/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= "Moneda 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 Moneda"
                    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 Monedas."
                    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 monedas, 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 inputStatusEdit = document.getElementById("inputStatus"+i);
    var status = document.getElementById("userStatus"+i);
    var inputDecimEdit = document.getElementById("inputDecim"+i);
    var inputInterfaceEdit = document.getElementById("inputInterface"+i);
    var inputIconName = document.getElementById("inputPriv"+i).getElementsByClassName("iconSel");
    if(inputIconName.length>0)inputIconName = inputIconName[0].getAttribute("ref");
            
    
    req = {};
    req.id = parent.getAttribute('data-id');
    req.name = inputNameEdit.value;
    req.symbol = inputSymbolEdit.value;
    req.interface = inputInterfaceEdit.value;
    req.decimals = inputDecimEdit.value;
    req.icon = inputIconName;
    //req.status = inputStatusEdit.value;
    if(status.classList.contains("active")){
        req.status = 1;
    } else {
        req.status = 0;
    }
    req.sessionid = sessionId;
    
    if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.symbol === "" || req.symbol === " " || req.status === "" || req.status === " " || req.decimals=="" || req.interface==""){
        var msg = document.getElementById("messageApi");
        msg.innerHTML= "Debe agregar datos v\u00E1lidos para actualizar una moneda";
        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 inputStatusEdit = document.getElementById("inputStatus"+i);
    var iconDeleteClear = document.getElementById("iconDelete"+i);
    var inputInterfaceEdit = document.getElementById("inputInterface"+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 = true;
    inputSymbolEdit.disabled = true;
    inputDecimEdit.disabled = true;
    inputInterfaceEdit.disabled = true;
    hidePopPriv();
    inputIcon.style.pointerEvents = "none";
    //inputStatusEdit.disabled = true;
    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 inputNameEdit = document.getElementById("inputName"+i).value;
    var modal = document.getElementById("myModal");
    var dataDelete = document.getElementById("dataDelete");
    dataDelete.innerHTML = "";
    var curr = document.createElement("li");
    curr.innerHTML = "Moneda: "+ inputNameEdit;
    curr.style.fontWeight= "normal"
    dataDelete.appendChild(curr);
    modal.style.display = "block";
    
    document.getElementById("buttonAceptModal").setAttribute("eleid",idCurrencie);
}

function sendApiUpdate(req){
    callWS("GET", "currencies/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();
                        var tblic = document.getElementById("iconListAdd");
                        if(tblic.getElementsByClassName("iconSel").length>0)
                            tblic.getElementsByClassName("iconSel")[0].classList.remove("iconSel");
                        tblic.previousElementSibling.innerHTML = "Icon"; 
                        tblic.previousElementSibling.removeAttribute("style");
                        
                        
                        
                        msg.innerHTML= "Moneda creada correctamente";
                    } else {
                        msg.innerHTML= "Moneda 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 moneda";
                        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 Monedas."
                    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 monedas, 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 paintRowsCurrencies(currencies){
    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 (currencies.numofrecords > 10){
        filas = parseInt(currencies.numofrecords) - ((parseInt(pageInPaginator) - 1) * 10);
        if(filas > 10){
            filas = 10;
        }
    } else {
        filas = currencies.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 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= currencies.records[i].symbol;
        if( !(currencies.privileges.update == false || currencies.privileges.update == "false")){
            iconEdit.addEventListener("click", function(){
                EditCurrencie("liCurrencie"+index)
            });
        }else{
            iconEdit.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para actualizar monedas.";
                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( !(currencies.privileges.delete == false || currencies.privileges.delete == "false")){
            iconDelete.addEventListener("click", function(){
                ConfirmDeleteCurrencie("liCurrencie"+index);
            });
        }else{
            iconDelete.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para eliminar monedas.";
                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 = "auto";
        inputName.disabled=true;
        inputName.classList.add("inputRow");
        inputName.setAttribute("id", "inputName"+index);
        inputName.value = currencies.records[i].name;
        divCellNm.appendChild(inputName);
        
        var divCellSm = document.createElement("div");
        divCellSm.classList.add("tableCell");
        divCellSm.style.width = "15%";
        inputSymbol.disabled=true;
        inputSymbol.classList.add("inputRow");
        inputSymbol.setAttribute("id", "inputSymbol"+index);
        inputSymbol.style.textAlign = "center";
        inputSymbol.value = currencies.records[i].symbol;
        divCellSm.appendChild(inputSymbol)
        
        var divCellInt = document.createElement("div");
        divCellInt.classList.add("tableCell");
        divCellInt.style.width = "20%";
        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="100%";
        inputInterface.style.minWidth="85px";
        inputInterface.value = currencies.records[i].interface;
        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 = currencies.records[i].status.id;
        /***CREAR SWITCH***/
        var divCellSwch = document.createElement("div");
        divCellSwch.classList.add("tableCell");
        divCellSwch.style.width ="50px";
        var cell,cont,swichBg,swichBal;
        cell = document.createElement("DIV"); cell.classList.add("switchCell");
            cont = document.createElement("DIV"); cont.classList.add("switchCont");
                swichBg = document.createElement("DIV"); swichBg.classList.add("switch");
                swichBg.setAttribute("id", "userStatus"+index);
                swichBal = document.createElement("DIV"); swichBal.classList.add("switchBal");
                if(currencies.records[i].status.id == 1){
                    swichBg.classList.add("active");
                    swichBal.classList.add("balActive");
                }
                swichBg.appendChild(swichBal);
                if( !(currencies.privileges.update == false || currencies.privileges.update == "false")){
                    swichBg.addEventListener("click", function(){
                        if(this.classList.contains("active")){
                            this.classList.remove("active");
                            this.firstElementChild.classList.remove("balActive");
                        }else{
                            this.classList.add("active");
                            this.firstElementChild.classList.add("balActive");
                        } 
                        UpdateCurrencies("liCurrencie"+index);
                    });
                }else{
                    swichBg.addEventListener("click", function(){
                        msg.innerHTML="No posee los privilegios para actualizar monedas.";
                        msg.classList.add("msgError");
                        msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("msgError");
                            msg.style.display="none";
                        }, 3000);
                    });
                    
                }
            cont.appendChild(swichBg);
        cell.appendChild(cont);
        divCellSwch.appendChild(cell);
        
        var divCellDcm = document.createElement("div");
        divCellDcm.classList.add("tableCell");
        divCellDcm.style.width = "15%";
        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.removeChild(inputDecim.options[0]);
        inputDecim.disabled = true;
        inputDecim.style.width="100%";
        inputDecim.style.minWidth="85px";
        inputDecim.value = currencies.records[i].decimals;
        divCellDcm.appendChild(inputDecim);
        
        var divCellIc = document.createElement("div");
        divCellIc.classList.add("tableCell");
        divCellIc.style.width = "15%";
        var inputPriv = document.createElement("div");
        inputPriv.classList.add("inputRow", "inputRol");
        inputPriv.classList.add("selectOrderBy");
        inputPriv.setAttribute("id", "inputPriv"+index);
        var span = document.createElement("span");
        span.innerHTML = "Icon";
        span.classList.add("spanIcon");
        span.addEventListener("click",function(){
            this.parentElement.dispatchEvent(new Event("click")); 
        });
        inputPriv.appendChild(span);
        inputPriv.setAttribute("style","pointer-events:none");
        inputPriv.style.cursor = "pointer";
        //inputPriv.style.backgroundPosition = "center";
        var privlistClone = document.getElementById("iconListAdd").cloneNode(true);
        privlistClone.getElementsByClassName("privArrow")[0].style.top = ((i+1)*18)+"px";
        privlistClone.style.top = -((i+1)*18)+"px";
        var icons = privlistClone.getElementsByClassName("icon");
        if(icons.length>0)icons[0].parentElement.parentElement.setAttribute("refbox","inputPriv"+index);
        for(var x=0;x<icons.length;x++){
            icons[x].addEventListener("click",function(){                //debugger;
                var icCol = document.getElementById(this.parentElement.parentElement.getAttribute("refbox")).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"));
                    
                }
            });
            if(icons[x].getAttribute("ref")==currencies.records[i].icon){
                var icCol = inputPriv.firstElementChild;
                icCol.innerHTML = "";
                icCol.setAttribute("style",icons[x].getAttribute("style"));
                icons[x].classList.add("iconSel");
            }
        }
        inputPriv.appendChild(privlistClone);
        inputPriv.addEventListener("click", function(ev){
            if(ev.target != this) return false;
            var lista = this.getElementsByClassName("privList")[0];
            if(lista.style.display !== "")
                hidePopPriv();
            else{
                showPopPriv(this);
                
            }
        });
        divCellIc.appendChild(inputPriv);
        
        divContent.classList.add("rowCurrencie");
        if(i%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liCurrencie"+index);
        divContent.dataset.id= currencies.records[i].id;
        divContent.appendChild(divCellSwch);
        divContent.appendChild(divCellNm);
        divContent.appendChild(divCellSm);
        divContent.appendChild(divCellInt);
        divContent.appendChild(divCellDcm);
        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 = currencies.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);
        }
    }
}