//Variables globales
var cleared=null;
var sessionId = sessionStorage.getItem("sessionId");
var pagerNumber = 10;
var userSelected;
var userEditId;
var decimCoin = 10;

window.onload = function(){
    initApp();
    var ref = getParameterByName("ref");
    if(ref != "" && ref != null){
        document.getElementById("search").value = ref;
    }
    
    loadList(document.getElementById("search").value, 1, 0, pagerNumber, sessionId);
    
    var selectOrderBy = document.getElementById("orderBy");
    selectOrderBy.addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    
    document.getElementById("afxuserFilt").addEventListener("change",function(){
         loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    
    document.getElementById("registerFilter").addEventListener("change", function(){
        pagerNumber = parseInt(document.getElementById("registerFilter").value);
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        if(e.keyCode==13)loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });

    //FIN BUSQUEDA
    
    document.getElementById("downloadData").addEventListener('click', function(){
        callDownload();
    });
    
    document.getElementById("fileUpload").addEventListener('change', function(){
        if(this.files.length>0)callUpload();
        else{
            var msg = document.getElementById("messageApi");
            msg.innerHTML="No hay ningún archivo para cargar."
            msg.classList.add("msgError"); 
            msg.style.display="block";
            setTimeout(function() {
                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"));
            });
        }
        
    
    document.getElementById("addData").addEventListener('click', function (event) {
        userEditId = 0;
        document.getElementById("doctypeAdd").value = "";
        document.getElementById("docAdd").value = "";
        document.getElementById("nameAdd").value = "";
        document.getElementById("emailAdd").value = "";
        document.getElementById("walletAdd").value = "";
        document.getElementById("organismAdd").value = "";
        document.getElementById("dateAdd").value = "";
        document.getElementById("linkAdd").value = "";
        //User afx
        document.getElementById("emailAFx").value = "";
        document.getElementById("useridAfx").value = "";
        document.getElementById("userlvlAfx").value = "";
        showModal();
    });
    
    //Cancelar crear/editar
    document.getElementById("cancelM").addEventListener('click', function (event) {
        document.getElementById("modalconfir").style.display = "none";
    });
    //Aceptar update
    document.getElementById("aceptM").addEventListener("click",function(){
        transactionsUpdate();
    });
    
    //Modal DELETE
    //Asignación de confirmar delete
    document.getElementById("buttonCancelModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
        var dataDelete = document.getElementById("dataDelete");
        dataDelete.innerHTML="";
        modal.style.display = "none";
    });
    
    document.getElementById("buttonAceptModal").addEventListener("click", function(){
        deleteConf(this.getAttribute("eleid"));
    });
    document.getElementById("closeModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
        var dataDelete = document.getElementById("dataDelete");
        dataDelete.innerHTML="";
        modal.style.display = "none";
    });
}

function deleteConf(id){
    var sessionId = sessionStorage.getItem("sessionId");
    req = {};
    req.id = id; 
    req.sessionid = sessionId;
    callWS("GET", "blacklist/delete", req, respuesta);
        function respuesta(status, rsp){
            if(rsp){
                let respuesta = JSON.parse(rsp);    
            }
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    var modal = document.getElementById("myModal");
                    var dataDelete = document.getElementById("dataDelete");
                    dataDelete.innerHTML="";
                    modal.style.display = "none";
                    
                    var offset = 0;
                    if(document.getElementsByClassName("pSelect").length>0){
                        offset = (document.getElementsByClassName("pSelect")[0].getAttribute("data-page")-1)*pagerNumber;
                    }
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                    document.getElementById("modalconfir").style.display = "";
                
                    //Mensaje SUCESS
                    msg.innerHTML= "Registro en lista negativa eliminado correctamente";
                    msg.classList.add("msgSucess");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgSucess");
                        msg.style.display="none";
                    }, 3000);
                break;
                case 304:
                    var modal = document.getElementById("myModal");
                    var dataDelete = document.getElementById("dataDelete");
                    dataDelete.innerHTML="";
                    modal.style.display = "none";
                    
                    msg.innerHTML="Existen dependencias que no permiten eliminar este registro";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                    
                break;
                case 402:
                    var modal = document.getElementById("myModal");
                    var dataDelete = document.getElementById("dataDelete");
                    dataDelete.innerHTML="";
                    modal.style.display = "none";
                    
                    msg.innerHTML="Existen dependencias que no permiten eliminar este registro";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                    
                break;
                case 400:
                    msg.innerHTML=respuesta.msg
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                break;
                case 401:
                    msg.innerHTML="Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n"
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                        myLogout();
                    }, 3000);
                break;
                case 403:
                    msg.innerHTML="No posee los privilegios para eliminar lista negativa."
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                break;
                case 500:
                    msg.innerHTML="Error al actualizar lista negativa, intente nuevamente."
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                break;
                default:
                    msg.innerHTML= respuesta.msg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
            }
        }
}

