var url_tcv = "https://explorador.petro.gob.ve/insight/transaction/";
var url_btc = "https://www.blockchain.com/btc/tx/";

window.onload = function(){
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    var filter = document.getElementById("search").value;
    if(filter == null || filter == undefined){
        filter  = '';
    }
    LoadOperations(filter, 0, '', document.getElementById("registerFilter").value, '', '', '', '',sessionId);
    
    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("arrowRangeFilter").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("arrowTypeFilter").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("arrowCurrencyFilter").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("arrowStatusFilter").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("arrowRegisterFilter").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('returnDeposit').addEventListener("click", function(){
        var modal = document.getElementById("imageModalDeposit");
        modal.style.display = "none";
    });
    
    document.getElementById('returnRetirement').addEventListener("click", function(){
        var modal = document.getElementById("imageModalRetirement");
        modal.style.display = "none";
    });
        
    /*document.getElementById("closeModalDetailRetirement").addEventListener("click", function(){
        var modal = document.getElementById("modalDetailRetirement");
        modal.style.display = "none";
        document.getElementById('approvedOp').style.display = 'table-row';
        document.getElementById('buttonAceptModalRetirement').style.display = 'block';
        document.getElementById('buttonRejectModalRetirement').style.display = 'block';
    });
    
    document.getElementById("closeModalDetailDeposit").addEventListener("click", function(){
        var modal = document.getElementById("modalDetailDeposit");
        modal.style.display = "none";
        document.getElementById('buttonAceptModalDeposit').style.display = 'block';
        document.getElementById('buttonRejectModalDeposit').style.display = 'block';
    });
    
    document.getElementById("closeModalDetailCripto").addEventListener("click", function(){
        var modal = document.getElementById("modalDetailCripto");
        modal.style.display = "none";
    });*/
    
    var tabLinks = document.getElementsByClassName("tablinks");
    for(let i=0; i<tabLinks.length; i++){
        tabLinks[i].addEventListener("click", function(){
            openTab(this);
        })
    }
    
    document.getElementById('buttonAceptModalCripto').addEventListener("click", function(){
        var modal = document.getElementById("modalDetailCripto");
        modal.style.display = "none";
    });
    
    document.getElementById('buttonBackModalRetirement').addEventListener("click", function(){
        var modal = document.getElementById("modalDetailRetirement");
        modal.style.display = "none";
        document.getElementById('approvedOp').style.display = 'block';
        document.getElementById('buttonAceptModalRetirement').style.display = 'block';
        document.getElementById('buttonRejectModalRetirement').style.display = 'block';
        document.getElementById('buttonBackModalRetirement').style.display = 'none';
    });
    
    document.getElementById('buttonBackModalDeposit').addEventListener("click", function(){
        var modal = document.getElementById("modalDetailDeposit");
        modal.style.display = "none";
        document.getElementById('buttonAceptModalDeposit').style.display = 'block';
        document.getElementById('buttonRejectModalDeposit').style.display = 'block';
        document.getElementById('buttonBackModalDeposit').style.display = 'none';
    });
    
    document.getElementById("orderBy").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("rangeFilter").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("typeFilter").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("currencyFilter").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("statusFilter").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("registerFilter").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    document.getElementById("iconSearch").addEventListener("click", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    // Event to input search
    document.getElementById("search").addEventListener("change",function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        
        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if(page1 != undefined){
            page1.classList.add("pSelect");
        }
        
        LoadOperations(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, document.getElementById("statusFilter").value, document.getElementById("rangeFilter").value, document.getElementById("typeFilter").value, document.getElementById("currencyFilter").value, sessionId);
    });
    
    
    //Cargamos las monedas
    LoadCurrencies("", 1, 0, 1000, sessionId);
    
    document.getElementById('rollbackRetirement').addEventListener("click", function(){
        console.log(document.getElementById('txid').value);
        rollbackTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgRetirement");
    });
    
    document.getElementById('buttonAceptModalRetirement').addEventListener("click", function(){
        let ref = document.getElementById('refApproved').value;
        let paydate = document.getElementById('dateApproved').value;
        let fileDeposit = document.getElementById('fileDeposit').files[0];
        let msg = document.getElementById('msgRetirement');
        let now = new Date();
        console.log(fileDeposit);
        
        if(ref == "" || ref == null || paydate == "" || paydate == null ){
            msg.innerHTML="Debe ingresar la referencia y fecha del pago";
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.innerHTML = "";
                msg.classList.remove("msgError"); 
                msg.style.display="none";
            }, 3000);
        }else if (document.getElementById('dateApproved').value !== '' && now.getTime() <= new Date(document.getElementById('dateApproved').value).getTime()){
            msg.innerHTML="No puede reportar fechas futuras";
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.innerHTML = "";
                msg.classList.remove("msgError"); 
                msg.style.display="none";
            }, 3000);
        }else if(fileDeposit == undefined){
            msg.innerHTML="Debe cargar imagen de referencia";
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.innerHTML = "";
                msg.classList.remove("msgError"); 
                msg.style.display="none";
            }, 3000);
        }else{
            approveTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgRetirement", fileDeposit, paydate, ref);
            ref.value = "";
            paydate.value = "";
            fileDeposit.value == null;
        }
        
    });
    
    document.getElementById('buttonRejectModalRetirement').addEventListener("click", function(){
        rejectTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgRetirement");
    });
    
    document.getElementById('buttonAceptModalDeposit').addEventListener("click", function(){
        approveTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgDeposit");
    });
            
    document.getElementById('buttonRejectModalDeposit').addEventListener("click", function(){
        console.log(document.getElementById('txid').value);
        rejectTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgDeposit");
    });
    
    document.getElementById('rollbackDeposit').addEventListener("click", function(){
        console.log(document.getElementById('txid').value);
        rollbackTx(sessionStorage.getItem("sessionId"),document.getElementById('txid').value,"msgDeposit");
    });
    
    document.getElementsByTagName('body')[0].addEventListener("click", function(event){
        let modalCripto = document.getElementById("modalDetailCripto");
        let modalDeposit = document.getElementById("modalDetailDeposit");
        let modalRetirement = document.getElementById("modalDetailRetirement");
        
        if(event.target == modalCripto || event.target == modalDeposit || event.target == modalRetirement){
            modalCripto.style.display = "none";
            modalDeposit.style.display = "none";
            modalRetirement.style.display = "none";
            
            document.getElementById('approvedOp').style.display = 'block';
            document.getElementById('buttonAceptModalRetirement').style.display = 'block';
            document.getElementById('buttonRejectModalRetirement').style.display = 'block';
            document.getElementById('buttonAceptModalDeposit').style.display = 'block';
            document.getElementById('buttonRejectModalDeposit').style.display = 'block';
            
            document.getElementById('refApproved').value = "";
            document.getElementById('dateApproved').value = "";
            document.getElementById('fileDeposit').value = null;
            document.getElementById('fileDeposit').files[0] = null;
        }
    });
    
    document.addEventListener('change', function (evt) {
        if (evt.target.className === 'file') {
            console.log(evt.target);
            console.log(evt.target.files);
            console.log(evt.target.offsetParent.previousElementSibling.children[0].textContent);
            console.log(evt.target.parentNode.parentNode.parentNode.children[2]);
            
            console.log()
            
            var valid = validarFile(evt.target)
            
            if (valid){
                if(evt.target.files[0].name !== 'Selecciona'){
                    
                    // Asignar el nombre y color
                    evt.target.offsetParent.previousElementSibling.children[0].textContent = evt.target.files[0].name
                    evt.target.offsetParent.previousElementSibling.children[0].style.color = "#262624"
                    
                    
                    const inpFile = evt.target;
                    const previewContainer = evt.target.parentNode.parentNode.parentNode.parentNode.parentNode.children[1].children[1].children[1];
                    //const previewImage = previewContainer.children[0];
                    const file = evt.target.files[0];
                    if(file){
                        const reader = new FileReader();
                        reader.readAsDataURL(file);
                        inpFile.setAttribute("loaded",1);
                    }
                }
            }else{
                var msg = document.getElementById("msgRetirement");
                 msg.innerHTML= 'La extensión del archivo no es válida.';
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");   
                    msg.style.display="none";
                }, 3000);
            }
        }  
    });
    
    
     /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
}

