window.onload = function(){
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    /* Active li */
    var liAct = document.getElementsByClassName("liAct");
    if(liAct.length > 0){
        liAct[0].classList.remove("liAct");
    }
    var sid = getParameterByName("sid");
    console.log("sid ", sid);
    //var sidebar = document.getElementById("sidebar");
    var pageAct = document.getElementById("accounts");
    if(pageAct){
        pageAct.classList.add("liAct");    
    }
    LoadAccounts('', 0, -5, 10, sessionId);
    
    document.getElementById("closeModal").addEventListener("click", function(){
        document.getElementById("dataDelete").innerHTML="";
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
    document.getElementById("closeSectionAdd").addEventListener("click", function(){
        var sectionAddCurrencie = document.getElementById("addSection");
        sectionAddCurrencie.style.visibility = "hidden";
    });
    
    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("arrowStatus").addEventListener("mouseover",function(){
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content =iconContainer.parentElement;
        content.removeChild(iconContainer);
        console.log("content", content);
        console.log("node clone", node)
        setTimeout(function() {
            content.appendChild(node);    
        }, 2000);
        
    });
    
    document.getElementById("arrowPayMethods").addEventListener("mouseover",function(){
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content =iconContainer.parentElement;
        content.removeChild(iconContainer);
        console.log("content", content);
        console.log("node clone", node)
        setTimeout(function() {
            content.appendChild(node);    
        }, 2000);
        
    });
    
    document.getElementById("arrowCountry").addEventListener("mouseover",function(){
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content =iconContainer.parentElement;
        content.removeChild(iconContainer);
        console.log("content", content);
        console.log("node clone", node)
        setTimeout(function() {
            content.appendChild(node);    
        }, 2000);
        
    });
    
    document.getElementById("arrowCurrencie").addEventListener("mouseover",function(){
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content =iconContainer.parentElement;
        content.removeChild(iconContainer);
        console.log("content", content);
        console.log("node clone", node)
        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 = "";
        LoadAccounts('', 0, selectOrderBy.value, 10, sessionId);
        //table.appendChild(nodeClone);
    });
    
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        LoadAccounts(this.value, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        if(e.keyCode==13)LoadAccounts(this.value, 0, document.getElementById("orderBy").value, 10, sessionId);
    });
    
    document.getElementById("iconAddCurrencie").addEventListener("click", function(){
        document.getElementById("StatusAdd").value = "";
        document.getElementById("payMethodsAdd").value= "";
        document.getElementById("detail1").value = "";
        document.getElementById("detail3").value = "";
        document.getElementById("CountryAdd").value = "";
        document.getElementById("detail2").value = "";
        document.getElementById("detail4").value = "";
        document.getElementById("CurrencieAdd").value = "";
        document.getElementById("buttonAceptAdd").setAttribute("eleid","");
        /**blaquear campos***/
        
        
        if(document.getElementById("iconAddCurrencie").getAttribute("data-privilegecreate") == "0"){
            var msg = document.getElementById("messageApi");
            msg.innerHTML="No posee privilegios para crear cuentas";
            msg.style.display = "flex";
            headerTableCurrencies.style.border= "1px solid #D0021B";
            setTimeout(function() {
                msg.style.display="none";
                headerTableCurrencies.style.border= "1px solid #D5DCE5";
            }, 3000);
        } else {
            var sectionAddCurrencie = document.getElementById("addSection");
            sectionAddCurrencie.getElementsByClassName("titleAdd")[0].innerHTML = "Agregar Cuenta";
            sectionAddCurrencie.style.visibility = "visible";
            document.getElementById("StatusAdd").value="1"
        }
    });
    
    document.getElementById("buttonAceptAdd").addEventListener("click", function(){
        var req= {}
        req.sessionid = sessionStorage.getItem("sessionId");
        if(this.getAttribute("eleid")!=="" && this.getAttribute("eleid")!==undefined)
            req.id = this.getAttribute("eleid");
        else    
            req.id = 0;
            
        console.log("req.id ", req.id)
        req.status = document.getElementById("StatusAdd").value;
        req.paymentmethodid = document.getElementById("payMethodsAdd").value;
        req.details1 = document.getElementById("detail1").value;
        req.details3 = document.getElementById("detail3").value;
        req.countryid = document.getElementById("CountryAdd").value;
        req.details2 = document.getElementById("detail2").value;
        req.details4 = document.getElementById("detail4").value;
        req.currencyid = document.getElementById("CurrencieAdd").value;
        if(req.id === "" || req.id === " "){
            var msg = document.getElementById("messageApi");
            msg.innerHTML= "Error al editar Cuenta interna, intente nuevamente";
            msg.classList.add("msgError");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError");
                msg.style.display="none";
            }, 5000);
        } else if( req.status === "" || req.status === " "){
            var msgFail = document.getElementById("msgStatus");
            var inputFail = document.getElementById("StatusAdd");
            msgFail.style.display="block";
            inputFail.style.border= "1px solid #D0021B";
            inputFail.style.marginBottom="0px";
            setTimeout(function() {
                msgFail.style.display="none";
                inputFail.style.marginBottom="8px";
                inputFail.style.border= "0.87px solid #D3D2D2";
            }, 3000);
        } else if( req.countryid === "" || req.countryid === " "){
            var msgFail = document.getElementById("msgCountry");
            var inputFail = document.getElementById("CountryAdd");
            msgFail.style.display="block";
            inputFail.style.border= "1px solid #D0021B";
            inputFail.style.marginBottom="0px";
            setTimeout(function() {
                msgFail.style.display="none";
                inputFail.style.marginBottom="8px";
                inputFail.style.border= "0.87px solid #D3D2D2";
            }, 3000);
            
        } else if(req.paymentmethodid === "" || req.paymentmethodid === " " ){
            var msgFail = document.getElementById("msgPayMethod");
            var inputFail = document.getElementById("payMethodsAdd");
            msgFail.style.display="block";
            inputFail.style.border= "1px solid #D0021B";
            inputFail.style.marginBottom="0px";
            setTimeout(function() {
                msgFail.style.display="none";
                inputFail.style.marginBottom="8px";
                inputFail.style.border= "0.87px solid #D3D2D2";
            }, 3000);
            
        }else if( req.currencyid === "" || req.currencyid === " "){
            var msgFail = document.getElementById("msgCurrencie");
            var inputFail = document.getElementById("CurrencieAdd");
            msgFail.style.display="block";
            inputFail.style.border= "1px solid #D0021B";
            inputFail.style.marginBottom="0px";
            setTimeout(function() {
                msgFail.style.display="none";
                inputFail.style.marginBottom="8px";
                inputFail.style.border= "0.87px solid #D3D2D2";
            }, 3000);
            
        } else if(req.details1 === "" || req.details1 === " "){
            var msgFail = document.getElementById("msgDet1");
            var inputFail = document.getElementById("detail1");
            msgFail.style.display="block";
            inputFail.style.border= "1px solid #D0021B";
            inputFail.style.marginBottom="0px";
            setTimeout(function() {
                msgFail.style.display="none";
                inputFail.style.marginBottom="8px";
                inputFail.style.border= "0.87px solid #D3D2D2";
            }, 3000);
        }else {
            sendApiUpdate(req);
        }
        
    });
    
    //Select país
    document.getElementById("CountryAdd").addEventListener("change", function(){
        loadPaymentmethods(this.value,"");
    });
    
    //Select metodo de pago
    document.getElementById("payMethodsAdd").addEventListener("change", function(){
        for(var i=0;i<paymentMethods.length;i++){
            if(paymentMethods[i].id == this.value){
                drawSelect(document.getElementById("CurrencieAdd"),"dsc", paymentMethods[i].currencies, "", "Monedas");
                document.getElementById("detail1").setAttribute("placeholder",paymentMethods[i].details1);
                document.getElementById("detail2").setAttribute("placeholder",paymentMethods[i].details2);
                document.getElementById("detail3").setAttribute("placeholder",paymentMethods[i].details3);
                document.getElementById("detail4").setAttribute("placeholder",paymentMethods[i].details4);
            }
        }
    });
    
    //Botones modal eliminar
    document.getElementById("buttonCancelModal").addEventListener("click", function(){
        document.getElementById("dataDelete").innerHTML="";
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    document.getElementById("buttonAceptModal").addEventListener("click", function(){
        DeleteRow(this.getAttribute("eleid"));
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
     /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
    
    LoadServicesSectionAdd();
}
var paymentMethods = [];
var countriesPaym = [];
function loadPaymentmethods(countryid,sel){
     var par = {};
        par.order = 1;
        par.offset = 0;
        par.numofrec = 9999;
        par.sessionid =sessionStorage.getItem("sessionId");
        if(countryid !== "")par.countryid = countryid;
        callWS("GET", "paymentmethods/list", par, respuesta);
        function respuesta(status, rsp){
            let currencies = JSON.parse(rsp);
            switch(status){
                case 200:
                    if(currencies.records !== null && countryid !== ""){
                        drawSelect(document.getElementById("payMethodsAdd"),"dsc", currencies.records, sel, "Forma de pago");
                        paymentMethods = currencies.records;
                    }else if(currencies.records !== null && countryid == ""){
                        countriesPaym = [];
                        for(var i=0;i<countriesList.length;i++){
                            for(var x=0;x<currencies.records.length;x++){
                                if(countriesList[i].id == currencies.records[x].country.id){
                                    countriesPaym.push(countriesList[i]);
                                    break;
                                }
                            }
                        }
                        
                        drawSelect(document.getElementById("CountryAdd"),"dsc", countriesPaym, "", "País");
                    }
                break;
                case 400:
                    msg.innerHTML=currencies.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");
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
            }
        }
}
function LoadAccounts(filter,offset,order,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;
        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", "accounts/list", par, respuesta);
        function respuesta(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    
                    if( ! (currencies.privileges.create == false || currencies.privileges.create == "false")){
                        document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "1";
                    } else {
                        document.getElementById("iconAddCurrencie").dataset.privilegeCreate = "0";
                    }
                    
                    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 Cuentas 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
                            if(currencies.records!==null)paintRowsPayMethods(currencies);
                            else{
                                document.getElementById("noCurrencieDefine").style.display= "flex";
                                document.getElementById("msgInTable").innerHTML="No Posee Cuentas definidas";
                                document.getElementById("paginator").style.display= "none";
                            }
                        }
                    }
                    break;
                case 400:
                    msg.innerHTML=currencies.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");
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=currencies.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", currencies); 
            }
        }
}

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;
            LoadAccounts(filter, offset, order, 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;
                    LoadAccounts(filter, offset, order, 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;
                    LoadAccounts(filter, offset, order, 10, sessionStorage.getItem("sessionId"));
                }
            }
        });
        
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
}

