var pageLoad = false;
window.onload = function(){
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    loadPriv();
    
    document.getElementById("closeModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
         modal.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);
        
    });
    
    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 = "";
        LoadUsers('', selectOrderBy.value, 0, 10, sessionId);
        //table.appendChild(nodeClone);
    });
    
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        LoadUsers(this.value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        if(e.keyCode==13)LoadUsers(this.value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    
    document.getElementById("iconSearch").addEventListener("click",function(e){
        LoadUsers(document.getElementById("search").value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    
    //Add Currencie status formato de place holder
    document.getElementById("addUserRol").addEventListener("change",function(){
        if(this.value !== "")this.classList.remove("placehColor");
        else this.classList.add("placehColor");
    });
    
    //Botón de agregar ROLEs
    document.getElementById("iconAddRol").addEventListener("click", function(){
        var sessionId = sessionStorage.getItem("sessionId");
        var inputNameAdd = document.getElementById("addRolName");
                            
        req = {};
        req.id = 0;
        req.name = inputNameAdd.value;
        req.status = 1;
        req.sessionid = sessionId;
                    
        if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.status === "" || req.status === " "){
            var msg = document.getElementById("messageApiRol");
            msg.innerHTML= "Debe agregar datos v\u00E1lidos para crear un Rol";
            msg.classList.add("msgErrorTable");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorTable");
                msg.classList.remove("msgErrorTable");
                msg.style.display="none";
            }, 5000);
        } else {
            sendUpdateRol(req,"", -1);    
        }
    });
    
    //AGREGAR USUARIOS
    document.getElementById("iconAddUser").addEventListener("click", function(){
        var sessionId = sessionStorage.getItem("sessionId");
        var inputNameAdd = document.getElementById("addUsersName");
        var inputEmailAdd = document.getElementById("addUserEmail");
        var inputRolAdd = document.getElementById("addUserRol");
        var statusAdd = document.getElementById("swichUserAdd");
                            
        req = {};
        req.id = 0;
        req.name = inputNameAdd.value;
        req.email = inputEmailAdd.value;
        req.rolid = inputRolAdd.value;
        if(statusAdd.classList.contains("active")){
            req.status = 1;
        }else{
            req.status = 0;
        }
        
        req.sessionid = sessionId;
        var msg = document.getElementById("messageApi");
        if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.email === "" || req.email === " " || req.rolid === "" || req.rolid === " " || req.status === "" || req.status === " "){
            msg.innerHTML= "Debe agregar datos válidos para crear un Usuario";
            msg.classList.add("msgErrorTable");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorTable");
                msg.style.display="none";
            }, 5000);
        } else {
            //Validación adicional de email
            if(!checkEmail(inputEmailAdd)){
                msg.innerHTML="Introduzca un correo válido";
                msg.classList.add("msgErrorTable");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgErrorTable");
                    msg.style.display="none";
                }, 3000);
                return 0;
            }
            sendApiUpdate(req, -1);    
        }
    });
    
    //MOSTRAR PRIVILEGIOS AGREGAR
    document.getElementById("addRolPriv").addEventListener("click", function(ev){
        if(ev.target != this && ev.target != this.children[0] && ev.target != this.children[1] && ev.target != this.children[1].children[0]) return false;
        var lista = this.getElementsByClassName("privList")[0];
        if(lista.style.display !== "")
            hidePopPriv();
        else
            showPopPriv(document.getElementById("addRolPriv"));
            
    });
    
    //BOTONES CONFIRMAR EL ELIMINAR
    document.getElementById("buttonCancelModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
    document.getElementById("buttonAceptModal").addEventListener("click", function(){
        DeleteCurrencie(this.getAttribute("eleid"),this.getAttribute("srv"), this.dataset.liParent);
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
    //Swich de status del agregar usuario
    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");
        } 
    });
    
    
     /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
    
    document.getElementById("content").style.marginLeft = "229px";
}

