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

window.onload = function(){
    initApp();
    loadListCurrencies();
    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("rangeFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("typeFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("pairFilter").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);
    });
    
    document.getElementById("pairFilter1").addEventListener("change", function(e){
        decimCoin = this.options[this.selectedIndex].getAttribute('decimals');
        console.log(this.options[this.selectedIndex].getAttribute('decimals'));
    })
    
    //Crear
    document.getElementById("addData").addEventListener('click', function (event) {
            document.getElementById("buttonsCreate").classList.remove("noShow");
            document.getElementById("buttonsEdit").classList.add("noShow");
            document.getElementById("addDate").value = "";
            document.getElementById("searchUser").value = "";
            document.getElementById("addDescription").value = "";
            document.getElementById("pairFilter1").value = "";
            document.getElementById("addQuantity").value = "";
            document.getElementById("addQuantity").setAttribute("dataNumber","");
            userEditId = 0;
            showModal();
    });
    document.getElementById("cancelM").addEventListener('click', function (event) {
        document.getElementById("modalconfir").style.display = "none";
    });
    document.getElementById("aceptM").addEventListener('click', function (event) {
        transactionsUpdate();
    });
    document.getElementById("editM").addEventListener('click', function (event) {
        transactionsUpdate();
    });
    document.getElementById("deleteM").addEventListener('click', function (event) {
        transactionsDelete();
    });
    //BUSQUEDA INTELIGENTE
    document.getElementById("searchUser").addEventListener("keyup", function(e){
            
            if(this.value.length >= 3){
                    if(cleared !== null){
                        clearTimeout(cleared);
                    }
                    cleared= setTimeout(function(){ myUsers(document.getElementById("searchUser").value); }, 1000);
            }else if(e.keyCode == 8){
                document.getElementById("searchUser").value="";
                userSelected="";
                if(cleared !== null){
                    clearTimeout(cleared);
                }
            }
    });
    window.addEventListener("click", function(){ 
        var div=document.getElementById("searchResult");
            div.classList.add("noShow");
    });
    //FIN BUSQUEDA
    
    document.getElementById("downloadData").addEventListener('click', function(){
        callDownload();
    });
    
     /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
    
    var fieldAmo = ["addQuantity"];
    formatAmount(fieldAmo);
}

function callDownload(){
    var filter =document.getElementById("search").value;
    var currencyid =document.getElementById("pairFilter").value;
    var order = document.getElementById("orderBy").value;
    order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if(dir=="desc")order="-"+order;
    order = order;

    download("transactions/listcsv?filter="+filter+"&currencyid="+currencyid+"&order="+order+"&sessionid="+sessionId);
    return;
}