function EditRow(id){
    let i = id.substr(id.length - 1);
    
    var sessionId = sessionStorage.getItem("sessionId");
    req = {};
    req.id = document.getElementById(id).getAttribute("data-id");
    console.log("id que se envia en el servicio ", req.id)
    req.sessionid = sessionId;
    callWS("GET", "accounts/entry", req, respuesta);
        function respuesta(status, rsp){
            let respuesta = JSON.parse(rsp);
            var msg = document.getElementById("messageApi")
            switch(status){
                case 200:
                    var sectionAddCurrencie = document.getElementById("addSection");
                    sectionAddCurrencie.getElementsByClassName("titleAdd")[0].innerHTML = "Editar Cuentas";
                    document.getElementById("buttonAceptAdd").setAttribute("eleid", req.id); // respuesta.entry.id
                    console.log("id que escribe en el sectiona add ", document.getElementById("buttonAceptAdd").getAttribute("eleid"))                
                    sectionAddCurrencie.style.visibility = "visible";
                    document.getElementById("StatusAdd").value = respuesta.entry.status;
                    loadPaymentmethods(respuesta.entry.country.id,respuesta.entry.paymentmethod.id);
                    document.getElementById("detail1").value = respuesta.entry.details1;
                    document.getElementById("detail3").value = respuesta.entry.details3;
                    document.getElementById("CountryAdd").value = respuesta.entry.country.id;
                    document.getElementById("detail2").value = respuesta.entry.details2;
                    document.getElementById("detail4").value = respuesta.entry.details4;
                    var cargarpaym = setInterval(function(){
                        if(paymentMethods.length>0){
                            for(var i=0;i<paymentMethods.length;i++){
                                clearInterval(cargarpaym);
                                if(paymentMethods[i].id == respuesta.entry.paymentmethod.id){
                                    drawSelect(document.getElementById("CurrencieAdd"),"dsc", paymentMethods[i].currencies, respuesta.entry.currency.id, "Monedas");
                                    document.getElementById("detail1").setAttribute("placeholder",paymentMethods[i].details1);
                                    document.getElementById("detail2").setAttribute("placeholder",paymentMethods[i].details2);
                                    document.getElementById("detail3").setAttribute("placeholder",paymentMethods[i].details3);
                                    document.getElementById("detail4").setAttribute("placeholder",paymentMethods[i].details4);
                                }
                            }
                        }
                    },1000);
                    /*document.getElementById("dataDelete").innerHTML="";
                    var nodeNoDelete = document.getElementById("noCurrencieDefine");
                    if (nodeNoDelete ){
                        var nodeClone = nodeNoDelete.cloneNode(true);    
                    }
                    var table = document.getElementById("bodyTableCurrencies");
                    table.innerHTML = "";
                    LoadAccounts('', 0, 1, 10, req.sessionid);
                    table.appendChild(nodeClone);*/
                    break;
                    
                case 400:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML=respuesta.msg
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 401:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="No posee los privilegios para actualizar esta cuenta."
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Error al actualizar cuenta, intente nuevamente."
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML= respuesta.msg;
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
            }
        }
    
}