function LoadUsers(filter, order, offset, numofrec, sessionid){
    var par = {};
    //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;
        if(order === "" || order === undefined)order = document.getElementById("orderBy").value;
        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", "users/list", par, respuesta);
        function respuesta(status, rsp){
            let users = JSON.parse(rsp);
            switch(status){
                case 200:
                    //NO APLICA EL SERVICIO SALE POR 304 SI NO TIENE PRIVILEGIO DE LECTURA
                    if(users.privileges.read == false || users.privileges.read == "false"){ 
                        /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noUserDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableUsers");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            document.getElementById("noUserDefine").style.display= "flex";
                            document.getElementById("msgInTableU").innerHTML="No Posee privilegios de lectura";
                            document.getElementById("paginator").style.display= "none"
                    } else {
                        if (users.numofrecords === 0){
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noUserDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableUsers");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            document.getElementById("noUserDefine").style.display= "flex";
                            document.getElementById("msgInTableU").innerHTML="No existen usuarios";
                            document.getElementById("paginator").style.display= "none";
                        } else {
                            if(users.numofrecords <= 10){
                                document.getElementById("paginator").style.display= "none";    
                            } else {
                                document.getElementById("paginator").style.display= ""; 
                                drawPags(users.numofrecords, "numbersPaginatorUser");
                            }
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noUserDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableUsers");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            //Pintar registros
                            paintRowsUsers(users);
                        }
                    }
                    if(offset==0){
                        //Se marca la primera página.
                        var pSel = document.getElementById("numbersPaginatorUser").getElementsByClassName("pSelect");
                        if(pSel.length>0)pSel[0].classList.remove("pSelect");
                        
                        var pageO=document.getElementById("numbersPaginatorUser").getElementsByClassName("pages");
                        if(pageO.length>0)pageO[0].classList.add("pSelect");
                    }
                    break;
                case 400:
                    msg.innerHTML=users.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        myLogout()
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=users.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000); 
                    break;
                case 403:
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noUserDefine");
                    if (nodeNoDelete ){
                        var nodeClone = nodeNoDelete.cloneNode(true);   
                        nodeClone.style.display="none";
                    }
                    var table = document.getElementById("bodyTableUsers");
                    table.innerHTML = "";
                    if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                    /**-hasta aqui-**/
                    document.getElementById("noUserDefine").style.display= "flex";
                    document.getElementById("msgInTableU").innerHTML="No Posee privilegios de lectura";
                    document.getElementById("paginator").style.display= "none"
                    
                    //Si se sale por privilegios de lectura no pinta muestro el contenido sin usuarios
                    if(!pageLoad){
                        //Mostrar pantalla al finalizar carga
                        pageLoad=true;
                        document.getElementsByClassName("centeredImage")[0].style.display = "";
                    }
                break;
                default:
                   
                   console.log("estatus 200", users); 
            }
        }
}
var rolesList = [];
function rolsList(sessionid){
      var par = {};
        par.order = 1;
        par.offset = 0;
        par.numofrec = 9999;
        par.sessionid = sessionid;
        callWS("GET", "roles/list", par, respuesta);
        function respuesta(status, rsp){
            let roles = JSON.parse(rsp)
            switch(status){
                case 200:
                    rolesList = roles.records;
                    var pageCnt = document.getElementById("numbersPaginatorUser");
                    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                    var offSetPageAdd = 0;
                    if(pageInPaginator){
                        pageInPaginator = pageInPaginator.innerHTML;
                        offSetDelete = (pageInPaginator*10) - 10;
                    }
                    var filter = document.getElementById("search").value;
                    var order = document.getElementById("orderBy").value;
                    LoadUsers(filter, order, offSetDelete, 10, sessionid);
                    /*drawRolList(roles.records);*/
                    drawSelect(document.getElementById("addUserRol"),"name", roles.records, "", "Rol");
                break;
                default:
                   console.log("estatus 200", roles); 
            }
        }
}
function LoadRols(filter, order, offset, numofrec, sessionid){
    var par = {};
        par.order = 1;
        par.offset = offset;
        par.numofrec = numofrec;
        par.sessionid = sessionid;
        callWS("GET", "roles/list", par, respuesta);
        function respuesta(status, rsp){
            let roles = JSON.parse(rsp)
            switch(status){
                case 200:
                    //Carga el listado completo y al finalizar se cargan los usuarios
                        rolsList(sessionid);
                    
                    if(roles.privileges.read == false || roles.privileges.read == "false"){
                        document.getElementById("noRolesDefine").style.display= "flex";
                        document.getElementById("msgInTable").innerHTML="No Posee privilegios de lectura";
                    } else {
                        if (roles.numofrecords === 0){
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noRolesDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableRoles");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            document.getElementById("noRolesDefine").style.display= "flex";
                            document.getElementById("msgInTable").innerHTML="No Posee Monedas definidas";
                            document.getElementById("paginatorRol").style.display= "none";
                        } else {
                            if(roles.numofrecords <= 10){
                                document.getElementById("paginatorRol").style.display= "none";    
                            } else {
                                document.getElementById("paginatorRol").style.display= ""; 
                                drawPags(roles.numofrecords, "numbersPaginatorRol");
                            }
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noRolesDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableRoles");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            //Pintar registros
                            paintRowsRols(roles);
                        }
                    }
                    if(offset==0){
                        //Se marca la primera página.
                        var pSel = document.getElementById("numbersPaginatorRol").getElementsByClassName("pSelect");
                        if(pSel.length>0)pSel[0].classList.remove("pSelect");
                        
                        var pageO=document.getElementById("numbersPaginatorRol").getElementsByClassName("pages");
                        if(pageO.length>0)pageO[0].classList.add("pSelect");
                    }
                    break;
                case 400:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        myLogout()
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                case 500:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 403:
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noRolesDefine");
                    if (nodeNoDelete ){
                        var nodeClone = nodeNoDelete.cloneNode(true);   
                        nodeClone.style.display="none";
                    }
                    var table = document.getElementById("bodyTableRoles");
                    table.innerHTML = "";
                    if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                    /**-hasta aqui-**/
                    document.getElementById("noRolesDefine").style.display= "flex";
                    document.getElementById("msgInTable").innerHTML="No Posee privilegios de lectura";
                    document.getElementById("paginatorRol").style.display= "none";
                    LoadUsers('', 0, 0, 10, sessionid);
                    document.getElementById("noRolesDefine").style.display= "flex";
                    document.getElementById("msgInTable").innerHTML="No Posee privilegios de lectura";
                break;
                default:
                   console.log("estatus 200", roles); 
            }
        }
}

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 = numbersPaginator.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;
            
            if(this.parentElement.getAttribute("id") === "numbersPaginatorRol"){
                LoadRols("", 1, offset, 10, sessionStorage.getItem("sessionId"));
            }else{
                LoadUsers(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")!="true"){
        var leftArrow = numbersPaginator.previousElementSibling;
        var rightArrow = numbersPaginator.nextElementSibling;
        //Evento flecha izquierda
        leftArrow.addEventListener("click",function(){
            var pSel = this.nextElementSibling.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].previousElementSibling !== null){
                    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;
                        if(this.nextElementSibling.getAttribute("id") === "numbersPaginatorRol"){
                            LoadRols(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
                        }else{
                            LoadUsers(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
                        }
                    }
                }
            }
        });
        
        //Evento flecha derecha
        rightArrow.addEventListener("click",function(){
            var pSel = this.previousElementSibling.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].nextElementSibling !== null){
                    if(pSel[0].nextElementSibling.classList.contains("pages")){
                        var last = pSel[0];
                        pSel[0].nextElementSibling.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;
                        if(this.previousElementSibling.getAttribute("id") === "numbersPaginatorRol"){
                            LoadRols(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
                        }else{
                            LoadUsers(filter, order, offset, 10, sessionStorage.getItem("sessionId"));
                        }
                    }
                }
            }
        });
        
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
}