//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid){
    var date = document.getElementById("rangeFilter").value;
    var type = document.getElementById("typeFilter").value;
    var currencyid = document.getElementById("pairFilter").value; 
    var par = {};
    //Se pasa el document.getElementById("search").value por el parametro filter.
        if(filter !== "" && filter !== undefined && filter !== null)
        par.filter = filter;
        
        if(date !== "" && date !== undefined && date !== null)
        par.daterange = date;
        
        if(type !== "" && type !== undefined && type !== null)
        par.type = type;
        
        if(currencyid !== "" && currencyid !== undefined && currencyid !== null)
        par.currencyid = currencyid;
        
        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;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
        callWS("GET", "transactions/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:
                   // console.log(currencies);

                        if (currencies.numofrecords === 0){
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null){
                                table.appendChild(nodeClone);
                            }
                            /**-hasta aqui-**/
                            //document.getElementById("noCurrencieDefine").style.display= "flex";
                            //document.getElementById("msgInTable").innerHTML="No Posee Balances definidos";
                            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);
            }
}
//Función para cargar listado MONEDAS
function loadListCurrencies(){
    var par= {};
    par.order = 1;
    par.offset = 0;
    par.numofrec = 500;
    par.sessionid = sessionId;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "currencies/list", par, respListCurrencies);
    return 0;
}
function respListCurrencies(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("messageApi");
            switch(status){
                case 200:
                    //console.log(currencies);
                    addOptions("pairFilter",currencies.records);
                    addOptions("pairFilter1",currencies.records);
                    break;
                case 400:
                    console.log(currencies);
                    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:
                    console.log(currencies);
                    break;
                default:
                    console.log(currencies);
            }
}
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
//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;
    if (data.numofrecords > pagerNumber){
        filas = parseInt(data.numofrecords) - ((parseInt(pageInPaginator) - 1) * pagerNumber);
        if(filas > pagerNumber){
            filas = pagerNumber;
        }
    } else {
        filas = data.numofrecords
    }
    
    
    //type 0 = impar, 1 = par
    let type = 0;
    let dataC = data.records;
    for (let i=0; i<filas; i++){
        var tableLine = document.createElement("div");
        tableLine.classList.add("tableLine");
        tableLine.id= "line/"+dataC[i].id;
        if(type === 0){
            tableLine.classList.add("rowImpar");
            type=type+1;
        }else if(type === 1){
            type = 0;
        }
        tableLine.innerHTML = '<div class="cell1">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].date.formatted+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell2">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].id+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell3">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].type+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell4">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].description+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell5">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].user.usr+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell7">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].currency.symbol+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell8">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].amount.formatted+'</span>'+
                                                    '</div>'+
                                                '</div>';
                        if(dataC[i].type === 'Ajuste'){                        
                        tableLine.innerHTML += '<div class="cell9">'+
                                                    '<div class="transIcons" id="openPop/'+dataC[i].id+'">'+
                                                        '<span>'+'<i class="far fa-edit"></i></span>'+
                                                    '</div>'+
                                                '</div>'; 
                        }else{
                            tableLine.innerHTML += '<div class="cell9">'+
                                                    '<div class="transIcons">'+
                                                    '</div>'+
                                                '</div>'; 
                        }
        rowCurrencie.appendChild(tableLine);
    }
    document.querySelectorAll('[id^="openPop/"]').forEach(function (element) {
        element.addEventListener('click', function (event) {
            var id= (this.id).split("/")[1];
            document.getElementById("buttonsCreate").classList.add("noShow");
            document.getElementById("buttonsEdit").classList.remove("noShow");
            userEditId = parseInt(id);
            transactionsEntry(id);
            showModal();
        });
    });

}
function transactionsEntry(id){
    var par = {};
    par.id = parseInt(id);
    par.sessionid = sessionId;
    callWS("GET", "transactions/entry", par, rspTransactionsEntry);
    return 0;
}
function rspTransactionsEntry(status, rsp){
    switch(status){
        case 200:
            //console.log(JSON.parse(rsp));
            var resp=JSON.parse(rsp);
            let date = resp.date.cannonical;
            date = date.replace(" ", "T");
            document.getElementById("addDate").value = date;
            document.getElementById("searchUser").value = resp.user.usr;
            document.getElementById("addDescription").value = resp.description;
            document.getElementById("pairFilter1").value = resp.currency.id;
            decimCoin = resp.currency.decimals;
            console.log(decimCoin);
            document.getElementById("addQuantity").value = resp.amount.formatted;
            document.getElementById("addQuantity").setAttribute("dataNumber",parseFloat(resp.amount.number).toFixed(decimCoin));
            userSelected = resp.user.id;
            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("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}
function transactionsDelete(){
    var par = {};
    par.id = userEditId;
    par.sessionid = sessionId;
    callWS("GET", "transactions/delete", par, rspTransactionsDelete);
    return 0;
}
function rspTransactionsDelete(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            location.reload();
            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("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}
function transactionsUpdate(){
    var date = document.getElementById("addDate").value;
    var user = document.getElementById("searchUser").value ;
    var desc = document.getElementById("addDescription").value ;
    var currency = document.getElementById("pairFilter1").value ;
    var amount = document.getElementById("addQuantity").value;
    var msg = document.getElementById("msgError");
    if(date === "" || user === "" || desc === "" || currency === "" || amount === ""){
        msg.innerText="Por favor complete todos los campos.";
        msg.style.visibility="visible";
        setTimeout(function() {
            msg.style.visibility="hidden";
        }, 4000);
        return 0;
    }
    
    console.log(date);
    
    // Validamos que la fecha sea una valida
    let dateSticked = new Date('1950-12-12');
    let dateForm = new Date(date);
    
    if(dateSticked > dateForm){
        msg.innerText="Formato de fecha inválido.";
        msg.style.visibility="visible";
        setTimeout(function() {
            msg.style.visibility="hidden";
        }, 4000);
        return 0;
    }
    console.log(dateForm);
    
    let dateForValid = dateformatted(date).replace('T',' ');
    if(!dateRegEx(dateForValid)){
        console.log(dateForValid);
        msg.innerText="Formato de fecha inválido.";
        msg.style.visibility="visible";
        setTimeout(function() {
            msg.style.visibility="hidden";
        }, 4000);
        return 0;
    }
    
    console.log(date);
    
    debugger;
    var par = {};
    par.id = userEditId;
    par.date = dateServer(date);
    par.dsc = desc;
    par.currencyid = currency;
    par.userid = userSelected;
    par.amount = amount;
    par.sessionid = sessionId;
    console.log(par)
    callWS("GET", "transactions/update", par, rspTransactionsUpdate);
    return 0;
}
function rspTransactionsUpdate(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            location.reload();
            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("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}
function showModal(){
    //document.getElementById('txid').value = txId;
    var modal = document.getElementById("modalconfir");
    modal.style.display = "block";
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}


//************* BUSQUEDA INTELIGENTE *******************
function myUsers(value){
    var par = {};
    par.filter = value;
    par.offset = 0;
    par.order = "1";
    par.numofrecords = 2000;
    par.sessionid = sessionId;
    callWS("GET", "appusers/list", par, rspUser);
    return 0;
}
function rspUser(status, rsp){
        switch(status){
            case 200:
               // console.log(JSON.parse(rsp));
                var resp=JSON.parse(rsp);
                var lista=document.getElementById("resultsC");
                var div=document.getElementById("searchResult");
                div.classList.remove("noShow");
                mySearchAddUser(lista,resp.records,resp.numofrecords);
                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("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
            case 403:
                console.log(JSON.parse(rsp));
                break;
            case 500:
                var resSeller=JSON.parse(rsp);
                alert("Error 500 "+resSeller.msg);
                console.log(JSON.parse(rsp));
                break;
            default:
                //console.log(rsp);
        }
    }
function mySearchAddUser(lista,data,num){
    lista.innerHTML = "";
    if(num===0){
      var line = document.createElement("li"); 
      line.innerHTML ='<span class="smallRsp">No tenemos registros que coincidan con su busqueda.</span>';
      lista.appendChild(line);
    }else{
        for(navLink of data){
            var line = document.createElement("li");
            line.classList.add("myNewLineUser");
            line.id="user-"+navLink.id;
            line.innerHTML ='<p class="nameResult"> '+navLink.usr+'</p>';
                lista.appendChild(line);
        }  
    }
    document.querySelectorAll('[class="myNewLineUser"]').forEach(function (element) {
       element.addEventListener('click', function (event) {
         var id=element.id;
         var par = {};
                par.id = parseInt(id.split("-")[1]);
                par.sessionid = sessionId;
                callWS("GET", "appusers/entry", par, rspUserEntry);
                return 0;
        }); 
    });
}
function rspUserEntry(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            var resp=JSON.parse(rsp).entry;
            var inputUser= document.getElementById("searchUser");
            inputUser.value=resp.usr;
            userSelected=resp.id;
            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("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}

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()}/${(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()}`;
}