function validarFile(all){
    //EXTENSIONES Y TAMANO PERMITIDO.
    var extensiones_permitidas = [".png", ".bmp", ".jpg", ".jpeg", ".pdf", ".doc", ".docx", ".gif"];
    var tamano = 8; // EXPRESADO EN MB.
    var rutayarchivo = all.value;
    var ultimo_punto = all.value.lastIndexOf(".");
    var extension = rutayarchivo.slice(ultimo_punto, rutayarchivo.length);
    if(extensiones_permitidas.indexOf(extension) == -1){
        //alert("Extensión de archivo no valida");
        document.getElementById(all.id).value = "";
        return false; // Si la extension es no válida ya no chequeo lo de abajo.
    }else{
        return true;
    }
}


function LoadOperations(filter, offset, order, numofrecords, status, fecha, type, currencyid, sessionid){
    var par = {};
    par.filter = filter;
    par.offset = offset;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if(dir=="desc")order="-"+order;
    par.order = order;
    par.numofrecords = numofrecords;
    par.status = status;
    par.fecha = fecha; 
    par.type = type;
    par.currencyid = currencyid;
    par.sessionid = sessionid;
    console.log(par);
    callWS("GET", "operations/list", par, respuesta);
        function respuesta(status, rsp){
            let resp = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    console.log("respuesta", resp);
                        if (resp.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 hay operaciones";
                            document.getElementById("paginator").style.display= "none";
                        } else {
                            
                            if(resp.numofrecords <= resp.records.length){
                                document.getElementById("paginator").style.display= "none";    
                            } else {
                                document.getElementById("paginator").style.display= ""; 
                                drawPags(resp.numofrecords, "numbersPaginator",resp.records.length);
                            }
                            /*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
                            paintRows(resp);
                        }
                break;
                
                case 400:
                    msg.innerHTML= resp.errmsg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError");   
                        msg.style.display="none";
                    }, 3000);
                break;
                    
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        myLogout();
                        msg.style.display="none";
                    }, 3000);
                break;
                
                case 403:
                    msg.innerHTML="No posee privilegio para realizar esta operaci\u00F3n";
                    msg.classList.add("msgError");
                    msg.style.marginTop = "10px";
                    msg.style.marginBottom = "10px";
                    msg.style.display="block";
                    /*setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);*/
                break;
                
                case 500:
                    msg.innerHTML="Error Interno";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                break;
                
                default:
                    msg.innerHTML= resp.errmsg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
        }
}

function paintRows(rows){
    console.log("rows to paint session ", rows)
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    var filas;
    if (rows.numofrecords > rows.records.length){
        filas = parseInt(rows.numofrecords) - ((parseInt(pageInPaginator) - 1) * rows.records.length);
        if(filas > rows.records.length){
            filas = rows.records.length;
        }
        console.log(filas);
    } else {
        filas = rows.numofrecords
    }
    for (let i=0; i<filas; i++){
        var divContent= document.createElement("div");
        var div1= document.createElement("div");
        var div2= document.createElement("div");
        var div3= document.createElement("div");
        var div4= document.createElement("div");
        var div5= document.createElement("div");
        var div6= document.createElement("div");
        var div7= document.createElement("div");
        var div8= document.createElement("div");
        div1.classList.add("cell1");
        div2.classList.add("cell2");
        div3.classList.add("cell3");
        div4.classList.add("cell4");
        div5.classList.add("cell5");
        div6.classList.add("cell6");
        div7.classList.add("cell7");
        div8.classList.add("cell8");
        var divCnt1= document.createElement("div");
        var divCnt2= document.createElement("div");
        var divCnt3= document.createElement("div");
        var divCnt4= document.createElement("div");
        var divCnt5= document.createElement("div");
        var divCnt6= document.createElement("div");
        var divCnt7= document.createElement("div");
        var divCnt8= document.createElement("div");
        divCnt1.classList.add("divCellCnt");
        divCnt2.classList.add("divCellCnt");
        divCnt3.classList.add("divCellCnt");
        divCnt4.classList.add("divCellCnt");
        divCnt5.classList.add("divCellCnt");
        divCnt6.classList.add("divCellCnt");
        divCnt7.classList.add("divCellCnt");
        divCnt8.classList.add("divCellCnt");
        // fecha
        var inputName= document.createElement("span");
        // Descripcion
        var inputSymbol= document.createElement("span");
        var inputUser= document.createElement("span");
        var inputCurrency= document.createElement("span");
        var inputType= document.createElement("span");
        var inputMount= document.createElement("span");
        var inputStatus= document.createElement("span");
        
        var p = document.createElement("p");
        var iconEdit= document.createElement("i");
        const index = i;
        
        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-eye");
        iconEdit.style.cursor = 'pointer';
        iconEdit.setAttribute("id", "iconEdit"+index);
        iconEdit.addEventListener("click", function(){
            var typeOp = 0;
            
            //Validamos si es una criptomoneda o fiat
            var isCripto = false;
            var isFiat = false;
            
            if(rows.records[i].account.currency.interface == 1 || rows.records[i].account.currency.interface == 2 || rows.records[i].account.currency.interface == 3){
                isFiat = true;
            }else if(rows.records[i].account.currency.interface == 4 || rows.records[i].account.currency.interface == 5){
                isCripto = true;
            }
    
            /*  1 = retiro CRIPTO
            *   2 = retiro FIAT
            *   3 = deposito FIAT
            *   4 = deposito CRIPTO
            *   5 = transferencia
            */
            if(rows.records[i].type.id == 1 && isCripto && !isFiat){
                typeOp = 4;
            }else if(rows.records[i].type.id == 1 && !isCripto && isFiat){
                typeOp = 3;
            }else if(rows.records[i].type.id == 2 && !isCripto && isFiat){
                typeOp = 2;
            }else if(rows.records[i].type.id == 2 && isCripto && !isFiat){
                typeOp = 1;
            }else if(rows.records[i].type.id == 3 && isCripto && !isFiat){
                typeOp = 5;
            }
            
            OpenDetail(rows.records[i],typeOp);
        });
        
        p.setAttribute("id", "p"+index);
        p.appendChild(iconEdit);
        divCnt8.appendChild(p);
        div8.appendChild(divCnt8);
        
        inputName.disabled=true;
        inputName.setAttribute("id", "inputName"+index);
        inputName.innerHTML = rows.records[i].date.formatted; 
        divCnt1.appendChild(inputName);
        div1.appendChild(divCnt1);
        
        inputSymbol.disabled=true;
        inputSymbol.setAttribute("id", "inputSymbol"+index)
        inputSymbol.innerHTML = rows.records[i].id;
        divCnt2.appendChild(inputSymbol);
        div2.appendChild(divCnt2);
        
        inputUser.disabled=true;
        inputUser.setAttribute("id", "inputSymbol"+index)
        if(rows.records[i].account){
            inputUser.innerHTML = rows.records[i].account.user.usr;
        }
        divCnt3.appendChild(inputUser);
        div3.appendChild(divCnt3);
        
        inputCurrency.disabled=true;
        inputCurrency.setAttribute("id", "inputSymbol"+index)
        if(rows.records[i].account){
            inputCurrency.innerHTML = rows.records[i].account.currency.symbol;
        }
        divCnt4.appendChild(inputCurrency);
        div4.appendChild(divCnt4);
        
        inputType.disabled=true;
        inputType.setAttribute("id", "inputSymbol"+index)
        inputType.innerHTML = rows.records[i].type.dsc;
        divCnt5.appendChild(inputType);
        div5.appendChild(divCnt5);
        
        var typeOp = 0;
            
        //Validamos si es una criptomoneda o fiat
        var isCripto = false;
        var isFiat = false;
            
        if(rows.records[i].account.currency.interface == 1 || rows.records[i].account.currency.interface == 2 || rows.records[i].account.currency.interface == 3){
            isFiat = true;
        }else if(rows.records[i].account.currency.interface == 4 || rows.records[i].account.currency.interface == 5){
            isCripto = true;
        }
    
        /*  1 = retiro CRIPTO
        *   2 = retiro FIAT
        *   3 = deposito FIAT
        *   4 = deposito CRIPTO
        *   5 = transferencia
        */
        if(rows.records[i].type.id == 1 && isCripto && !isFiat){
            typeOp = 4;
        }else if(rows.records[i].type.id == 1 && !isCripto && isFiat){
            typeOp = 3;
        }else if(rows.records[i].type.id == 2 && !isCripto && isFiat){
            typeOp = 2;
        }else if(rows.records[i].type.id == 2 && isCripto && !isFiat){
            typeOp = 1;
        }else if(rows.records[i].type.id == 3 && isCripto && !isFiat){
            typeOp = 5;
        }
            
        inputMount.disabled=true;
        inputMount.setAttribute("id", "inputSymbol"+index)
        inputMount.innerHTML = typeOp != 2 ? rows.records[i].amount.formatted : formattedNumber2((rows.records[i].amount.number - rows.records[i].fee.number).toFixed(rows.records[i].account.currency.decimals));
        divCnt6.appendChild(inputMount);
        div6.appendChild(divCnt6);
        
        inputStatus.disabled=true;
        //inputStatus.classList.add("inputRowCurrencie");
        inputStatus.setAttribute("id", "inputStatus"+index);
        if(rows.records[i].status == 1){
            inputStatus.innerHTML = 'Aprobado';    
        } else if(rows.records[i].status == 0){
            inputStatus.innerHTML = 'Pendiente';    
        } else if(rows.records[i].status == 2){
            inputStatus.innerHTML = 'Rechazado';    
        }
        divCnt7.appendChild(inputStatus);
        div7.appendChild(divCnt7);
        
        /***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(rows.records[i].status.id == 1){
                    swichBg.classList.add("active");
                    swichBal.classList.add("balActive");
                }
                swichBg.appendChild(swichBal);
                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");
                    } 
                    UpdateStatusRow("liSession"+index, this);
                });
            cont.appendChild(swichBg);
        cell.appendChild(cont);
        div4.appendChild(cell);
        div4.style.paddingLeft = "28px";*/
        
        divContent.classList.add("rowCurrencie");
        if(i%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liSession"+index);
        divContent.dataset.id= rows.records[i].id;
        divContent.appendChild(div1);
        divContent.appendChild(div2);
        divContent.appendChild(div5);
        divContent.appendChild(div3);
        divContent.appendChild(div4);
        divContent.appendChild(div6);
        divContent.appendChild(div7);
        divContent.appendChild(div8);
        divContent.style.display = "table";
        divContent.style.width = "100%";
        
        rowCurrencie.appendChild(divContent);
    }
    
    for(let j = rows.records.length; j<10; j++){
        var divContent= document.createElement("div");
        var inputName= document.createElement("div");
        var inputSymbol= document.createElement("div");
        var inputStatus= document.createElement("div");
        const index = j;
        
        inputName.classList.add("inputRowCurrencie");
        inputSymbol.classList.add("inputRowCurrencie");
        inputStatus.classList.add("inputRowCurrencie");
        
        divContent.classList.add("rowCurrencie");
        if(j%2 === 0){
             divContent.classList.add("rowImpar");
        }
        divContent.appendChild(inputName);
        divContent.appendChild(inputSymbol);
        divContent.appendChild(inputStatus);
        divContent.style.display = "table";
        divContent.style.width = "100%";
        //divContent.style.cursor = "none";
        
        rowCurrencie.appendChild(divContent);
    }
}

function drawPags(numofrecords, tbl, recordsAct){
    var pages = Math.ceil( numofrecords / document.getElementById("registerFilter").value );
    console.log(pages);
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if(numbersPaginator.getElementsByClassName("pSelect").length>0){
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
        console.log(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 pagina 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 filter = document.getElementById("search").value;
            
            if(filter == null || filter == undefined){
                filter  = '';
            }
            var offset = (this.innerHTML-1)*recordsAct;
            var orderByOp = document.getElementById("orderBy").value;
            var registerFilteOp = document.getElementById("registerFilter").value;
            var statusFilterOp = document.getElementById("statusFilter").value;
            var rangeFilterOp = document.getElementById("rangeFilter").value;
            var typeFilterOp = document.getElementById("typeFilter").value;
            var currencyIdOp = document.getElementById("currencyFilter").value;
            var sessionId = sessionStorage.getItem("sessionId");
            
            LoadOperations(filter, offset, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, 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 != null && 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 filter = document.getElementById("search").value;
            
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    var offset = (pSel[0].innerHTML-1)*recordsAct;
                    var orderByOp = document.getElementById("orderBy").value;
                    var registerFilteOp = document.getElementById("registerFilter").value;
                    var statusFilterOp = document.getElementById("statusFilter").value;
                    var rangeFilterOp = document.getElementById("rangeFilter").value;
                    var typeFilterOp = document.getElementById("typeFilter").value;
                    var currencyIdOp = document.getElementById("currencyFilter").value;
                    var sessionId = sessionStorage.getItem("sessionId");
            
                    LoadOperations(filter, offset, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, 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 != null && 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 filter = document.getElementById("search").value;
            
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    var offset = (pSel[0].innerHTML-1)*recordsAct;
                    var orderByOp = document.getElementById("orderBy").value;
                    var registerFilteOp = document.getElementById("registerFilter").value;
                    var statusFilterOp = document.getElementById("statusFilter").value;
                    var rangeFilterOp = document.getElementById("rangeFilter").value;
                    var typeFilterOp = document.getElementById("typeFilter").value;
                    var currencyIdOp = document.getElementById("currencyFilter").value;
                    var sessionId = sessionStorage.getItem("sessionId");
            
                    LoadOperations(filter, offset, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, sessionId);
                }
            }
        });
        
        //Evento flecha doble
        
        
        //Evento flecha doble derecha
        
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
}

function OpenDetail(row, typeModal = 0){
    var modal;
    
    /*  1 = retiro CRIPTO
    *   2 = retiro FIAT
    *   3 = deposito FIAT
    *   4 = deposito CRIPTO
    */
    if(typeModal == 1 || typeModal == 4 || typeModal == 5){
        modal = document.getElementById("modalDetailCripto");
    }else if(typeModal == 2){
        modal = document.getElementById("modalDetailRetirement");
    }else if(typeModal == 3){
        modal = document.getElementById("modalDetailDeposit");
    }
    
    console.log(modal);
    modal.style.display = "flex";
    
    //Consultamos para los datos de la transaccion
    LoadMovement(row.id, sessionStorage.getItem("sessionId"), typeModal);
}

function LoadMovement(id,sessionid,typeModal){
    var par = {};
    par.id = id;
    par.sessionid = sessionid;
    console.log(par);
    callWS("GET", "operations/entry", par, respuesta);
        function respuesta(status, rsp){
            let resp = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    console.log("respuesta", resp);
                    loadTx(resp, typeModal);
                break;
                
                case 400:
                    msg.innerHTML= resp.errmsg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError");   
                        msg.style.display="none";
                    }, 3000);
                break;
                    
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        myLogout();
                        msg.style.display="none";
                    }, 3000);
                break;
                
                case 500:
                    msg.innerHTML="Error Interno";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                break;
                
                default:
                    msg.innerHTML= resp.errmsg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.innerHTML = "";
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
        }
}