function EditUsers(id){
    let i = id.substr(id.length - 1);
    var parent = document.getElementById(id);
    var inputNameEdit = document.getElementById("inputName"+i);
    var inputEmailEdit = document.getElementById("inputEmail"+i);
    var inputRolEdit = document.getElementById("inputRol"+i);
    var iconDeleteClear = document.getElementById("iconDeleteU"+i);
    var pAvailable = document.getElementById("pU"+i);
    var pDisabled = document.getElementById("pEditU"+i);
    inputNameEdit.disabled = false;
    inputEmailEdit.disabled = false;
    inputRolEdit.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 EditRol(id){
    let i = id.substr(id.length - 1);
    var parent = document.getElementById(id);
    var inputNameEdit = document.getElementById("inputNameRol"+i);
    var inputPrivEdit = document.getElementById("inputPriv"+i);
    var iconDeleteClear = document.getElementById("iconDeleteR"+i);
    var pAvailable = document.getElementById("p"+i);
    var pDisabled = document.getElementById("pEdit"+i);
    inputNameEdit.disabled = false;
    var switchs = inputPrivEdit.getElementsByClassName("switch");
    for(let j=0; j<switchs.length; j++){
        switchs[j].style.pointerEvents = "";
        switchs[j].style.cursor="pointer"
    }
    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,srv, liId){
    if(liId != -1){
        var idxLi = liId.substr(liId.length -1 );    
    }
    var sessionId = sessionStorage.getItem("sessionId");
    req = {};
    req.id = id; 
    req.sessionid = sessionId;
    callWS("GET", srv+"/delete", req, respuesta);
        function respuesta(status, rsp){
            if(rsp){
                let respuesta = JSON.parse(rsp);
                var rspmsg = JSON.parse(rsp);
            }
            
            if(srv === "roles") {
                var msg = document.getElementById("msgErrorliRol" + idxLi);
                var msgTable = document.getElementById("messageApiRol");
            } else{
              var msg = document.getElementById("msgErrorliUser" + idxLi);  
              var msgTable = document.getElementById("messageApi");
            } 
            var rowError = document.getElementById(liId);
            var rowErrorColor = 'white';
            if(rowError.classList.contains('rowImpar')){
                rowErrorColor = "rgba(245, 246, 248, 1)"
            }
            console.log(status);
            switch(status){
                case 200:
                    if(srv == 'users'){
                        msgTable.innerHTML = "Usuario eliminado correctamente";
                        msgTable.classList.add("msgSucessTable");
                        msgTable.style.display="block";
                        setTimeout(function() {
                            msgTable.classList.remove("msgSucessTable");
                            msgTable.style.display="none";
                        }, 3000);
                        var nodeNoDelete = document.getElementById("noUserDefine");
                        if (nodeNoDelete ){
                            var nodeClone = nodeNoDelete.cloneNode(true);    
                        }
                        var table = document.getElementById("bodyTableUsers");
                        table.innerHTML = "";
                        /*
                        document.getElementById("addCurrencieName").value ="";
                        document.getElementById("addCurrencieSymbol").value ="";
                        document.getElementById("addCurrencieStatus").value ="";
                        document.getElementById("addCurrencieStatus").dispatchEvent(new Event("change"));*/
                        var pageCnt = document.getElementById("numbersPaginatorUser");
                        var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                        var offSetPageAdd = 0;
                        if(pageInPaginator){
                            pageInPaginator = pageInPaginator.innerHTML;
                            offSetDelete = (pageInPaginator*10) - 10;
                        }
                        var filter = document.getElementById("search").value;
                        var order = document.getElementById("orderBy").value;
                        LoadUsers(filter, order, offSetDelete, 10, req.sessionid);
                        table.appendChild(nodeClone);
                    }else if(srv == 'roles'){
                        msgTable.innerHTML = "Rol eliminado correctamente";
                        msgTable.classList.add("msgSucessTable");
                        msgTable.style.display="block";
                        setTimeout(function() {
                            msgTable.classList.remove("msgSucessTable");
                            msgTable.style.display="none";
                        }, 3000);
                        var nodeNoDelete = document.getElementById("noRolesDefine");
                        if (nodeNoDelete ){
                            var nodeClone = nodeNoDelete.cloneNode(true);    
                        }
                        var table = document.getElementById("bodyTableRoles");
                        table.innerHTML = "";
                        var pageCnt = document.getElementById("numbersPaginatorRol");
                        var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                        var offSetPageAdd = 0;
                        if(pageInPaginator){
                            pageInPaginator = pageInPaginator.innerHTML;
                            offSetDelete = (pageInPaginator*10) - 10;
                        }
                        LoadRols("", 1, offSetDelete, 10, req.sessionid);
                        table.appendChild(nodeClone);
                    }
                    break;
                    
                case 304:
                    rowError.style.backgroundColor= "#FAE5E8";
                    if(srv=="roles") {
                        msg.innerHTML="Existen dependencias que no permiten eliminar este Rol";
                        msg.classList.add("msgError");
                        msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("msgError");
                            rowError.style.backgroundColor= rowErrorColor;
                            msg.style.display="none";
                        }, 3000); 
                    } else { 
                        msg.innerHTML="Existen dependencias que no permiten eliminar este Usuario";
                        msg.classList.add("msgError");
                        msg.style.display="block";
                        setTimeout(function() {
                            rowError.style.backgroundColor= rowErrorColor;
                            msg.classList.remove("msgError");
                            msg.style.display="none";
                        }, 3000);
                    }
                break;
                case 400:
                    rowError.style.backgroundColor= "#FAE5E8";
                    msg.innerHTML=rspmsg.msg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        rowError.style.backgroundColor= rowErrorColor;
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 401:
                    rowError.style.backgroundColor= "#FAE5E8";
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.style.display="block";
                    msg.classList.add("msgError");
                    setTimeout(function() {
                        rowError.style.backgroundColor= rowErrorColor;
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    rowError.style.backgroundColor= "#FAE5E8";
                    msg.innerHTML="No posee los privilegios para actualizar Monedas."
                    msg.style.display="block";
                    msg.classList.add("msgError");
                    setTimeout(function() {
                        rowError.style.backgroundColor= rowErrorColor;
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    rowError.style.backgroundColor= "#FAE5E8";
                    msg.innerHTML="Error interno, intente nuevamente";
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        rowError.style.backgroundColor= rowErrorColor;
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    rowError.style.backgroundColor= "#FAE5E8";
                    msg.innerHTML= respuesta.msg;
                    msg.style.display="block";
                    setTimeout(function() {
                        rowError.style.backgroundColor= rowErrorColor.split(" ")[0];
                        msg.style.display="none";
                    }, 3000);
            }
        }
}

function UpdateRol(id){
    var sessionId = sessionStorage.getItem("sessionId");
    let i = id.substr(id.length - 1);
    var parent = document.getElementById(id)
    var inputName = document.getElementById("inputNameRol"+i);
    var tblcnt = document.getElementById("inputPriv"+i);
        
    req = {};
    req.id = parent.getAttribute("data-id");
    req.name = inputName.value;
    req.status = 1;
    req.sessionid = sessionId;
                
    if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.status === "" || req.status === " "){
    var msg = document.getElementById("messageApiRol");
        msg.innerHTML= "Debe agregar datos válidos para crear un Rol";
        msg.classList.add("msgErrorTable");
        msg.style.display="block";
        setTimeout(function() {
            msg.classList.remove("msgErrorTable");
            msg.style.display="none";
        }, 5000);
    } else {
        sendUpdateRol(req,tblcnt, id);    
    }
}

function UpdateUsers(id){
    var sessionId = sessionStorage.getItem("sessionId");
    let i = id.substr(id.length - 1);
    var parent = document.getElementById(id);
    var inputNameEdit = document.getElementById("inputName"+i);
    var inputEmailEdit = document.getElementById("inputEmail"+i);
    var inputRolEdit = document.getElementById("inputRol"+i);
    var status = document.getElementById("userStatus"+i);
    
    req = {};
    req.id = parent.getAttribute('data-id');
    req.name = inputNameEdit.value;
    req.email = inputEmailEdit.value;
    req.rolid = inputRolEdit.value;
    if(status.classList.contains("active"))
        req.status = 1;
    else
        req.status = 0;
    req.sessionid = sessionId;
    var msg = document.getElementById("messageApi");
    if(req.id === "" || req.id === " " || req.name === "" || req.name === " " || req.email === "" || req.email === " " || req.rol === "" || req.rol === " "){
        msg.innerHTML= "Debe agregar datos válidos para actualizar un Usuario";
        msg.classList.add("msgErrorTable");
        msg.style.display="block";
        setTimeout(function() {
            msg.classList.remove("msgErrorTable");
            msg.style.display="none";
        }, 5000);
    } else {
        
        //Validación adicional de email
        if(!checkEmail(inputEmailEdit)){
            msg.innerHTML="Introduzca un correo válido";
            msg.classList.add("msgErrorTable");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorTable");
                msg.style.display="none";
            }, 3000);
            return 0;
        }
        
        sendApiUpdate(req, id);    
    }
    
    
}