function DeleteRow(id){
    var sessionId = sessionStorage.getItem("sessionId");
    let i = id.substr(id.length - 1);
    
    req = {};
    req.id = id; 
    req.sessionid = sessionId;
    callWS("GET", "accounts/delete", req, respuesta);
        function respuesta(status, rsp){
            if(rsp){
                let respuesta = JSON.parse(rsp);    
            }
            var msg = document.getElementById("messageApi")
            switch(status){
                case 200:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Cuenta eliminada correctamente"
                    msg.classList.add("msgSucessTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgSucessTable");
                        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 pageCnt = document.getElementById("numbersPaginator");
                    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;
                    LoadAccounts(filter,offSetDelete, order, 10, req.sessionid);
                    table.appendChild(nodeClone);
                    break;
                    
                case 304: 
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Existen dependencias que no permiten eliminar esta Cuenta"
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 400:
                    document.getElementById("dataDelete").innerHTML="";
                    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:
                    document.getElementById("dataDelete").innerHTML="";
                    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:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="No posee los privilegios para actualizar Cuentas."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Error al actualizar Cuentas, intente nuevamente."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML= respuesta.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
            }
        }
}
function entryAccount(id){
    let i = id.substr(id.length - 1);
    
    var sessionId = sessionStorage.getItem("sessionId");
    req = {};
    req.id = document.getElementById(id).getAttribute("data-id");
    req.sessionid = sessionId;
    callWS("GET", "accounts/entry", req, respuesta);
        function respuesta(status, rsp){
            let respuesta = JSON.parse(rsp);
            var msg = document.getElementById("messageApi")
            switch(status){
                case 200:
                    UpdateCurrencies(id,respuesta);
                break;
                case 400:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML=respuesta.msg
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 401:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                    break;
                    
                case 403:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="No posee los privilegios para actualizar esta cuenta."
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML="Error al actualizar cuenta, intente nuevamente."
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    document.getElementById("dataDelete").innerHTML="";
                    msg.innerHTML= respuesta.msg;
                    msg.style.color="red";
                    msg.style.textAlign="center";
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.style.display="none";
                    }, 3000);
            }
        }
    
}
function UpdateCurrencies(id,rsp){
    var sessionId = sessionStorage.getItem("sessionId");
    let i = id.substr(id.length - 1);
    
    req.paymentmethodid = rsp.entry.paymentmethod.id;
    req.details1 = rsp.entry.details1;
    req.details3 = rsp.entry.details3;
    req.details2 = rsp.entry.details2;
    req.details4 = rsp.entry.details4;
    req.currencyid = rsp.entry.currency.id;
    
    var status = document.getElementById("userStatus"+i);
    if(status.classList.contains("active"))
        req.status = 1;
    else
        req.status = 0;
    req.sessionid = sessionId;
    
    sendApiUpdate(req);
}