/*  Funcion para cargar los datos de la transaccion en el modal
*
*/
function loadTx(tx, modal){
    console.log(modal);
    /*  1 = retiro CRIPTO
    *   2 = retiro FIAT
    *   3 = deposito FIAT
    *   4 = deposito CRIPTO
    */
    document.getElementById('txid').value = tx.entry.id;
    
    if(modal == 1 || modal == 4 || modal == 5){
        if(modal == 4){
            document.getElementById('titleModalCripto').innerHTML = "Depósito " + tx.entry.account.currency.symbol;
            document.getElementById("userOrTxLabel").innerHTML = 'Usuario';
            document.getElementById("DestinationColumnCripto").style.display = 'none';
        }else if(modal == 1){
            document.getElementById('titleModalCripto').innerHTML = "Retiro " + tx.entry.account.currency.symbol;
            document.getElementById("userOrTxLabel").innerHTML = 'Usuario';
            document.getElementById("DestinationColumnCripto").style.display = 'none';
        }else if(modal == 5){
            document.getElementById('titleModalCripto').innerHTML = "Transferencia " + tx.entry.account.currency.symbol;
            document.getElementById("userOrTxLabel").innerHTML = 'Usuario Origen';
            document.getElementById("DestinationColumnCripto").style.display = 'table-row';
        }
        
        document.getElementById("paymentDateCripto").innerHTML = tx.entry.payment.date.formatted;
        document.getElementById("userOrTxCripto").innerHTML = modal == 1 ? tx.entry.userpaymentmethod.wallet : tx.entry.account.user.usr;
        document.getElementById("txAmountCripto").innerHTML = tx.entry.amount.formatted;
        document.getElementById("txIdCripto").innerHTML = modal == 5 ? tx.entry.txid : `<span>${tx.entry.txid}</span><a href="${determinateUrl(tx.entry.account.currency.interface, tx.entry.payment.ref)}" target="_blank" class="fas fa-external-link-alt" style="margin-left: 80%;"></a>`;
        document.getElementById("txFeeCripto").innerHTML = tx.entry.fee.formatted;
        if(modal == 5 || modal == 1){
            document.getElementById("txTotalCripto").innerHTML = formattedNumber2((tx.entry.amount.number + tx.entry.fee.number).toFixed(tx.entry.account.currency.decimals));
            modal == 5 ? document.getElementById("userDesTxCripto").innerHTML = tx.entry.userpaymentmethod.user.fullname : null;
        }else{
            document.getElementById("txTotalCripto").innerHTML = formattedNumber2((tx.entry.amount.number - tx.entry.fee.number).toFixed(tx.entry.account.currency.decimals));
        }
        
    }else if(modal == 2){
        document.getElementById('titleModalRetirement').innerHTML = "Retiro " + tx.entry.account.currency.symbol;
        document.getElementById("accountDestinationRetirement").innerHTML = tx.entry.userpaymentmethod.paymentmethod.dsc;
        document.getElementById("paymentDateRetirement").innerHTML = tx.entry.payment.date.formatted;
        document.getElementById("paymentRefRetirement").innerHTML = tx.entry.payment.ref;
        document.getElementById("userTxRetirement").innerHTML = tx.entry.account.user.usr;
        document.getElementById("userNameRetirement").innerHTML = tx.entry.account.user.fullname;
        document.getElementById("userDocRetirement").innerHTML = tx.entry.account.user.doc;
        document.getElementById("txAmountRetirement").innerHTML = tx.entry.amount.formatted;
        document.getElementById("txFeeRetirement").innerHTML = tx.entry.fee.formatted;
        document.getElementById("txTotalRetirement").innerHTML = formattedNumber2((tx.entry.amount.number - tx.entry.fee.number).toFixed(tx.entry.account.currency.decimals));
        dragDetails(tx.entry.userpaymentmethod,1,"Retirement");
        dragDetails(tx.entry.userpaymentmethod,2,"Retirement");
        dragDetails(tx.entry.userpaymentmethod,3,"Retirement");
        dragDetails(tx.entry.userpaymentmethod,4,"Retirement");
        
        //Si ya esta validado no mostramos los datos para aprobar/rechazar
        //Ni los botones
        if(tx.entry.rejected != null || tx.entry.valid != null){
            document.getElementById('approvedOp').style.display = 'none';
            document.getElementById('buttonAceptModalRetirement').style.display = 'none';
            document.getElementById('buttonRejectModalRetirement').style.display = 'none';
            document.getElementById('buttonBackModalRetirement').style.display = 'block';
            document.getElementById('rollbackRetirement').style.display = "block";
            
            if(tx.entry.payment.url == null){
                document.getElementById('txImgRetirement').style.display = "none";
            }else{
                document.getElementById('txImgRetirement').style.display = "block";
                document.getElementById('txImgRetirement').addEventListener("click", function(){
                    var modal = document.getElementById("imageModalRetirement");
                    modal.style.display = "block";
                    var previewImage = document.getElementById("imgPreviewRetirement");
                    previewImage.setAttribute("src",tx.entry.payment.url);
                });
            }
            
        }else{
            document.getElementById('buttonBackModalRetirement').style.display = 'none';
            document.getElementById('rollbackRetirement').style.display = "none";
            document.getElementById('txImgRetirement').style.display = "none";
        }
    }else if(modal == 3){
        document.getElementById('titleModalDeposit').innerHTML = "Depósito " + tx.entry.account.currency.symbol;
        document.getElementById("accountDestinationDeposit").innerHTML = tx.entry.userpaymentmethod.paymentmethod.dsc;
        document.getElementById("paymentDateDeposit").innerHTML = tx.entry.payment.date.formatted;
        document.getElementById("paymentRefDeposit").innerHTML = tx.entry.payment.ref;
        document.getElementById("userTxDeposit").innerHTML = tx.entry.account.user.usr;
        document.getElementById("txAmountDeposit").innerHTML = tx.entry.amount.formatted;
        document.getElementById("txFeeDeposit").innerHTML = tx.entry.fee.formatted;
        document.getElementById("txTotalDeposit").innerHTML = formattedNumber2((tx.entry.amount.number - tx.entry.fee.number).toFixed(tx.entry.account.currency.decimals));
        dragDetails(tx.entry.userpaymentmethod,1,"Deposit");
        dragDetails(tx.entry.userpaymentmethod,2,"Deposit");
        dragDetails(tx.entry.userpaymentmethod,3,"Deposit");
        dragDetails(tx.entry.userpaymentmethod,4,"Deposit");
        
        document.getElementById('txImgDeposit').addEventListener("click", function(){
            var modal = document.getElementById("imageModalDeposit");
            modal.style.display = "block";
            var previewImage = document.getElementById("imgPreview");
            previewImage.setAttribute("src",tx.entry.payment.url);
        });
        
        //Si ya esta validado no mostramos los datos para aprobar/rechazar
        //Ni los botones
        if(tx.entry.rejected != null || tx.entry.valid != null){
            document.getElementById('buttonAceptModalDeposit').style.display = 'none';
            document.getElementById('buttonRejectModalDeposit').style.display = 'none';
            document.getElementById('buttonBackModalDeposit').style.display = 'block';
            document.getElementById('rollbackDeposit').style.display = "block";
        }else{
            document.getElementById('buttonBackModalDeposit').style.display = 'none';
            document.getElementById('rollbackDeposit').style.display = "none";
        }
    }
}