function CancelEditUsers(id){
    let i = id.substr(id.length - 1);
    document.getElementById("liUser"+i).style.backgroundColor = "";
    var inputNameEdit = document.getElementById("inputName"+i);
    var inputEmailEdit = document.getElementById("inputEmail"+i);
    var inputRolEdit = document.getElementById("inputRol"+i);
    var iconDeleteClear = document.getElementById("iconDeleteU"+i);
    var pAvailable = document.getElementById("pU"+i);
    var pDisabled = document.getElementById("pEditU"+i);
    inputNameEdit.disabled = true;
    inputEmailEdit.disabled = true;
    inputRolEdit.disabled = true;
    pAvailable.style.visibility ="visible";
    pAvailable.style.position ="relative";
    pDisabled.style.visibility ="hidden";
    pDisabled.style.position ="absolute";
}
function CancelEditRol(id){
    let i = id.substr(id.length - 1);
    hidePopPriv();
    document.getElementById("liRol"+i).style.backgroundColor = "";
    var inputNameEdit = document.getElementById("inputNameRol"+i);
    var inputPrivEdit = document.getElementById("inputPriv"+i);
    var iconDeleteClear = document.getElementById("iconDeleteR"+i);
    var pAvailable = document.getElementById("p"+i);
    var pDisabled = document.getElementById("pEdit"+i);
    inputNameEdit.disabled = true;
    var switchs = inputPrivEdit.getElementsByClassName("switch");
    for(let j=0; j<switchs.length; j++){
        switchs[j].style.pointerEvents = "none";
        switchs[j].style.cursor="none"
    }
    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.substr(id.length - 1);
    
    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 = "Usuario: "+ inputNameEdit;
    curr.style.fontWeight= "normal"
    dataDelete.appendChild(curr);
    modal.style.display = "block";
    
    document.getElementById("buttonAceptModal").setAttribute("eleid",idCurrencie);
    document.getElementById("buttonAceptModal").dataset.liParent = id;
    document.getElementById("buttonAceptModal").setAttribute("srv","users");
}
function ConfirmDeleteRol(id) {
    var parent = document.getElementById(id);
    var idCurrencie = parent.getAttribute('data-id');
    let i = id.substr(id.length - 1);
    var inputNameEdit = document.getElementById("inputNameRol"+i).value;
    var modal = document.getElementById("myModal");
    var dataDelete = document.getElementById("dataDelete");
    dataDelete.innerHTML = "";
    var curr = document.createElement("li");
    curr.innerHTML = "Rol: "+ inputNameEdit;
    curr.style.fontWeight= "normal"
    dataDelete.appendChild(curr);
    modal.style.display = "block";
    
    document.getElementById("buttonAceptModal").setAttribute("eleid",idCurrencie);
    document.getElementById("buttonAceptModal").dataset.liParent = id;
    document.getElementById("buttonAceptModal").setAttribute("srv","roles");
}
function sendUpdateRol(req,tblcnt, liId){
    callWS("GET", "roles/update", req, respuesta);
        function respuesta(status, rsp){
            if(rsp!=="")var respuesta = JSON.parse(rsp);
            if(liId == -1){
                var msg = document.getElementById("messageApiRol")    
            } else {
                var idx = liId.substr(liId.length - 1);
                var msg = document.getElementById("msgErrorliRol"+idx);
                var liFail = document.getElementById(liId);
                var liErrorColor = 'white';
                if (liFail.classList.contains("rowImpar") ){
                    liErrorColor  = "rgba(245, 246, 248, 1)";
                }
            }
            
            switch(status){
                case 200:
                    var privids="";
                    var list = "";
                    if(req.id === 0){
                        msg.innerHTML = "Rol creado correctamente";
                        list = document.getElementById("tblAddPriv").getElementsByClassName("switch");
                    }else{
                        msg.innerHTML = "Rol actualizado correctamente";
                        list = tblcnt.getElementsByClassName("switch");
                    }
                    for(var i=0;i<list.length;i++){
                        if(list[i].classList.contains("active"))
                            privids += list[i].getAttribute("privid")+"-";
                            
                    }
                    msg.classList.add("msgSucessTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgSucessTable");
                        msg.style.display="none";
                    }, 3000);
                    privids = privids.substr(0,privids.length - 1);
                    var prms = {};
                    prms.rolid = respuesta.id;
                    prms.privileges = privids;
                    prms.sessionid = req.sessionid;
                    
                    updatePrivileges(prms);
                break;
                case 304: //Registro sin modificar validamos igual los privilegios
                    msg.innerHTML = "No se realizaron cambios al Rol";
                    msg.style.display="block";
                    msg.classList.add("msgSucessTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgSucessTable");
                        msg.style.display="none";
                    }, 3000);
                    var list = tblcnt.getElementsByClassName("switch");
                    var privids = "";
                    for(var i=0;i<list.length;i++){
                        if(list[i].classList.contains("active"))
                            privids += list[i].getAttribute("privid")+"-";
                            
                    }
                    privids = privids.substr(0,privids.length - 1);
                    
                    var prms = {};
                    prms.rolid = req.id;
                    prms.privileges = privids;
                    prms.sessionid = req.sessionid;
                    updatePrivileges(prms);
                break;
                case 400:
                    msg.innerHTML=respuesta.msg
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    msg.innerHTML="No posee los privilegios para actualizar Roles."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    msg.innerHTML="Ya existe el Rol, intente nuevamente."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                default:
                    msg.innerHTML= respuesta.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
            }
        }
    
}