function CancelEditCurrencie(id){
    let i = id.substr(id.length - 1);
    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 pAvailable = document.getElementById("p"+i);
    var pDisabled = document.getElementById("pEdit"+i);
    inputNameEdit.disabled = true;
    inputSymbolEdit.disabled = true;
    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 idItem = parent.getAttribute('data-id');
    let i = id.substr(id.length - 1);
    
    var dataDelete2 = document.createElement("li")
    dataDelete2.innerHTML = "Cuenta: " + document.getElementById("inputNameBank"+i).value;
    dataDelete2.style.fontWeight = "normal";
    var dataDelete1 = document.createElement("li")
    dataDelete1.innerHTML = "País: " + document.getElementById("inputCountry"+i).value;
    dataDelete1.style.fontWeight = "normal";
    var dataDelete3 = document.createElement("li")
    dataDelete3.innerHTML = "Moneda: " + document.getElementById("inputCurrencie"+i).value;
    dataDelete3.style.fontWeight = "normal";
    
    var modal = document.getElementById("myModal");
    document.getElementById("dataDelete").appendChild(dataDelete1);
    document.getElementById("dataDelete").appendChild(dataDelete2);
    document.getElementById("dataDelete").appendChild(dataDelete3);
    modal.style.display = "block";
    
    document.getElementById("buttonAceptModal").setAttribute("eleid",idItem);
    
    
}