function determinateUrl(interfacetx, txid){
    switch(interfacetx){
        case 5:
            return url_tcv + "" + txid;
            break;
        case 4:
            return url_btc + "" + txid;
            break;
    }
}

function dragDetails(account, detailid, modal){
    //Grupo de un detalle
    let mainDiv = document.getElementById(`accountDetails${detailid}${modal}`);
    let label = document.createElement("div");
    let value = document.createElement("div");
    
    //Limpiamos el div 
    while(mainDiv.firstChild){
        mainDiv.removeChild(mainDiv.firstChild);
    }
    
    //Adjuntamos las clases a los divs
    label.classList.add("rowDetailRetirement","firstColDetail");
    value.classList.add("rowDetailRetirement","secondColDetail");
    
    //Quitamos los bordes
    label.style.borderBottom = "none";
    value.style.borderBottom = "none";
    
    //Colocamos el texto
    label.innerHTML = `${account.paymentmethod[`details${detailid}`]}`;
    value.innerHTML = `${account[`details${detailid}`]}`;
    
    //Mostramos en pantalla
    console.log(account[`details${detailid}`]);
    if(account[`details${detailid}`] != null && account.paymentmethod[`details${detailid}`] != null){
        mainDiv.appendChild(label);
        mainDiv.appendChild(value);
    }
}