function ConfirmDel(id) {
    var parent = document.getElementById(id);
    var idCurrencie = id.split("/")[1];
    let i = idCurrencie;
    
    var inputNameEdit = document.getElementById("usrMailList"+i).innerHTML;
    var modal = document.getElementById("myModal");
    var dataDelete = document.getElementById("dataDelete");
    dataDelete.innerHTML = "";
    var curr = document.createElement("li");
    curr.innerHTML = "Correo: "+ inputNameEdit;
    curr.style.fontWeight= "normal"
    dataDelete.appendChild(curr);
    modal.style.display = "block";
    
    document.getElementById("buttonAceptModal").setAttribute("eleid",idCurrencie);
}

function callDownload(){
    var par = {};
    var sessionid = sessionStorage.getItem("sessionId");
    //Se pasa el document.getElementById("search").value por el parametro filter.
    var filter = document.getElementById("search").value;
    var order = Math.abs(document.getElementById("orderBy").value);
    var dir = document.getElementById("orderDirect").value;
    if(dir=="desc")order="-"+order;
    var afxFilt = document.getElementById("afxuserFilt").value;
    if(afxFilt!=="")afxFilt = "&afxusers="+afxFilt;
    var parmStr = "?sessionid="+sessionid+"&offset=0&numofrec=999999999999&filter="+filter+"&order="+order+afxFilt;
    download("blacklist/listcsv.php"+parmStr);
    return;
}

function callUpload(){
    var par = {};
    par.file = document.getElementById("fileUpload").files[0];
    par.sessionid = sessionStorage.getItem("sessionId");
    callWS("POST", "blacklist/uploadpicture", par, respUploaded);
    return;
}
function respUploaded(status, rsp){
    var msg = document.getElementById("messageApi");
    var rsp = JSON.parse(rsp);
    document.getElementById("fileUpload").value = "";
    switch(status){
        case 200:
            console.log(rsp);
            //SE REPINTA EL LISTADO LUEGO DE LA CARGA
            var offset = 0;
            if(document.getElementsByClassName("pSelect").length>0){
                offset = (document.getElementsByClassName("pSelect")[0].getAttribute("data-page")-1)*pagerNumber;
            }
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
            var msg = document.getElementById("messageApi");
            msg.innerHTML="Se cargaron "+rsp.loaded.news+" Registros nuevos, "+rsp.loaded.updated+" Registros actualizados y "+rsp.loaded.failed+" Registros fallidos";
            msg.classList.add("msgSucess"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgSucess"); 
                msg.style.display="none";
            }, 6000);
        break;
        case 400:
            msg.innerHTML=rsp.msg;
            msg.classList.add("msgError");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError");   
                msg.style.display="none";
            }, 5000);
        break;
        default:
        console.log(rsp);
            msg.innerHTML="El archivo es inválido, por favor cargue un archivo valido con formato de lista negativa";
            msg.classList.add("msgError");
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgError");   
                msg.style.display="none";
            }, 5000);
        break;
    }
    
}

//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid){
    var par = {};
    //Se pasa el document.getElementById("search").value por el parametro filter.
    if(filter !== "" && filter !== undefined && filter !== null)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;
    var afxFilt = document.getElementById("afxuserFilt");
    if(afxFilt.value !== ""){
        par.afxusers = afxFilt.value;
    }
    //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "blacklist/list", par, respList);
    return 0;
}
//Función para el retorno del listado listado
function respList(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                        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);
                            }
                            document.getElementById("paginator").style.display= "none";
                        }else{
                            if(currencies.numofrecords <= pagerNumber){
                                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
                            paintRowsList(currencies);
                     }
                     
                    break;
                case 400:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");   
                        msg.style.display="none";
                    }, 5000);
                    break;
                case 401:
                    msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=" Error Interno";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
}