function sendApiUpdate(req){
    callWS("GET", "accounts/update", req, respuesta);
        function respuesta(status, rsp){
            if(rsp!=="")var response = JSON.parse(rsp);
            var msg = document.getElementById("messageApi")
            switch(status){
                case 200:
                    
                    document.getElementById("closeSectionAdd").dispatchEvent(new Event("click"));
                    if(req.id === 0){
                        document.getElementById("StatusAdd").value = "";
                        document.getElementById("payMethodsAdd").value= "";
                        document.getElementById("detail1").value = "";
                        document.getElementById("detail3").value = "";
                        document.getElementById("CountryAdd").value = "";
                        document.getElementById("detail2").value = "";
                        document.getElementById("detail4").value = "";
                        document.getElementById("CurrencieAdd").value = "";
                    }
                    if(req.id == 0){
                        msg.innerHTML = "Cuenta creada correctamente";
                    } else{
                        msg.innerHTML = "Cuenta actualizada correctamente";
                    }
                    msg.classList.add("msgSucessTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgSucessTable");
                        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 pageCnt = document.getElementById("numbersPaginator");
                    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;
                    
                    LoadAccounts(filter,offSetDelete, order, 10, req.sessionid);
                    table.appendChild(nodeClone);
                    break;
                case 304:
                    msg.innerHTML="No se realizaron cambios en la Cuenta."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 400:
                    msg.innerHTML=response.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 Cuentas."
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
                    break;
                    
                case 500:
                    msg.innerHTML="Error al actualizar Cuentas, 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= response.msg;
                    msg.classList.add("msgErrorTable");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgErrorTable");
                        msg.style.display="none";
                    }, 3000);
            }
    }
}