function LoadCurrencies(filter, order, offset, numofrec, sessionid){
    var req = {};
    req.filter = filter;
    req.order = order;
    req.offset = offset;
    req.numofrec = numofrec;
    req.sessionid = sessionid;
    
    callWS("GET", "currencies/list", req, respuesta);
    function respuesta(status, rsp){
        let resp = JSON.parse(rsp);
        var currencies = document.getElementById("currencyFilter");
        //var msg = document.getElementById("messageApi")
        switch(status){
            case 200:
                for (let i=0; i<resp.records.length; i++){
                    var op = document.createElement("option");
                    if(resp.records.length == 0){
                        op.text= "No hay monedas definidas";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        currencies.appendChild(op);
                    } else {
                        if(resp.records[i].status.id == 1){
                            op.text= resp.records[i].name + "(" + resp.records[i].symbol + ")";
                            op.value = resp.records[i].id;
                            currencies.appendChild(op);
                        }
                    }
                }
                
                
            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 500:
                /*msg.innerHTML="Error al actualizar monedas, 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);*/
        }
    }
}

function approveTx(sessionId, id, msgName, paymentfile = "", paymentdate = "", paymentref = ""){
    var req = {};
    req.id = id;
    req.sessionid = sessionId;
    paymentdate != "" ? req.paymentdate = paymentdate : null;
    paymentref != "" ? req.paymentref = paymentref : null;
    req.paymentfile = paymentfile;
    
    console.log(req);
    document.getElementById('buttonAceptModalDeposit').setAttribute("disabled","true");
    document.getElementById('buttonRejectModalDeposit').setAttribute("disabled","true");
    document.getElementById('buttonAceptModalRetirement').setAttribute("disabled","true");
    document.getElementById('buttonRejectModalRetirement').setAttribute("disabled","true");
    
    callWS("POST", "operations/accept", req, respuesta);
    function respuesta(status, rsp){
        let resp = JSON.parse(rsp);
        let msg = document.getElementById(`${msgName}`);
        switch(status){
            case 200:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Movimiento aprobado correctamente";
                msg.style.display = "block";
                
                setTimeout(function() {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display="none";
                    
                    //Se desmarca la pagina anterior
                    var pSel = document.getElementsByClassName("pSelect");
                    if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
                    //Colocamos la pagina 1
                    var page1 = document.getElementsByClassName("pages")[0];
                    if(page1 != undefined){
                        page1.classList.add("pSelect");
                    }
                    
                    document.getElementById('refApproved').value = "";
                    document.getElementById('dateApproved').value = "";
                    document.getElementById('fileDeposit').value = null;
                    document.getElementById('fileDeposit').files[0] = null;
        
                    //Se repinta el listado desde el offset seleccionado
                    var filter = document.getElementById("search").value;
                
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    var orderByOp = document.getElementById("orderBy").value;
                    var registerFilteOp = document.getElementById("registerFilter").value;
                    var statusFilterOp = document.getElementById("statusFilter").value;
                    var rangeFilterOp = document.getElementById("rangeFilter").value;
                    var typeFilterOp = document.getElementById("typeFilter").value;
                    var currencyIdOp = document.getElementById("currencyFilter").value;
                    var sessionId = sessionStorage.getItem("sessionId");
                    
                    document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                    document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                    document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                    document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                    document.getElementById("modalDetailRetirement").style.display = "none";
                    document.getElementById("modalDetailCripto").style.display = "none";
                    document.getElementById("modalDetailDeposit").style.display = "none";
                    
                    LoadOperations(filter, 0, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, sessionId);
                }, 3000);
    
                break;
            case 400:
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                /*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.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    myLogout();
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 403:
                msg.innerHTML="No posee privilegio para realizar esta operaci\u00F3n";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 500:
                msg.innerHTML="Error Interno";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            break;
            
            default:
                msg.innerHTML= resp.errmsg;
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
        }
    }
}

function rejectTx(sessionId, id, msgName){
    var req = {};
    req.id = id;
    req.sessionid = sessionId;
    
    document.getElementById('buttonAceptModalDeposit').setAttribute("disabled","true");
    document.getElementById('buttonRejectModalDeposit').setAttribute("disabled","true");
    document.getElementById('buttonAceptModalRetirement').setAttribute("disabled","true");
    document.getElementById('buttonRejectModalRetirement').setAttribute("disabled","true");
    
    callWS("GET", "operations/reject", req, respuesta);
    function respuesta(status, rsp){
        let resp = JSON.parse(rsp);
        let msg = document.getElementById(`${msgName}`);
        switch(status){
            case 200:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Movimiento anulado correctamente";
                msg.style.display = "block";
                setTimeout(function() {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display="none";
                    
                    //Se desmarca la pagina anterior
                    var pSel = document.getElementsByClassName("pSelect");
                    if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
                    //Colocamos la pagina 1
                    var page1 = document.getElementsByClassName("pages")[0];
                    if(page1 != undefined){
                        page1.classList.add("pSelect");
                    }
                    
                    //Se repinta el listado desde el offset seleccionado
                    var filter = document.getElementById("search").value;
                
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    
                    document.getElementById('approvedOp').style.display = 'block';
                    var orderByOp = document.getElementById("orderBy").value;
                    var registerFilteOp = document.getElementById("registerFilter").value;
                    var statusFilterOp = document.getElementById("statusFilter").value;
                    var rangeFilterOp = document.getElementById("rangeFilter").value;
                    var typeFilterOp = document.getElementById("typeFilter").value;
                    var currencyIdOp = document.getElementById("currencyFilter").value;
                    var sessionId = sessionStorage.getItem("sessionId");
                    document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                    document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                    document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                    document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                
                    document.getElementById("modalDetailRetirement").style.display = "none";
                    document.getElementById("modalDetailCripto").style.display = "none";
                    document.getElementById("modalDetailDeposit").style.display = "none";
                    
                    LoadOperations(filter, 0, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, sessionId);
                }, 3000);
    
                break;
            case 400:
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                /*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.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    myLogout();
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 403:
                msg.innerHTML="No posee privilegio para realizar esta operaci\u00F3n";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 500:
                msg.innerHTML="Error Interno";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            break;
            
            default:
                msg.innerHTML= resp.errmsg;
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('buttonAceptModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonRejectModalDeposit').removeAttribute("disabled");
                document.getElementById('buttonAceptModalRetirement').removeAttribute("disabled");
                document.getElementById('buttonRejectModalRetirement').removeAttribute("disabled");
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
        }
    }
}

function rollbackTx(sessionId, id, msgName){
    var req = {};
    req.id = id;
    req.sessionid = sessionId;
    document.getElementById('rollbackDeposit').style.display = "none";
    document.getElementById('rollbackRetirement').style.display = "none";
    
    callWS("GET", "operations/cancel", req, respuesta);
    function respuesta(status, rsp){
        let resp = JSON.parse(rsp);
        let msg = document.getElementById(`${msgName}`);
        switch(status){
            case 200:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Movimiento revertido correctamente";
                msg.style.display = "block";
                setTimeout(function() {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display="none";
                    
                    //Se desmarca la pagina anterior
                    var pSel = document.getElementsByClassName("pSelect");
                    if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
                    //Colocamos la pagina 1
                    var page1 = document.getElementsByClassName("pages")[0];
                    if(page1 != undefined){
                        page1.classList.add("pSelect");
                    }
                    
                    //Se repinta el listado desde el offset seleccionado
                    var filter = document.getElementById("search").value;
                
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    var orderByOp = document.getElementById("orderBy").value;
                    var registerFilteOp = document.getElementById("registerFilter").value;
                    var statusFilterOp = document.getElementById("statusFilter").value;
                    var rangeFilterOp = document.getElementById("rangeFilter").value;
                    var typeFilterOp = document.getElementById("typeFilter").value;
                    var currencyIdOp = document.getElementById("currencyFilter").value;
                    var sessionId = sessionStorage.getItem("sessionId");
                    
                    document.getElementById('approvedOp').style.display = 'block';
                    document.getElementById("modalDetailRetirement").style.display = "none";
                    document.getElementById("modalDetailCripto").style.display = "none";
                    document.getElementById("modalDetailDeposit").style.display = "none";
                    
                    document.getElementById('rollbackDeposit').style.display = "block";
                    document.getElementById('rollbackRetirement').style.display = "block";
                    
                    document.getElementById('buttonAceptModalRetirement').style.display = 'block';
                    document.getElementById('buttonRejectModalRetirement').style.display = 'block';
                    document.getElementById('buttonAceptModalDeposit').style.display = 'block';
                    document.getElementById('buttonRejectModalDeposit').style.display = 'block';
                    
                    LoadOperations(filter, 0, orderByOp, registerFilteOp, statusFilterOp, rangeFilterOp, typeFilterOp, currencyIdOp, sessionId);
                }, 3000);
    
                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.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('rollbackDeposit').style.display = "block";
                document.getElementById('rollbackRetirement').style.display = "block";
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    myLogout();
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 403:
                msg.innerHTML="No posee privilegio para realizar esta operaci\u00F3n";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('rollbackDeposit').style.display = "block";
                document.getElementById('rollbackRetirement').style.display = "block";
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            break;
            
            case 500:
                msg.innerHTML="Error Interno";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('rollbackDeposit').style.display = "block";
                document.getElementById('rollbackRetirement').style.display = "block";
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
            break;
            
            default:
                msg.innerHTML= resp.msg;
                msg.classList.add("msgError"); 
                msg.style.display="block";
                document.getElementById('rollbackDeposit').style.display = "block";
                document.getElementById('rollbackRetirement').style.display = "block";
                setTimeout(function() {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
        }
    }
}

function fixDecimals(number){
  number = number.split('').reverse().join('')
  for (var i = 0; i < number.length; i ++){
    if(number[i] == ','){
      return (number.slice(i+1)).split('').reverse().join('')
    }
    else if(number[i] != 0){
      return (number.slice(i)).split('').reverse().join('')
    }
  }
}

function formattedNumber2(num) {
    num +='';
    var splitStr = num.split('.');
    var splitLeft = splitStr[0];
    var splitRight = splitStr.length > 1 ? "," + splitStr[1] : '';
    var regx = /(\d+)(\d{3})/;
    while (regx.test(splitLeft)) {
        splitLeft = splitLeft.replace(regx, '$1' + "." + '$2');
    }
    return splitLeft +splitRight;
}