window.onload = function () {
    var sessionId = sessionStorage.getItem("sessionId");
    var ref = getParameterByName("ref");
    initApp();

    if (ref != "" && ref != null) {
        document.getElementById("search").value = ref;
    }

    var filter = document.getElementById("search").value;
    if (filter == null || filter == undefined) {
        filter = '';
    }

    LoadPairs(sessionId, 0, 0, 9999);
    LoadExchanges(filter, 0, '', document.getElementById("registerFilter").value, sessionId, '', '', '');

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

    document.getElementById("pairFilter").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");
        }

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

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

        LoadExchanges(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

    // Download CSV
    document.getElementById('downloadData').addEventListener("click", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }

        var pSel = document.getElementsByClassName("pSelect");

        downloadCSV(filter, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId, document.getElementById('rangeFilter').value, document.getElementById('typeFilter').value, document.getElementById('pairFilter').value);
    });

    /*funcion del ordenar**/

    var orderDirect = document.getElementById("orderDirect");
    if (orderDirect !== null) {
        orderDirect.addEventListener("change", function () {
            document.getElementById("orderBy").dispatchEvent(new Event("change"));
        });
    }
}

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 = "";

    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 filter = document.getElementById("search").value;

            if (filter == null || filter == undefined) {
                filter = '';
            }
            var offset = (this.getAttribute("data-page") - 1) * recordsAct;
            var sessionId = sessionStorage.getItem("sessionId");
            var order = document.getElementById('orderBy').value;
            var numofrecords = document.getElementById('registerFilter').value;
            var daterange = document.getElementById('rangeFilter').value;
            var type = document.getElementById('typeFilter').value;
            var pairid = document.getElementById('pairFilter').value;

            LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
        });
        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 filter = document.getElementById("search").value;

            if (filter == null || filter == undefined) {
                filter = '';
            }
            var offset = (this.innerHTML - 1) * recordsAct;
            var sessionId = sessionStorage.getItem("sessionId");
            var order = document.getElementById('orderBy').value;
            var numofrecords = document.getElementById('registerFilter').value;
            var daterange = document.getElementById('rangeFilter').value;
            var type = document.getElementById('typeFilter').value;
            var pairid = document.getElementById('pairFilter').value;

            LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
        });
        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 filter = document.getElementById("search").value;

            if (filter == null || filter == undefined) {
                filter = '';
            }
            var offset = (this.getAttribute("data-page") - 1) * recordsAct;
            var sessionId = sessionStorage.getItem("sessionId");
            var order = document.getElementById('orderBy').value;
            var numofrecords = document.getElementById('registerFilter').value;
            var daterange = document.getElementById('rangeFilter').value;
            var type = document.getElementById('typeFilter').value;
            var pairid = document.getElementById('pairFilter').value;

            LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
        });
        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 != undefined) {
                    if (pSel[0].previousElementSibling.classList.contains("pages")) {
                        var last = pSel[0];
                        pSel[0].previousElementSibling.classList.add("pSelect");
                        last.classList.remove("pSelect");
                        var filter = document.getElementById("search").value;

                        if (filter == null || filter == undefined) {
                            filter = '';
                        }
                        var offset = (pSel[0].innerHTML - 1) * recordsAct;
                        var sessionId = sessionStorage.getItem("sessionId");
                        var order = document.getElementById('orderBy').value;
                        var numofrecords = document.getElementById('registerFilter').value;
                        var daterange = document.getElementById('rangeFilter').value;
                        var type = document.getElementById('typeFilter').value;
                        var pairid = document.getElementById('pairFilter').value;

                        LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
                    }
                }
            }
        });
        //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 filter = document.getElementById("search").value;

                    if (filter == null || filter == undefined) {
                        filter = '';
                    }
                    var offset = (pSel[0].innerHTML - 1) * recordsAct;
                    var sessionId = sessionStorage.getItem("sessionId");
                    var order = document.getElementById('orderBy').value;
                    var numofrecords = document.getElementById('registerFilter').value;
                    var daterange = document.getElementById('rangeFilter').value;
                    var type = document.getElementById('typeFilter').value;
                    var pairid = document.getElementById('pairFilter').value;

                    LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent", true);
    }


}
/*
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 sessionId = sessionStorage.getItem("sessionId");
            var order = document.getElementById('orderBy').value;
            var numofrecords = document.getElementById('registerFilter').value;
            var daterange = document.getElementById('rangeFilter').value;
            var type = document.getElementById('typeFilter').value;
            var pairid = document.getElementById('pairFilter').value;
            
            LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
            
    
        });
        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 sessionId = sessionStorage.getItem("sessionId");
                    var order = document.getElementById('orderBy').value;
                    var numofrecords = document.getElementById('registerFilter').value;
                    var daterange = document.getElementById('rangeFilter').value;
                    var type = document.getElementById('typeFilter').value;
                    var pairid = document.getElementById('pairFilter').value;
                
                    LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
                }
            }
        });
        
        //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 sessionId = sessionStorage.getItem("sessionId");
                    var order = document.getElementById('orderBy').value;
                    var numofrecords = document.getElementById('registerFilter').value;
                    var daterange = document.getElementById('rangeFilter').value;
                    var type = document.getElementById('typeFilter').value;
                    var pairid = document.getElementById('pairFilter').value;
                
                    LoadExchanges(filter, offset, order, numofrecords, sessionId, daterange, type, pairid);
                }
            }
        });
        
        //Evento flecha doble
        
        
        //Evento flecha doble derecha
        
        numbersPaginator.setAttribute("arrowsEvent",true);
    }
}*/