function paintRowsPayMethods(paymethods){ 
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    var filas;
    if (paymethods.numofrecords > 10){
        filas = paymethods.records.length;
    } else {
        filas = paymethods.records.length;
    }
    for (i=0; i<filas; i++){
        var divContent= document.createElement("div");
        var labelcheckStatus = document.createElement("label");
        var checkStatus = document.createElement("input");
        var circleCheckStatus = document.createElement("span");
        var inputNameBank= document.createElement("input");
        var inputCountry= document.createElement("input");
        var inputCurrencie= document.createElement("input");
        var inputDetail1= 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 = i;
        
        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-edit");
        iconEdit.setAttribute("id", "iconEdit"+index);
        if( !(paymethods.privileges.update == false || paymethods.privileges.update == "false")){
            iconEdit.addEventListener("click", function(){
                EditRow("liCurrencie"+index)
            });
        }else{
            iconEdit.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para actualizar cuentas.";
                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", "iconDelete"+index);
        if( !(paymethods.privileges.delete == false || paymethods.privileges.delete == "false")){
            iconDelete.addEventListener("click", function(){
                ConfirmDeleteCurrencie("liCurrencie"+index);
            });
        }else{
            iconDelete.addEventListener("click", function(){
                msg.innerHTML="No posee los privilegios para eliminar cuentas.";
                msg.classList.add("msgErrorTable");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgErrorTable");
                    msg.style.display="none";
                }, 3000);
            });
            
        }
        
        p.setAttribute("id", "p"+index);
        p.appendChild(iconEdit);
        p.appendChild(iconDelete);
        p.style.display="inherit";
        p2.style.visibility="visible";
        p2.style.position="relative";
        
        iconDone.classList.add("fas");
        iconDone.classList.add("fa-check-circle");
        iconDone.style.color ="#4287CE";
        iconDone.setAttribute("id", "iconDone"+index);
        
        iconCancel.classList.add("far");
        iconCancel.classList.add("fa-times-circle");
        iconCancel.style.color ="#4287CE";
        iconCancel.setAttribute("id", "iconCancel"+index);
        
        p2.setAttribute("id", "pEdit"+index);
        p2.appendChild(iconDone);
        p2.appendChild(iconCancel);
        p2.style.display="inherit";
        p2.style.visibility="hidden";
        p2.style.position="absolute";
        
        checkStatus.type="checkbox";
        checkStatus.setAttribute("id", "inputSatus"+index);
        circleCheckStatus.classList.add("slider");
        circleCheckStatus.classList.add("round");
        labelcheckStatus.classList.add("switch");
        labelcheckStatus.appendChild(checkStatus);
        labelcheckStatus.appendChild(circleCheckStatus);
        
        inputNameBank.disabled=true;
        inputNameBank.classList.add("inputRowCurrencie");
        inputNameBank.style.textAlign = "center";
        inputNameBank.setAttribute("id", "inputNameBank"+index);
        inputNameBank.setAttribute("payid", paymethods.records[i].paymentmethod.id);
        inputNameBank.value = paymethods.records[i].paymentmethod.dsc;
        
        
        
        inputCountry.disabled=true;
        inputCountry.classList.add("inputRowCurrencie");
        inputCountry.setAttribute("id", "inputCountry"+index);
        inputCountry.dataset.idCountry= paymethods.records[i].country.id;
        inputCountry.value = paymethods.records[i].country.dsc;
        
        inputCurrencie.disabled=true;
        inputCurrencie.classList.add("inputRowCurrencie");
        inputCurrencie.setAttribute("id", "inputCurrencie"+index);
        inputNameBank.setAttribute("idCurr", paymethods.records[i].currency.id);
        inputCurrencie.style.width = "13%";
        inputCurrencie.style.textAlign = "center";
        inputCurrencie.value = paymethods.records[i].currency.symbol; 
        
        
        divContent.classList.add("rowCurrencie");
        if(i%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liCurrencie"+index);
        divContent.dataset.id = paymethods.records[i].id;
        
        //divContent.appendChild(labelcheckStatus);
        /***CREAR SWITCH***/
        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(paymethods.records[i].status == 1){
                    swichBg.classList.add("active");
                    swichBal.classList.add("balActive");
                }
                swichBg.appendChild(swichBal);
                if( !(paymethods.privileges.update == false || paymethods.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");
                    } 
                    entryAccount("liCurrencie"+index);
                });
                }else{
                    swichBg.addEventListener("click", function(){
                        msg.innerHTML="No posee los privilegios para actualizar cuentas.";
                        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);
        
        //Detalle 1
        inputDetail1.disabled=true;
        inputDetail1.classList.add("inputRowCurrencie");
        inputDetail1.setAttribute("id", "inputDetail"+index);
        inputDetail1.value = paymethods.records[i].details1;
        
        
        
        divContent.appendChild(cell);
        
        divContent.appendChild(inputCountry);
        divContent.appendChild(inputNameBank);
        divContent.appendChild(inputCurrencie);
        divContent.appendChild(inputDetail1);
        divContent.appendChild(p);        divContent.appendChild(p2);
        divContent.style.display = "flex";
        
        rowCurrencie.appendChild(divContent);
    }
    
    for(let j = paymethods.records.length; j<10; j++){
        var divContent= document.createElement("div");
        var inputNameBank= document.createElement("input");
        var inputCountry= document.createElement("input");
        var inputCurrencie= document.createElement("select");
        var inputDetail1= document.createElement("input");
        const index = j;
        
        inputNameBank.disabled=true;
        inputNameBank.classList.add("inputRowCurrencie");
        inputNameBank.value = " ";
        
        inputCountry.disabled=true;
        inputCountry.classList.add("inputRowCurrencie");
        inputCountry.value = " ";
        
        inputCurrencie.disabled=true;
        inputCurrencie.classList.add("inputRowCurrencie");
        inputCurrencie.classList.add("selectOrderBy");
        
         //Detalle 1
        inputDetail1.disabled=true;
        inputDetail1.classList.add("inputRowCurrencie");
        
        divContent.classList.add("rowCurrencie");
        if(j%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.appendChild(inputCountry);
        divContent.appendChild(inputNameBank);
        divContent.appendChild(inputCurrencie);
        divContent.appendChild(inputDetail1);
        divContent.style.display = "flex";
        divContent.style.cursor = "none";
        
        rowCurrencie.appendChild(divContent);
    }
}

function LoadServicesSectionAdd(){
    var sessionId = sessionStorage.getItem("sessionId");
    LoadCountries("", 1, 0, 1000, sessionId);
    /*LoadCurrencies("", 1, 0, 1000, sessionId);
    LoadPayMethods("", 0, 1, 1000, sessionId)*/
}
var countriesList = [];
function LoadCountries(filter, order, offset, numofrec, sessionid){
    var req = {};
    req.filter = filter;
    req.order = order;
    req.offset = offset;
    req.numofrec = numofrec;
    req.sessionid = sessionid;
    
    callWS("GET", "countries/list", req, respuesta);
    function respuesta(status, rsp){
        let resp = JSON.parse(rsp);
        var countries = document.getElementById("CountryAdd");
        //var msg = document.getElementById("messageApi")
        switch(status){
            case 200:
                countriesList = resp.records;
                loadPaymentmethods("","");
                /*
                for (let i=0; i<resp.records.length; i++){
                    var op = document.createElement("option");
                    if(resp.records.length == 0){
                        op.text= "No hay paises definidos";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        countries.appendChild(op);
                    } else {
                        if(resp.records[i].status.id == 1){
                            op.text= resp.records[i].dsc
                            op.value = resp.records[i].id;
                            countries.appendChild(op);
                        }
                    }
                }*/
            
            break;
            case 400:
                /*msg.innerHTML=respuesta.msg
                msg.style.color="red";
                msg.style.textAlign="center";
                msg.style.display="block";
                setTimeout(function() {
                    msg.style.display="none";
                }, 3000);*/
                break;
                
            case 401:
                /*msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                msg.style.color="red";
                msg.style.textAlign="center";
                msg.style.display="block";
                setTimeout(function() {
                    msg.style.display="none";
                    myLogout();
                }, 3000);*/
                break;
                
            case 403:
                /*msg.innerHTML="No posee los privilegios para actualizar Cuentas."
                msg.style.color="red";
                msg.style.textAlign="center";
                msg.style.display="block";
                setTimeout(function() {
                    msg.style.display="none";
                }, 3000);*/
                break;
                
            case 500:
                /*msg.innerHTML="Error al actualizar Cuentas, intente nuevamente."
                msg.style.color="red";
                msg.style.textAlign="center";
                msg.style.display="block";
                setTimeout(function() {
                    msg.style.display="none";
                }, 3000);*/
                break;
            default:
                /*msg.innerHTML= respuesta.msg;
                msg.style.color="red";
                msg.style.textAlign="center";
                msg.style.display="block";
                setTimeout(function() {
                    msg.style.display="none";
                }, 3000);*/
        }
    }
}