function sendApiUpdate(req, liId){
    console.log("request", req);
    callWS("GET", "users/update", req, respuesta);
        function respuesta(status, rsp){
            console.log("status", status)
            if(rsp!=="")var respuesta = JSON.parse(rsp);
            if(liId == -1){
                var msg = document.getElementById("messageApi")    
            } else {
                var idx = liId.substr(liId.length - 1);
                var msg = document.getElementById("msgErrorliUser"+idx);
                var liFail = document.getElementById(liId);
                var liErrorColor = 'white';
                if (liFail.classList.contains("rowImpar") ){
                    liErrorColor  = "rgba(245, 246, 248, 1)";
                }
            }
            
            switch(status){
                case 200:
                    if(req.id === 0){
                        document.getElementById("addUsersName").value ="";
                        document.getElementById("addUserEmail").value ="";
                        document.getElementById("addUserRol").value ="";
                        document.getElementById("addUserRol").dispatchEvent(new Event("change"));
                    }
                    var nodeNoDelete = document.getElementById("noUserDefine");
                    if(nodeNoDelete){
                        var nodeClone = nodeNoDelete.cloneNode(true);
                    }
                    console.log(nodeNoDelete);
                    console.log(nodeClone);
                    var table = document.getElementById("bodyTableUsers");
                    table.innerHTML = "";
                    var pageCnt = document.getElementById("numbersPaginatorUser");
                    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                    var offSetDelete = 0;
                    if(pageInPaginator){
                        pageInPaginator = pageInPaginator.innerHTML;
                        offSetDelete = (pageInPaginator*10) - 10;
                    }
                    var filter = document.getElementById("search").value;
                    var order = document.getElementById("orderBy").value;
                    LoadUsers(filter, order, offSetDelete, 10, req.sessionid);
                    if(req.id == 0){
                        msg.innerHTML = "Usuario creado correctamente";
                    } else{
                        msg.innerHTML = "Usuario actualizado correctamente";
                    }
                    msg.classList.add("msgSucessTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgSucessTable");
                        msg.style.display="none";
                    }, 3000);
                    console.log(table);
                    //table.appendChild(nodeClone);
                    break;
                case 304: //Registro sin modificar validamos igual los privilegios
                    msg.style.display="block";
                    if (liFail){
                        console.log("liFail", liFail);
                        console.log("msg ", msg);
                        liFail.style.backgroundColor = "#FAE5E8"    
                    }
                    setTimeout(function() {
                        if(liFail){
                            liFail.style.backgroundColor= liErrorColor;    
                        }
                        msg.style.display="none";
                    }, 3000);
                    var nodeNoDelete = document.getElementById("noUserDefine");
                    if(nodeNoDelete){
                        var nodeClone = nodeNoDelete.cloneNode(true);
                    }
                    var table = document.getElementById("bodyTableUsers");
                    table.innerHTML = "";
                    var pageCnt = document.getElementById("numbersPaginatorUser");
                    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                    var offSetPageAdd = 0;
                    if(pageInPaginator){
                        pageInPaginator = pageInPaginator.innerHTML;
                        offSetDelete = (pageInPaginator*10) - 10;
                    }
                    var filter = document.getElementById("search").value;
                    var order = document.getElementById("orderBy").value;
                    LoadUsers(filter, order, offSetDelete, 10, req.sessionid);
                    //table.appendChild(nodeClone);
                break;   
                case 400:
                    msg.innerHTML=respuesta.msg
                    if (liId == -1){
                        msg.classList.add("msgErrorTable");
                        setTimeout(function() {
                            msg.classList.add("msgErrorTable");
                            msg.style.display="none";
                        }, 3000);
                    } else {
                        msg.style.display="block";
                        liFail.style.backgroundColor = "#FAE5E8"
                        setTimeout(function() {
                            liFail.style.backgroundColor= liErrorColor;
                            msg.style.display="none";
                        }, 3000);
                    }
                    break;
                    
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    msg.innerHTML="No posee los privilegios para actualizar Usuarios."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    msg.innerHTML="Ya existe el Usuario, intente nuevamente."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    msg.innerHTML= respuesta.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
            }
        }
    
}
function updatePrivileges(req){
    console.log("reques create ", req)
    callWS("GET", "privileges/saverolprivileges", req, respuesta);
        function respuesta(status, rsp){
            let respuesta = JSON.parse(rsp);
            var msg = document.getElementById("messageApiRol")
            switch(status){
                case 200:
                    document.getElementById("addRolName").value ="";
                    activeAllSw(document.getElementById("addRolPriv"));
                    hidePopPriv();
                    
                    var nodeNoDelete = document.getElementById("noRolesDefine");
                    if(nodeNoDelete){
                        var nodeClone = nodeNoDelete.cloneNode(true);
                    }
                    var table = document.getElementById("bodyTableRoles");
                    table.innerHTML = "";
                    var pageCnt = document.getElementById("numbersPaginatorRol");
                    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
                    var offSetPageAdd = 0;
                    if(pageInPaginator){
                        pageInPaginator = pageInPaginator.innerHTML;
                        offSetDelete = (pageInPaginator*10) - 10;
                    }
                    LoadRols('', 1, offSetDelete, 10, req.sessionid);
                    table.appendChild(nodeClone);
                    break;
                    
                case 400:
                    msg.innerHTML=respuesta.msg
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    msg.innerHTML="No posee los privilegios para actualizar Roles."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML="Ya existe el Rol, intente nuevamente."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    msg.innerHTML= respuesta.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
            }
        }
    
}