function addOptions(domElement, data) {
 var select = document.getElementById(domElement);
    for (i = 0; i < data.length; i++) {
        var op = document.createElement("option");
        /*option.value = data[i].id;
        option.text = data[i].name;
        select.add(option);*/
        
        if(data.length == 0){
            op.text= "No hay monedas definidas";
            op.disabled = true;
            op.value = " ";
            op.selected = true;
            select.appendChild(op);
        } else {
            if(data[i].status.id == 1){
                op.text= data[i].name;
                op.value = data[i].id;
                op.setAttribute("decimals", data[i].decimals);
                select.appendChild(op);
            }
        }
                    
    }
}
//Funcion para el Paginado
var pagerNumber = 10;
function drawPags(numofrecords, tbl){
    var pages = Math.ceil( numofrecords / pagerNumber );
    var numbersPaginator = document.getElementById(tbl);
    var lastPag = 0;
    if(numbersPaginator.getElementsByClassName("pSelect").length>0){
        lastPag = numbersPaginator.getElementsByClassName("pSelect")[0].getAttribute("data-page");
    }
    numbersPaginator.innerHTML = "";
    
    var initialPage=0;
    var n=8;
    if (pages>n){  // cambio de formato en caso de mas de n paginas
        initialPage = Math.max((lastPag-Math.ceil(n/2)+2), 1)-1;
    }
    
    // puntitos iniciales cuando son más de 10 página y no se empieza por la primera
    if (pages>n && initialPage !== 0 && initialPage !== 1){
        spanF = document.createElement("div");
        spanF.classList.add("pages");
        spanF.innerHTML = "1 ...";
        spanF.dataset.page= 1;
        spanF.style.cursor="pointer";
        spanF.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page")-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanF);
        /*
        span = document.createElement("div");
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);*/
        
    }

    //Pintar paginas de table (numeros)
    for(var k=initialPage; k<pages && !(k-initialPage > n-1); k++){
        var p = document.createElement("div");
        p.classList.add("pages");
        p.innerHTML = k+1;
        p.dataset.page= k+1;
        if(lastPag==0 && k==0)p.classList.add("pSelect");//Se selecciona la página 1
        else if(lastPag!==0 && (lastPag-1)==k)p.classList.add("pSelect");
        
        p.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.innerHTML-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        p.style.cursor="pointer";
        numbersPaginator.appendChild(p);
                                
    }
    
    // puntitos si no se ven las útlimas páginas
    if (pages>n && initialPage+n<pages){
        /*
        span = document.createElement("div");
        span.setAttribute("title", pages+" páginas")
        span.classList.add("pages");
        span.innerHTML = "...";
        numbersPaginator.appendChild(span);
        */
        
        spanL = document.createElement("div");
        spanL.classList.add("pages");
        spanL.innerHTML = "... "+pages;
        spanL.dataset.page= pages;
        spanL.style.cursor="pointer";
        spanL.addEventListener("click", function(){
            //Se desmarca la página anterior
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0)pSel[0].classList.remove("pSelect");
            
            //Se actualiza la página seleccionada
            this.classList.add("pSelect");
            
            //Se repinta el listado desde el offset seleccionado
            var offset = (this.getAttribute("data-page")-1)*pagerNumber;
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
        });
        numbersPaginator.appendChild(spanL);
    }
    
    
    
    //Asignación de eventos validar que sólo se haga una vez
    if(numbersPaginator.getAttribute("arrowsEvent")=="false"){
        var leftArrow = numbersPaginator.previousElementSibling;
        var rightArrow = numbersPaginator.nextElementSibling;
        //Evento flecha izquierda
        leftArrow.addEventListener("click",function(){
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].previousElementSibling.classList.contains("pages")){
                    var last = pSel[0];
                    pSel[0].previousElementSibling.classList.add("pSelect");
                    last.classList.remove("pSelect");
                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML-1)*pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        //Evento flecha derecha
        rightArrow.addEventListener("click",function(){
            var pSel = document.getElementsByClassName("pSelect");
            if(pSel.length>0){
                //Si el elemento anterior al seleccionado es una pagina
                if(pSel[0].nextElementSibling.classList.contains("pages")){
                    pSel[0].nextElementSibling.classList.add("pSelect");
                    pSel[0].classList.remove("pSelect");
                    
                    //Se repinta el listado desde el offset seleccionado
                    var offset = (pSel[0].innerHTML-1)*pagerNumber;
                    var order = document.getElementById("orderBy").value;
                    var filter = document.getElementById("search").value;
                    loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
    
    
}

//Aqui se pintan los registros
function paintRowsList(data){
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    rowCurrencie.innerHTML = "";
    var filas;    
    let dataC = data.records;
    if(dataC!==undefined && dataC!==null){
        for (let i=0; i<dataC.length; i++){
            var tableLine = document.createElement("div");
            tableLine.classList.add("tableLine");
            tableLine.id= "line/"+dataC[i].id;
            if((i%2)==0){
                tableLine.classList.add("rowImpar");
            }else{
                tableLine.classList.remove("rowImpar");
            }
            /*Popup al hacer hover en el "i" */
            var detailPop = document.createElement("div");
            detailPop.classList.add("detailInfCnt");
                var detLink = document.createElement("div");
                detLink.classList.add("detInfLink");
                detLink.innerHTML = dataC[i].link;
                
                var detUsrid = document.createElement("div");
                detUsrid.classList.add("detInfUsrid");
                detUsrid.innerHTML = '<span style="font-weight:bold;">Cliente AFX</span> '+dataC[i].user.id;
                
                var detLvl = document.createElement("div");
                detLvl.classList.add("detInfLvl");
                var lvl = 0; if(dataC[i].user.level!=="")lvl = dataC[i].user.level;
                detLvl.innerHTML = '<span style="font-weight:bold;">KYC</span> '+lvl;
                
            detailPop.appendChild(detLink);detailPop.appendChild(detUsrid);
            detailPop.appendChild(detLvl);
            
            
            tableLine.innerHTML =                   '<div class="cell1">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].doc.type+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell2">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].doc.dsc+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell3">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].name+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell4">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].account+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell5">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span id="usrMailList'+dataC[i].id+'">'+dataC[i].email+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell6">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].organism+'</span>'+
                                                        '</div>'+
                                                    '</div>'+
                                                    '<div class="cell7">'+
                                                        '<div class="divCellCnt">'+
                                                            '<span>'+dataC[i].date+'</span>'+
                                                        '</div>'+
                                                    '</div>'+              
                                                    '<div class="cell8">'+
                                                        '<div class="transIcons" id="openPop/'+dataC[i].id+'">'+
                                                            '<span><i class="fas fa-info-circle"></i></span>'+
                                                        '</div>'+
                                                        '<div class="transIcons" id="openDel/'+dataC[i].id+'">'+
                                                            '<span><i class="far fa-trash-alt"></i></span>'+
                                                        '</div>'+
                                                    '</div>'; 
            rowCurrencie.appendChild(tableLine);
            tableLine.lastElementChild.firstElementChild.appendChild(detailPop);
            
            tableLine.addEventListener('click', function (event) {
                if(!event.target.classList.contains("transIcons") && !event.target.classList.contains("fas") && !event.target.classList.contains("far")){
                    var id= (this.id).split("/")[1];
                    userEditId = parseInt(id);
                    transactionsEntry(id);
                }
            });
        }
        document.querySelectorAll('[id^="openPop/"]').forEach(function (element) {
            element.addEventListener('click', function (event) {
                var ele = this;
                if(ele.lastElementChild.style.display == ""){
                    ele.lastElementChild.style.display = "block";
                    setTimeout(function(){
                        ele.lastElementChild.style.opacity = 1;   
                    },300);
                }else{
                    ele.lastElementChild.style.opacity = "";
                    setTimeout(function(){
                        ele.lastElementChild.style.display = "";   
                    },300);
                }
            });
            /*
            element.addEventListener('click', function (event) {
                var id= (this.id).split("/")[1];
                userEditId = parseInt(id);
                transactionsEntry(id);
            });*/
        });
        document.querySelectorAll('[id^="openDel/"]').forEach(function (element) {
            element.addEventListener('click', function (event) {
                var id= (this.id).split("/")[1];
                userEditId = parseInt(id);
                ConfirmDel("line/"+parseInt(id));
            });
        });
    }

}

function transactionsEntry(id){
    var par = {};
    par.id = parseInt(id);
    par.sessionid = sessionId;
    callWS("GET", "blacklist/entry", par, rspTransactionsEntry);
    return 0;
}
function rspTransactionsEntry(status, rsp){
    switch(status){
        case 200:
            var rsp=JSON.parse(rsp);
            //Se rellenan los campos
            document.getElementById("doctypeAdd").value = rsp.entry.doc.type;
            document.getElementById("docAdd").value = rsp.entry.doc.dsc;
            document.getElementById("nameAdd").value = rsp.entry.name;
            document.getElementById("emailAdd").value = rsp.entry.email;
            document.getElementById("walletAdd").value = rsp.entry.account;
            document.getElementById("organismAdd").value = rsp.entry.organism;
            var dateA = (rsp.entry.date).split("/");
            var dateFmt = dateA[2]+"-"+dateA[1]+"-"+dateA[0];
            document.getElementById("dateAdd").value = dateFmt;
            document.getElementById("linkAdd").value = rsp.entry.link;
            
            if(rsp.entry.user.id!==0){
                document.getElementById("emailAFx").value = rsp.entry.user.email;
                document.getElementById("useridAfx").value = rsp.entry.user.id;
                document.getElementById("userlvlAfx").value = "Nivel "+rsp.entry.user.level;
            }else{
                
                document.getElementById("emailAFx").value = "";
                document.getElementById("useridAfx").value = "";
                document.getElementById("userlvlAfx").value = "";
            }
            
            showModal();
        break;
        case 400:
            console.log(JSON.parse(rsp));
        break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgErrorUpd"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorUpd"); 
                myLogout()
                msg.style.display="none";
            }, 3000);
        break;
        case 403:
        break;
        case 500:
        break;
        default:
    }
}

function transactionsUpdate(){
    var doctype = document.getElementById("doctypeAdd").value ;
    var doc = document.getElementById("docAdd").value ;
    var name = document.getElementById("nameAdd").value ;
    var email = document.getElementById("emailAdd").value ;
    var account = document.getElementById("walletAdd").value ;
    var organism = document.getElementById("organismAdd").value ;
    var date = document.getElementById("dateAdd").value ;
    var link = document.getElementById("linkAdd").value;
    var par = {};
    var msg = document.getElementById("msgErrorUpd");
    if((doctype == "" || doc == "") && name == "" && email == "" &&
    account == ""){
        msg.innerHTML="Al menos uno de los siguientes campos debe estar lleno documento,correo,nombre o wallet";
        msg.classList.add("msgErrorUpd"); 
        msg.style.display="block";
        setTimeout(function() {
            msg.classList.remove("msgErrorUpd"); 
            msg.style.display="none";
        }, 3000);
        return;
    }
    par.id = userEditId;
    par.doctype = doctype;
    par.doc = doc;
    par.name = name;
    par.email = email;
    par.account = account;
    par.organism = organism;
    par.date = date;
    par.link = link;
    par.sessionid = sessionId;
    callWS("GET", "blacklist/update", par, rspTransactionsUpdate);
    return 0;
}
function rspTransactionsUpdate(status, rsp){
    var msg = document.getElementById("msgErrorUpd");
    switch(status){
        case 200:
            //Se repinta el listado desde el offset seleccionado
            var offset = 0;
            if(document.getElementsByClassName("pSelect").length>0){
                offset = (document.getElementsByClassName("pSelect")[0].getAttribute("data-page")-1)*pagerNumber;
            }
            var order = document.getElementById("orderBy").value;
            var filter = document.getElementById("search").value;
            loadList(filter, order, offset, pagerNumber, sessionStorage.getItem("sessionId"));
            document.getElementById("modalconfir").style.display = "";
        break;
        case 400:
            console.log(JSON.parse(rsp));
        break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgErrorUpd"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorUpd"); 
                myLogout()
                msg.style.display="none";
            }, 3000);
        break;
        case 403:
            if(userEditId==0)msg.innerHTML="No posee privilegios para crear un registro en lista negativa";
            else msg.innerHTML="No posee privilegios para modificar un registro en lista negativa";
            msg.classList.add("msgErrorUpd"); 
            msg.style.display="block";
            setTimeout(function() {
                msg.classList.remove("msgErrorUpd"); 
                msg.style.display="";
            }, 3000);
        break;
        case 500:
        break;
        default:
            console.log(rsp);
    }
}
function showModal(){
    //document.getElementById('txid').value = txId;
    var modal = document.getElementById("modalconfir");
    modal.style.display = "table";
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}


function dateRegEx(date){
    var pattern = new RegExp("^(3[01]|[12][0-9]|0[1-9])/(1[0-2]|0[1-9])/[0-9]{4} (2[0-3]|[01]?[0-9]):([0-5]?[0-9])$");
    if (date.search(pattern)===0) return true;
    else return false; 
}

const dateformatted = (date) => {
    let day = new Date(date);
    return `${(day.getDate() < 10 ? '0' + day.getDate() : day.getDate())}/${((day.getMonth() + 1) < 10 ? "0" + (day.getMonth() + 1) : (day.getMonth() + 1) )}/${day.getFullYear()}T${day.getHours()}:${day.getMinutes()}`;
}

const dateServer = date => {
    let day = new Date(date);
    return `${day.getFullYear()}/${(day.getMonth() + 1)}/${day.getDate()}T${day.getHours()}:${day.getMinutes()}`;
}