function LoadExchanges(filter, offset, order, numofrecords, sessionid, daterange, type, pairid) {
    var par = {};
    par.filter = filter;
    par.sessionid = sessionid;
    par.offset = offset;
    par.numofrecords = numofrecords;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if (dir == "desc") order = "-" + order;
    par.order = order;
    par.daterange = daterange;
    par.type = type;
    par.pairid = pairid;
    console.log(par);
    callWS("GET", "exchanges/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('noCurrencieDefine').style.justifyContent = "center";
                    document.getElementById("msgInTable").innerHTML = "No hay Intercambios";
                    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");
                    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";
                /*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);
        }
    }
}

//PARA LLAMAR A TODOS LOS SERVICIOS
function callWSCSV(type, service, params, response) {
    var globalurl = ".";
    var url = globalurl + "/api/" + service + ".php";
    var wait = document.createElement("div");
    wait.classList.add("waitScreen")
    wait.setAttribute("id", "waitScreen");
    var spin = document.createElement("div");
    spin.classList.add("spinChar");
    spin.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i>';
    wait.appendChild(spin);
    document.body.appendChild(wait);
    WS_waitscreen = true;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4) {
            var rsp = "";
            if (this.responseText !== "") {
                rsp = this.responseText;
                response(this.status, this.responseText);
            } else {
                response(this.status, this.responseText);
            }
            var waitScreen = document.getElementById("waitScreen");
            document.body.removeChild(waitScreen);
            WS_waitscreen = false;
        }
    }
    switch (type) {
        case "GET":
            var parsedPars = Object.keys(params).map(function (k) {
                return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
            }).join('&');
            xhttp.open(type.toUpperCase(), url + "?" + parsedPars, true);
            xhttp.send();
            break;
    }
}
function downloadCSV(filter, offset, order, numofrecords, sessionid, daterange, type, pairid) {
    var par = {};
    par.filter = filter;
    par.sessionid = sessionid;
    par.offset = offset;
    par.numofrecords = numofrecords;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if (dir == "desc") order = "-" + order;
    par.order = order;
    par.daterange = daterange;
    par.type = type;
    par.pairid = pairid;
    console.log(par);
    callWSCSV("GET", "exchanges/reportexchanges", par, respuesta);
    function respuesta(status, rsp) {
        let resp = rsp;
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                console.log("respuesta", resp);
                let contentType = 'application/octet-stream';
                var a = document.createElement('a');
                var blob = new Blob([resp], { 'type': contentType });
                a.href = window.URL.createObjectURL(blob);
                a.download = 'intercambios.csv';
                a.click();
                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.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
    }
    console.log(filas);
    for (let i = 0; i < filas; i++) {
        const index = 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");
        var div9 = 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");
        div9.classList.add("cell9");
        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");
        var divCnt9 = 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");
        divCnt9.classList.add("divCellCnt");
        // fecha
        var dateExchange = document.createElement("span");
        // ref
        var refExchange = document.createElement("span");
        // par
        var parExchange = document.createElement("span");
        // kind
        var kindExchange = document.createElement("span");
        // id bid 
        var bidExchange = document.createElement("span");
        // id ask
        var askExchange = document.createElement("span");
        //qty
        var qtyExchange = document.createElement("span");
        //price
        var priceExchange = document.createElement("span");
        //total
        var totalExchange = document.createElement("span");

        dateExchange.disabled = true;
        dateExchange.setAttribute("id", "dateExchange" + index);
        dateExchange.innerHTML = rows.records[i].date.formatted;
        divCnt1.appendChild(dateExchange);
        div1.appendChild(divCnt1);

        refExchange.disabled = true;
        refExchange.setAttribute("id", "refExchange" + index)
        refExchange.innerHTML = rows.records[i].id;
        divCnt2.appendChild(refExchange);
        div2.appendChild(divCnt2);

        parExchange.disabled = true;
        parExchange.setAttribute("id", "parExchange" + index)
        parExchange.innerHTML = rows.records[i].pair.dsc;
        divCnt3.appendChild(parExchange);
        div3.appendChild(divCnt3);

        kindExchange.disabled = true;
        kindExchange.setAttribute("id", "kindExchange" + index)
        //if(rows.records[i].type.id == 1){
        kindExchange.innerHTML = rows.records[i].side.dsc;
        /*}else if(rows.records[i].type.id == 2){
            if(rows.records[i].side.id == 1){
                kindExchange.innerHTML = 'Compra';
            }else{
                kindExchange.innerHTML = 'Venta';
            }
            
        }*/
        divCnt4.appendChild(kindExchange);
        div4.appendChild(divCnt4);

        bidExchange.disabled = true;
        bidExchange.setAttribute("id", "bidExchange" + index)
        bidExchange.innerHTML = rows.records[i].orderbuy;

        bidExchange.style.cursor = "pointer";
        bidExchange.addEventListener("click", function () {
            gotoPage('menu', "orders", { "userName": getParameterByName("userName"), "ref": rows.records[i].orderbuy });
        });

        divCnt5.appendChild(bidExchange);
        div5.appendChild(divCnt5);

        askExchange.disabled = true;
        askExchange.setAttribute("id", "askExchange" + index);
        askExchange.innerHTML = rows.records[i].ordersell;

        askExchange.style.cursor = "pointer";
        askExchange.addEventListener("click", function () {
            gotoPage('menu', "orders", { "userName": getParameterByName("userName"), "ref": rows.records[i].ordersell });
        });

        divCnt6.appendChild(askExchange);
        div6.appendChild(divCnt6);

        qtyExchange.disabled = true;
        qtyExchange.setAttribute("id", "qtyExchange" + index);
        qtyExchange.innerHTML = rows.records[i].qty.formatted;
        divCnt7.appendChild(qtyExchange);
        div7.appendChild(divCnt7);

        priceExchange.disabled = true;
        priceExchange.setAttribute("id", "priceExchange" + index);
        priceExchange.innerHTML = rows.records[i].price.formatted;
        divCnt8.appendChild(priceExchange);
        div8.appendChild(divCnt8);

        totalExchange.disabled = true;
        totalExchange.setAttribute("id", "totalExchange" + index);
        totalExchange.innerHTML = rows.records[i].total.formatted;
        divCnt9.appendChild(totalExchange);
        div9.appendChild(divCnt9);

        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(div3);
        divContent.appendChild(div4);
        divContent.appendChild(div5);
        divContent.appendChild(div6);
        divContent.appendChild(div7);
        divContent.appendChild(div8);
        divContent.appendChild(div9);
        divContent.style.display = "table";
        divContent.style.width = "94%";

        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 = "94%";

        rowCurrencie.appendChild(divContent);
    }
}

function LoadPairs(sessionid, order, offset, numofrec) {
    var req = {};
    req.sessionid = sessionid;
    req.order = order;
    req.offset = offset;
    req.numofrec = numofrec;

    callWS("GET", "pairs/list", req, respuesta);
    function respuesta(status, rsp) {
        let resp = JSON.parse(rsp);
        var pairs = document.getElementById("pairFilter");
        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 pares definidos";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        currencies.appendChild(op);
                    } else {
                        op.text = resp.records[i].dsc;
                        op.value = resp.records[i].id;
                        pairs.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 pares"
            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);*/
        }
    }
}