function paintRowsUsers(users){
    
    var msg = document.getElementById("messageApi");// para errores
    var pageCnt = document.getElementById("numbersPaginatorUser");
    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableUsers");
    var filas;
    if (users.numofrecords > 10){
        filas = parseInt(users.numofrecords) - ((parseInt(pageInPaginator) - 1) * 10);
        if(filas > 10){
            filas = 10;
        }
    } else {
        filas = users.numofrecords
    }


    /*var rowCurrencie = document.getElementById("bodyTableUsers");
    var filas;
    if(users.numofrecords > 10){
        filas = users.records.length;
    } else{
        filas = users.numofrecords;
    }*/
    for (i=0; i<filas; i++){
        var divContent= document.createElement("div");
        var inputName= document.createElement("input");
        var inputSymbol= document.createElement("input");
        var inputStatus= 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;
        
        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-edit");
        iconEdit.setAttribute("id", "iconEditU"+index);
        if( !(users.privileges.update == false || users.privileges.update == "false")){
            iconEdit.addEventListener("click", function(){
                EditUsers("liUser"+index);
            });
        }else{
            iconEdit.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para actualizar usuarios.";
                msg.classList.add("msgErrorTable");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgErrorTable");
                    msg.style.display="none";
                }, 3000);
            });
        }
        
        
        iconDelete.classList.add("fas");
        iconDelete.classList.add("fa-trash-alt");
        iconDelete.setAttribute("id", "iconDeleteU"+index);
        if( !(users.privileges.delete == false || users.privileges.delete == "false")){
            iconDelete.addEventListener("click", function(){
                ConfirmDeleteCurrencie("liUser"+index)
            });
        }else{
            iconDelete.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para eliminar usuarios.";
                msg.classList.add("msgErrorTable");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgErrorTable");
                    msg.style.display="none";
                }, 3000);
            });
        }
        
        var divCell = document.createElement("div");
        divCell.classList.add("tableCell");
        divCell.style.width = "60px";
        p.setAttribute("id", "pU"+index);
        p.appendChild(iconEdit);
        p.appendChild(iconDelete);
        p.classList.add("icAddCnt");
        p.style.visibility="";
        p.style.position="relative";
        
        iconDone.classList.add("fas");
        iconDone.classList.add("fa-check-circle");
        iconDone.style.color ="#4287CE";
        iconDone.setAttribute("id", "iconDoneU"+index);
        iconDone.addEventListener("click", function(){
            UpdateUsers("liUser"+index);
        });
        
        iconCancel.classList.add("far");
        iconCancel.classList.add("fa-times-circle");
        iconCancel.style.color ="#4287CE";
        iconCancel.setAttribute("id", "iconCancelU"+index);
        iconCancel.addEventListener("click", function(){
            CancelEditUsers("liUser"+index);
        });
        
        p2.setAttribute("id", "pEditU"+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);
        
        var divCellNm = document.createElement("div");
        divCellNm.classList.add("tableCell");
        divCellNm.style.width = "28%";
        inputName.disabled=true;
        inputName.classList.add("inputRow");
        inputName.setAttribute("id", "inputName"+index);
        inputName.value = users.records[i].name;
        divCellNm.appendChild(inputName);
        
        var divCellEmail = document.createElement("div");
        divCellEmail.classList.add("tableCell");
        divCellEmail.style.width = "auto";
        inputSymbol.disabled=true;
        inputSymbol.classList.add("inputRow", "inputEmail");
        inputSymbol.setAttribute("id", "inputEmail"+index)
        inputSymbol.value = users.records[i].email;
        divCellEmail.appendChild(inputSymbol);
        
        var divCellRol = document.createElement("div");
        divCellRol.classList.add("tableCell");
        divCellRol.style.width = "20%";
        inputStatus.disabled=true;
        inputStatus.classList.add("inputRow", "inputRol");
        inputStatus.classList.add("selectOrderBy");
        inputStatus.setAttribute("id", "inputRol"+index);
        var rolid="";
        if(users.records[i].rol!==null)rolid =users.records[i].rol.id;
        drawSelect(inputStatus,"name", rolesList, rolid, "");
        divCellRol.appendChild(inputStatus);
        
        divContent.classList.add("rowCurrencie");
        if(i%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liUser"+index);
        divContent.dataset.id= users.records[i].id;
        
        /***CREAR SWITCH***/
        var divCellSw = document.createElement("div");
        divCellSw.classList.add("tableCell");
        divCellSw.style.width = "38px";
        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(users.records[i].status.id == 1){
                    swichBg.classList.add("active");
                    swichBal.classList.add("balActive");
                }
                swichBg.appendChild(swichBal);
                if(users.privileges.update){
                    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");
                        } 
                        UpdateUsers("liUser"+index);
                    });
                }else{
                    swichBg.addEventListener("click", function(){
                        msg.innerHTML="No posee los privilegios para actualizar usuarios.";
                        msg.classList.add("msgErrorTable");
                        msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("msgErrorTable");
                            msg.style.display="none";
                        }, 3000);
                    });
                }
                
            cont.appendChild(swichBg);
        cell.appendChild(cont);
        divCellSw.appendChild(cell);
        
        divContent.appendChild(divCellSw);
        divContent.appendChild(divCellNm);
        divContent.appendChild(divCellEmail);
        divContent.appendChild(divCellRol);
        divContent.appendChild(divCell);
        
        rowCurrencie.appendChild(divContent);
        var msgRow = document.createElement("p");
        msgRow.setAttribute("id","msgErrorliUser"+index);
        msgRow.classList.add("msgError");
        rowCurrencie.appendChild(msgRow);
    }
    
    for(let j = users.records.length; j<10; j++){
        var divContent= document.createElement("div");
        var inputName= document.createElement("input");
        var inputSymbol= document.createElement("input");
        var inputStatus= document.createElement("input");
        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 = j;
        
        
        var divCell = document.createElement("div");
        divCell.classList.add("tableCell");
        divCell.style.width = "60px";
        divCell.appendChild(p);
        
        var divCellNm = document.createElement("div");
        divCellNm.classList.add("tableCell");
        divCellNm.style.width = "28%";
        inputName.disabled=true;
        inputName.classList.add("inputRow");
        inputName.setAttribute("id", "inputName"+index);
        inputName.value = "";
        divCellNm.appendChild(inputName);
        
        var divCellEmail = document.createElement("div");
        divCellEmail.classList.add("tableCell");
        divCellEmail.style.width = "auto";
        inputSymbol.disabled=true;
        inputSymbol.classList.add("inputRow", "inputEmail");
        inputSymbol.setAttribute("id", "inputEmail"+index)
        inputSymbol.value = "";
        divCellEmail.appendChild(inputSymbol);
        
        var divCellRol = document.createElement("div");
        divCellRol.classList.add("tableCell");
        divCellRol.style.width = "20%";
        inputStatus.disabled=true;
        inputStatus.classList.add("inputRow", "inputRol");
        inputStatus.classList.add("selectOrderBy");
        inputStatus.setAttribute("id", "inputRol"+index);
        inputStatus.innerHTML = "";
        divCellRol.appendChild(inputStatus);
        
        divContent.classList.add("rowCurrencie");
        if(j%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liUser"+index);

        /***CREAR SWITCH***/
        var divCellSw = document.createElement("div");
        divCellSw.classList.add("tableCell");
        divCellSw.style.width = "38px";
        var cell,cont,swichBg,swichBal;
        cell = document.createElement("DIV"); cell.classList.add("switchCell");
        cell.innerHTML = "";
        divCellSw.appendChild(cell);
        
        divContent.appendChild(divCellSw);
        divContent.appendChild(divCellNm);
        divContent.appendChild(divCellEmail);
        divContent.appendChild(divCellRol);
        divContent.appendChild(divCell);
        
        rowCurrencie.appendChild(divContent);
    }
    if(!pageLoad){
        //Mostrar pantalla al finalizar carga
        pageLoad=true;
        document.getElementsByClassName("centeredImage")[0].style.display = "";
    }
}
function paintRowsRols(roles){
    var msg = document.getElementById("messageApiRol");
    var pageCnt = document.getElementById("numbersPaginatorRol");
    var pageInPaginator = pageCnt.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableRoles");
    var filas;
    if (roles.numofrecords > 10){
        filas = parseInt(roles.numofrecords) - ((parseInt(pageInPaginator) - 1) * 10);
        if(filas > 10){
            filas = 10;
        }
    } else {
        filas = roles.numofrecords
    }
    
    /*var rowCurrencie = document.getElementById("bodyTableRoles");
    var filas;
    if(roles.numofrecords > 10){
        filas = roles.records.length;
    } else {
        filas = roles.numofrecords;
    }*/
    for (i=0; i<filas; i++){
        var divContent= document.createElement("div");
        var inputName= document.createElement("input");
        var inputPriv= document.createElement("div");
        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;
        
        var divCell = document.createElement("div");
        divCell.classList.add("tableCell");
        divCell.style.width = "60px";
        
        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-edit");
        iconEdit.setAttribute("id", "iconEditR"+index);
        var id= roles.records[i].id;
        if( !(roles.privileges.update == false || roles.privileges.update == "false")){
            iconEdit.addEventListener("click", function(){
                EditRol("liRol"+index)
            });
        }else{
            iconEdit.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para actualizar roles.";
                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", "iconDeleteR"+index);
        if( !(roles.privileges.delete == false || roles.privileges.delete == "false")){
            iconDelete.addEventListener("click", function(){
                ConfirmDeleteRol("liRol"+index)
            });
        }else{
            iconDelete.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para eliminar roles.";
                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="";
        p.style.position="relative";
        
        iconDone.classList.add("fas");
        iconDone.classList.add("fa-check-circle");
        iconDone.style.color ="#4287CE";
        iconDone.setAttribute("id", "iconDoneR"+index);
        iconDone.addEventListener("click", function(){
            UpdateRol("liRol"+index);
        });
        
        iconCancel.classList.add("far");
        iconCancel.classList.add("fa-times-circle");
        iconCancel.style.color ="#4287CE";
        iconCancel.setAttribute("id", "iconCancelR"+index);
        iconCancel.addEventListener("click", function(){
            CancelEditRol("liRol"+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);
        
        var divCellNm = document.createElement("div");
        divCellNm.classList.add("tableCell");
        divCellNm.style.width = "auto";
        inputName.disabled=true;
        inputName.classList.add("inputRow");
        inputName.setAttribute("id", "inputNameRol"+index);
        inputName.value = roles.records[i].name;
        divCellNm.appendChild(inputName);
        //inputPriv.style.pointerEvents = "none";
        var divCellPriv = document.createElement("div");
        divCellPriv.classList.add("tableCell");
        divCellPriv.style.width = "30%";
        inputPriv.classList.add("inputRow", "inputRol");
        inputPriv.classList.add("selectOrderBy");
        inputPriv.setAttribute("id", "inputPriv"+index);
        var icRow = document.createElement("div");
        icRow.classList.add("iconContainerArrow");
        icRow.style.bottom = "0";
        icRow.innerHTML = '<i class="fas fa-caret-down"></i>';
        var lbl = document.createElement("span");
        lbl.innerHTML = "Privilegios";
        inputPriv.appendChild(lbl);
        inputPriv.appendChild(icRow);
        //inputPriv.innerHTML = "Privilegios";
        var privlistClone = document.getElementById("privListAdd").cloneNode(true);
        privlistClone.getElementsByClassName("privArrow")[0].style.top = ((i+1)*30)-11+"px";
        privlistClone.style.top = -(((i+1)*30)-8)+"px";
        
        var switchs = privlistClone.getElementsByClassName("switch");
        for(var x=0;x<switchs.length;x++){
            switchs[x].style.pointerEvents = "none";
            switchs[x].style.cursor="none";
            switchs[x].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");
                } 
                //updtStatus(this);
            });
        }
        inputPriv.appendChild(privlistClone);
        inputPriv.setAttribute("rolid",roles.records[i].id);
        inputPriv.addEventListener("click", function(ev){
            //if(ev.target != this && ev.target != this.children[0] && ev.target != this.children[1] && ev.target != this.children[1].children[0]) return false;
            if(ev.target == this)
                var lista = this.getElementsByClassName("privList")[0];
            else if(ev.target == this.children[1] || ev.target == this.children[0])
                var lista = this.parentElement.getElementsByClassName("privList")[0];
            else if(ev.target == this.children[1].children[0])
                var lista = this.parentElement.parentElement.getElementsByClassName("privList")[0];
            else 
                return false;
                
            if(lista.style.display !== "")
                hidePopPriv();
            else{
                loadRolPriv(this.getAttribute("rolid"),this);
            }
        });
        divCellPriv.appendChild(inputPriv);
        divContent.classList.add("rowCurrencie");
        if(i%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liRol"+index);
        divContent.dataset.id= roles.records[i].id;
        
        divContent.appendChild(divCellNm);
        divContent.appendChild(divCellPriv);
        divContent.appendChild(divCell);
        
        rowCurrencie.appendChild(divContent);
        var msgRow = document.createElement("p");
        msgRow.setAttribute("id","msgErrorliRol"+index);
        msgRow.classList.add("msgError");
        rowCurrencie.appendChild(msgRow);
    }
    
    for(let j = roles.records.length; j<10; j++){
        var divContent= document.createElement("div");
        var inputName= document.createElement("input");
        var inputPriv= document.createElement("div");
        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 = j;
        
        inputName.disabled=true;
        inputName.classList.add("inputRow");
        inputName.value = "";
        
        inputPriv.disabled=true;
        inputPriv.classList.add("inputRow");
        inputPriv.classList.add("selectOrderBy");
        
        divContent.classList.add("rowCurrencie");
        if(j%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liRol"+index);
        divContent.appendChild(inputName);
        divContent.appendChild(inputPriv);
        divContent.appendChild(p);
        divContent.appendChild(p2);
        //divContent.style.display = "flex";
        
        rowCurrencie.appendChild(divContent);
        //divContent.style.display = "flex";
        divContent.style.cursor = "normal";
        
        rowCurrencie.appendChild(divContent);
    }
}

function loadPriv(){
    var par = {};
        par.order = 1;
        par.offset = 0;
        par.numofrec = 999;
        par.sessionid = sessionStorage.getItem("sessionId");
        callWS("GET", "privileges/list", par, respuesta);
        function respuesta(status, rsp){
            let resp = JSON.parse(rsp);
            switch(status){
                case 200:
                    drawPrivList(resp.records);
                    LoadRols('', 1, 0, 10, sessionStorage.getItem("sessionId"));
                break;
                case 400:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        myLogout()
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                   console.log("estatus 200", resp); 
            }
        }
}
function activeAllSw(tbl){
    var switchs = tbl.getElementsByClassName("switch");
    for(var i=0;i<switchs.length;i++){
        switchs[i].classList.add("active");
        switchs[i].firstElementChild.classList.add("balActive");
    }
}
function disabledAll(tbl){
    var switchs = tbl.getElementsByClassName("switch");
    for(var i=0;i<switchs.length;i++){
        switchs[i].classList.remove("active");
        switchs[i].firstElementChild.classList.remove("balActive");
    }
}
function drawPrivList(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 col1, col2, col3;
            
            //Var Columna 2 Fecha
            var col1, name;
            col1 = ele.firstElementChild; name = col1.firstElementChild;
            name.innerHTML = rsp[i].grp;
            
            //Var Columna 3 type
            var col2, dsc;
            col2 = col1.nextElementSibling; dsc = col2.firstElementChild;
            dsc.innerHTML = rsp[i].dsc;
            
            
            //Var Columna 5 Nombre anunciante
            var col3, status;
            col3 = col2.nextElementSibling; status = col3.firstElementChild;
            status.firstElementChild.setAttribute("privid",rsp[i].id);
            status.firstElementChild.addEventListener("click", function(ev){
                if(this.classList.contains("active")){
                    this.classList.remove("active");
                    this.firstElementChild.classList.remove("balActive");
                }else{
                    this.classList.add("active");
                    this.firstElementChild.classList.add("balActive");
                } 
                //updtStatus(this);
            });  
            //username.innerHTML = reg[i].emision.account.user.name;
            
            tbl.appendChild(ele);
        }
    }
}
function loadRolPriv(id,tbl){
    var par = {};
        par.rolid = id;
        par.sessionid = sessionStorage.getItem("sessionId");
        callWS("GET", "privileges/loadrolprivileges", par, respuesta);
        function respuesta(status, rsp){
            var resp = JSON.parse(rsp);
            switch(status){
                case 200:
                    var swichs = tbl.getElementsByClassName("switch");
                    for(var i=0;i<swichs.length;i++){
                        swichs[i].classList.remove("active");
                        swichs[i].firstElementChild.classList.remove("balActive");
                        console.log(resp);
                        if(resp.privileges!==null){
                        for(var x=0;x<resp.privileges.length;x++){
                            if(swichs[i].getAttribute("privid") == resp.privileges[x].id){
                                swichs[i].classList.add("active");
                                swichs[i].firstElementChild.classList.add("balActive");
                            }
                        }
                        }
                    }
                    showPopPriv(tbl);
                    
                break;
                case 400:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        myLogout()
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=roles.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                   console.log("estatus 200", resp); 
            }
        }
}

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);
        }
    }
}