//Variables globales
var sessionId = sessionStorage.getItem("sessionId");
var deleteCityId;
var editedCity = {};
function blockOpt(ele){
    var id = ele.getAttribute("id");
    var select = document.getElementById(id);
    var val = "";
    //Edición
    var parts = id.split("/");
    if(parts.length == 2){
        if(parts[0] == "currencyBase"){
            val = document.getElementById("currencyRef/"+parts[1]);
        }else if(parts[0] == "currencyRef"){
            val = document.getElementById("currencyBase/"+parts[1]);
        }
    }else{
        if(select.getAttribute("id") == "baseCurrencyId"){
            val = document.getElementById("refCurrencyId");
        }else if(select.getAttribute("id") == "refCurrencyId"){
            val = document.getElementById("baseCurrencyId");
        }
    }
    var opts = val.options;
    for(var i=0;i<opts.length;i++){
        opts[i].removeAttribute("disabled");
        if(ele.value !== ""){
            if(opts[i].getAttribute("value") == ele.value){
                opts[i].setAttribute("disabled","");
            }
        }
    }
}
window.onload = function(){
    initApp();
    
    loadCountries('', 1, 0, 1000, sessionId);
    
    var filter = document.getElementById("search").value;
    if(filter == null || filter == undefined){
        filter  = '';
    }
    
    //Moneda base
    document.getElementById("baseCurrencyId").addEventListener('change', function(){
        blockOpt(this);
    });
    //Moneda referencia
    document.getElementById("baseCurrencyId").addEventListener('change', function(){
        blockOpt(this);
    });
    
    // Ordenamiento de elementos
    document.getElementById("orderBy").addEventListener("change", function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        loadList(filter, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    
    //Cerrar modal
    document.getElementById("closeModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
    //Cancelar modal
    document.getElementById("buttonCancelModal").addEventListener("click", function(){
        var modal = document.getElementById("myModal");
         modal.style.display = "none";
    });
    
    //Borrar elemento
    document.getElementById("buttonAceptModal").addEventListener("click", function(){
        deleteElement();
    });
    
    //Guardar estado
    document.getElementById("iconAddCity").addEventListener('click', function (event) {
        var msg = document.getElementById("messageApi"); 
        var status = document.getElementById("swichUserAdd");
        var pmstatus = 0;
        if(status.classList.contains("active")){
            pmstatus = 1;
        } else {
            pmstatus = 0;
        }      
        if (this.dataset.privilegeCreate == "1"){
            updateElement(0, document.getElementById("baseCurrencyId").value, document.getElementById("refCurrencyId").value,pmstatus);
        }else{
            msg.innerHTML = "No posee privilegios para crear un par";
            msg.style.display="block";
            msg.classList.add("msgError");
            setTimeout(function() {
                msg.classList.remove("msgError");
                msg.style.display="none";
            }, 3000);
        }
    });
    
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        var filter = this.value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        loadList(filter, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        var filter = this.value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        if(e.keyCode==13)loadList(filter, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    document.getElementById("iconSearch").addEventListener("click",function(){
        var filter = document.getElementById("search").value;
        if(filter == null || filter == undefined){
            filter  = '';
        }
        loadList(filter, document.getElementById("orderBy").value, 0, 10, sessionId);
    });
    
    
    //Swich de status del agregar moneda
    document.getElementById("swichUserAdd").addEventListener("click",function(){
        if(this.classList.contains("active")){
            this.classList.remove("active");
            this.firstElementChild.classList.remove("balActive");
        }else{
            this.classList.add("active");
            this.firstElementChild.classList.add("balActive");
        } 
    });
    
    /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
}



function loadCountries(filter, order, offset, numofrec, sessionid){
    var par = {};
    //Se pasa el document.getElementById("search").value por el parametro filter.
    par.filter = filter;
    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", "currencies/list", par, respCountries);
    
    function respCountries(status, rsp){
        let currencies = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                console.log(currencies);
                currlist = currencies.records;
                //Listado de moneda base
                var currenciesList = document.getElementById("baseCurrencyId");
                //listado moneda ref
                var currenciesListRef = document.getElementById("refCurrencyId");
                for (let i=0; i<currencies.records.length; i++){
                    var op = document.createElement("option");
                    op.style.textIndent = "5px";
                    
                    if(currencies.records.length == 0){
                        op.text= "No hay monedas definidas";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        currenciesList.appendChild(op);
                        var op2 = op.cloneNode(true);
                        currenciesListRef.appendChild(op2);
                    } else {
                        if(currencies.records[i].status.id == 1){
                            op.text= currencies.records[i].symbol;
                            op.value = currencies.records[i].id;
                            currenciesList.appendChild(op);
                            var op2 = op.cloneNode(true);
                            currenciesListRef.appendChild(op2);
                        }
                    }
                }
                loadList(filter, 1, 0, 10, sessionId);
                //loadList(filter, 1, 0, 10, sessionId);
                break;
            case 400:
                /*msg.innerHTML=countries.msg;
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");   
                    msg.style.display="none";
                }, 100000);
                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=countries.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
var currlist = [];
function loadList(filter, order, offset, numofrec, sessionid){
    var par = {};
    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;
    //llamamos al servicio
    callWS("GET", "pairs/list", par, respList);
    
    //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.privileges.create == false || currencies.privileges.create == "false"){
                    document.getElementById("iconAddCity").dataset.privilegeCreate = "0";
                } else {
                    document.getElementById("iconAddCity").dataset.privilegeCreate = "1";
                }
                console.log(currencies);
                if (currencies.numofrecords === 0){
                    /*Blanquear tabla*/
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noCurrencieDefine");
                    if (nodeNoDelete ){
                        nodeNoDelete.children[0].innerHTML = ""; 
                        nodeNoDelete.style.display="none";
                    }
                    var table = document.getElementById("bodyTableCountries");
                    table.innerHTML = "";
                    /*if(nodeClone!==undefined && nodeClone!==null){
                        table.appendChild(nodeClone);
                    }*/
                    document.getElementById("noCurrencieDefine").style.display = "block";
                    document.getElementById("msgInTable").innerHTML = "No Posee pares de intercambio definidas";
                    document.getElementById("paginator").style.display = "none";
                }else{
                    if(currencies.numofrecords <= 10){
                        document.getElementById("paginator").style.display= "none";    
                    } else {
                        document.getElementById("paginator").style.display= ""; 
                        drawPags(currencies.numofrecords, "numbersPaginator");
                    }
                    document.getElementById("noCurrencieDefine").style.display = "none";
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noCurrencieDefine");
                    if (nodeNoDelete ){
                        nodeNoDelete.children[0].innerHTML = ""; 
                        nodeNoDelete.style.display="none";
                    }
                    
                   var table = document.getElementById("bodyTableCountries");
                    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";
                }, 100000);
                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:
                    msg.innerHTML="No posee privilegios para ver pares";
                    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 Interno";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError"); 
                    msg.style.display="none";
                }, 3000);
                console.log(currencies);
                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);
        }
    }
}

//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=10;
    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.getAttribute("data-page");
    }
    console.log(pageInPaginator);
    var rowCurrencie = document.getElementById("bodyTableCountries");
    rowCurrencie.innerHTML = "";
    var filas;
    if (data.numofrecords > 10){
        filas = parseInt(data.numofrecords) - ((parseInt(pageInPaginator) - 1) * 10);
        if(filas > 10){
            filas = 10;
        }
    } else {
        filas = data.numofrecords
    }
    //type 0 = impar, 1 = par
    let type = 0;
    let dataC = data.records;
    console.log(dataC);
    console.log(filas);
    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;
        }
        
        var divcell = document.createElement("div");
        divcell.classList.add("divCellCnt");
        var selbase = document.createElement("select");
        selbase.classList.add("inputRow","selectOrderBy");
        selbase.id = "currencyBase/"+dataC[i].id;
        selbase.setAttribute("sym",dataC[i].refcurrency.symbol);
        selbase.innerHTML = makeListCurrencies(currlist,dataC[i].refcurrency.id,dataC[i].currency.id);
        //Moneda base
        selbase.addEventListener('change', function(){
            blockOpt(this);
        });
        divcell.appendChild(selbase);
        
        var divcellr = document.createElement("div");
        divcellr.classList.add("divCellCnt");
            var selref = document.createElement("select");
            selref.classList.add("inputRow","selectOrderBy");
            selref.setAttribute("sym",dataC[i].currency.symbol);
            selref.id = "currencyRef/"+dataC[i].id;
            selref.innerHTML = makeListCurrencies(currlist,dataC[i].currency.id,dataC[i].refcurrency.id);
            selref.addEventListener('change', function(){
                blockOpt(this);
            });
        divcellr.appendChild(selref);
        
        var act, inact = "";
        if(dataC[i].status.id==1){
            act = "selected";
        }else if(dataC[i].status.id==0){
            inact = "selected";
        }
        
        /***CREAR SWITCH***/
        var divCellSwch = document.createElement("div");
        divCellSwch.classList.add("tableCell");
        divCellSwch.style.width ="50px";
        var cell,cont,swichBg,swichBal;
        cell = document.createElement("DIV"); cell.classList.add("switchCell");
            cont = document.createElement("DIV"); cont.classList.add("switchCont");
                swichBg = document.createElement("DIV"); swichBg.classList.add("switch");
                swichBg.setAttribute("id", "status/"+dataC[i].id);
                swichBg.style.pointerEvents = "none";
                swichBg.style.cursor = "pointer";
                swichBal = document.createElement("DIV"); swichBal.classList.add("switchBal");
                if(data.records[i].status.id == 1){
                    swichBg.classList.add("active");
                    swichBal.classList.add("balActive");
                }
                swichBg.appendChild(swichBal);
                if( !(data.privileges.update == false || data.privileges.update == "false")){
                    swichBg.addEventListener("click", function(){
                        if(this.classList.contains("active")){
                            this.classList.remove("active");
                            this.firstElementChild.classList.remove("balActive");
                        }else{
                            this.classList.add("active");
                            this.firstElementChild.classList.add("balActive");
                        }
                        /*
                        var idpair = (this.id).split("/")[1];
                        pair = {
                            basecurrency: document.getElementById("currencyBase/"+idpair).value,
                            refcurrency: document.getElementById("currencyRef/"+idpair).value,
                            status: document.getElementById("status/"+idpair).value
                        };
                        updateElement(idpair, pair.basecurrency, pair.refcurrency, pair.status);*/
                    });
                }else{
                    swichBg.addEventListener("click", function(){
                        msg.innerHTML="No posee los privilegios para actualizar pares.";
                        msg.classList.add("msgError");
                        msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("msgError");
                            msg.style.display="none";
                        }, 3000);
                    });
                    
                }
            cont.appendChild(swichBg);
        cell.appendChild(cont);
        divCellSwch.appendChild(cell);
        
        tableLine.innerHTML = `<div class="cell1" style="width: 15%;">
                                </div>
                                <div class="cell1" style="width: 37.5%;">
                                </div>
                                <div class="cell1" style="width: 37.5%;">
                                </div>
                                <div class="cell1" style="width: 10%;">
                                    <div class="divCellCnt countriesicons" id="countriesIcons/${dataC[i].id}">
                                        <a id="edit/${dataC[i].id}"><i class="fas fa-edit"></i></a>
                                        <a id="delete/${dataC[i].id}"><i class="fas fa-trash-alt"></i></a>
                                    </div>
                                    <div class="divCellCnt countriesicons edit nShow" id="countriesIconsEdit/${dataC[i].id}">
                                        <a id="editConfirm/${dataC[i].id}"><i class="fas fa-check-circle"></i></a>
                                        <a id="editClose/${dataC[i].id}"><i class="far fa-times-circle"></i></a>
                                    </div>
                                </div>`;
        
        
        tableLine.children[0].appendChild(divCellSwch);
        tableLine.children[1].appendChild(divcell);
        tableLine.children[2].appendChild(divcellr);
        rowCurrencie.appendChild(tableLine);
    }
    document.querySelectorAll('[id^="edit/"]').forEach(function (element) {
        if(!(data.privileges.update == false || data.privileges.update == "false")){
            element.addEventListener('click', function (event) {
            var idpair = (this.id).split("/")[1];
            cleanAll();
            
            document.getElementById("countriesIcons/"+idpair).classList.add("nShow");
            document.getElementById("countriesIconsEdit/"+idpair).classList.remove("nShow");
            document.getElementById("line/"+idpair).classList.add("editLine");
            document.getElementById("currencyBase/"+idpair).disabled = false;
            document.getElementById("currencyRef/"+idpair).disabled = false;
            var status = document.getElementById("status/"+idpair);
            status.style.pointerEvents = "";
            document.getElementById("currencyBase/"+idpair).focus();
        });
        }else{
            var msg = document.getElementById("messageApi");
            element.addEventListener("click", function(){
                var msg = document.getElementById("messageApi");
                msg.innerHTML="No posee los privilegios para actualizar pares de intercambio.";
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
            });
        }
    });
    document.querySelectorAll('[id^="editClose/"]').forEach(function (element) {
        element.addEventListener('click', function (event) {
            var idpair = (this.id).split("/")[1];
            document.getElementById("countriesIcons/"+idpair).classList.remove("nShow");
            document.getElementById("countriesIconsEdit/"+idpair).classList.add("nShow");
            document.getElementById("line/"+idpair).classList.remove("editLine");
            document.getElementById("currencyBase/"+idpair).disabled = true;
            document.getElementById("currencyRef/"+idpair).disabled = true;
            var status = document.getElementById("status/"+idpair);
            status.style.pointerEvents = "none";
            var par = {};
            par.id = idpair;
            par.sessionid = sessionId;
            //llamamos al servicio
            callWS("GET", "pairs/entry", par, respList);
            
            function respList(status, rsp){
                let city = JSON.parse(rsp);
                switch(status){
                    case 200:
                        console.log(city);
                        document.getElementById("currencyBase/"+idpair).value = city.entry.refcurrency.id;
                        document.getElementById("currencyRef/"+idpair).value = city.entry.currency.id;
                        //document.getElementById("status/"+idpair).value = city.entry.status.id;
                    break;
                }
            }
            
        });
    });
    document.querySelectorAll('[id^="editConfirm/"]').forEach(function (element) {
        element.addEventListener('click', function (event) {
            var idpair = (this.id).split("/")[1];
            var status = document.getElementById("status/"+idpair);
            var pmstatus = 0;
            if(status.classList.contains("active")){
                pmstatus = 1;
            } else {
                pmstatus = 0;
            }  
            pair = {
                basecurrency: document.getElementById("currencyBase/"+idpair).value,
                refcurrency: document.getElementById("currencyRef/"+idpair).value,
                status: pmstatus
            };
            updateElement(idpair, pair.basecurrency, pair.refcurrency, pair.status);
        });
    });
    document.querySelectorAll('[id^="delete/"]').forEach(function (element) {
        if(!(data.privileges.delete == false || data.privileges.delete == "false")){
            element.addEventListener('click', function (event) {
                var id= (this.id).split("/")[1];
                deleteCityId=id;
                document.getElementById("countryDelete").innerText = document.getElementById("currencyBase/"+id).getAttribute("sym")+"/"+document.getElementById("currencyRef/"+id).getAttribute("sym");
                var modal = document.getElementById("myModal");
                modal.style.display = "block";
            });
        }else{
            element.addEventListener("click", function(){
                var msg = document.getElementById("messageApi");
                msg.innerHTML="No posee los privilegios para eliminar pares de intercambio";
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
            });
            
        }
    });
}

function makeListCurrencies(arr,id,dis){
    var listOp = '';
    var data;
    for(var i=0;i<arr.length;i++){
        data = arr[i];
        var disatr = "";
        var sel = "";
        if(dis !== null && dis !== undefined && dis !== "" && dis == data.id){
            disatr = "disabled";
        }
        if(id !== null && id !== undefined && id !== "" && id == data.id){
            sel = "selected";
        }
        
        listOp += `<option ${disatr} value="${data.id}" ${sel}>${data.symbol}</option>`;
    }
    return listOp;
}

//Hace que solo este disponible 1 linea para editar    
function cleanAll(){
    document.querySelectorAll('[id^="countriesIcons/"]').forEach(function (element) {
        element.classList.remove("nShow");
    });
    document.querySelectorAll('[id^="countriesIconsEdit/"]').forEach(function (element) {
        element.classList.add("nShow");
    });
    document.querySelectorAll('[id^="line/"]').forEach(function (element) {
        element.classList.remove("editLine");
    });
    document.querySelectorAll('[id^="countryName/"]').forEach(function (element) {
        element.disabled = true;
    });
}


function removeOptions(selectElement) {
   var i, L = selectElement.options.length - 1;
   for(i = L; i >= 0; i--) {
      selectElement.remove(i);
   }
}

function updateElement(id,basecurrency,refcurrency,status){
    var par = {};
    par.id= parseInt(id);
    par.basecurrency = basecurrency;
    par.refcurrency = refcurrency;
    par.status=status;
    par.sessionid = sessionId;
    console.log(par);
    callWS("GET", "pairs/update", par, rspUpdate);
    
    function rspUpdate(status, rsp){
    var respuesta = JSON.parse(rsp);
    var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                //CORREGIR ESTA VAINA
                if(id !== 0){
                    //Es una actualizacion
                    document.getElementById("countriesIcons/"+id).classList.remove("nShow");
                    document.getElementById("countriesIconsEdit/"+id).classList.add("nShow");
                    document.getElementById("line/"+id).classList.remove("editLine");
                    document.getElementById("currencyBase/"+id).disabled = true;
                    document.getElementById("currencyRef/"+id).disabled = true;
                    var status = document.getElementById("status/"+id);
                    status.style.pointerEvents = "none";
                    msg.innerHTML="Par actualizado con éxito"
                    msg.classList.add("goodEdit");
                    msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("goodEdit");
                            msg.style.display="none";
                            //Se desmarca la pagina anterior
                            var pSel = document.getElementsByClassName("pSelect");
                            if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
                            //Colocamos la pagina 1
                            var page1 = document.getElementsByClassName("pages")[0];
                            if(page1 != undefined){
                                page1.classList.add("pSelect");
                            }
                        }, 3000);
                }else{
                    //Es un nuevo elemento
                    document.getElementById('baseCurrencyId').value = '';
                    document.getElementById('refCurrencyId').value = '';
                    var status = undefined;status = document.getElementById("swichUserAdd");
                    status.classList.remove("active");
                    status.children[0].classList.remove("balActive");
                    document.getElementById('swichUserAdd').value = '';
                    msg.innerHTML="Par creado con éxito"
                    msg.classList.add("goodEdit");
                    msg.style.display="block";
                        setTimeout(function() {
                            msg.classList.remove("goodEdit");
                            msg.style.display="none";
                            //Se desmarca la pagina anterior
                            var pSel = document.getElementsByClassName("pSelect");
                            if(pSel.length>0)pSel[0].classList.remove("pSelect");
        
                            //Colocamos la pagina 1
                            var page1 = document.getElementsByClassName("pages")[0];
                            if(page1 != undefined){
                                page1.classList.add("pSelect");
                            }
                            //Se repinta el listado desde el offset seleccionado
                            var order = document.getElementById("orderBy").value;
                            loadList(document.getElementById("search").value, order, 0, 10, sessionId);
                        }, 3000);
                }
            break;
            case 204://Registro sin modificar
                console.log(respuesta)
            break;
            case 400://Registro sin modificar
                msg.innerHTML="Todos los campos son requeridos"
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
                break;
            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 402:
                msg.innerHTML="Ya existe el par."
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                //Se repinta el listado desde el offset seleccionado
                            var order = document.getElementById("orderBy").value;
                            loadList(document.getElementById("search").value, order, 0, 10, sessionId);
            break;
            case 403:
                    msg.innerHTML="No posee los privilegios para actualizar pares de intercambio."
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                    break;
            case 405:
                msg.innerHTML=respuesta.msg
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                //Se repinta el listado desde el offset seleccionado
                var order = document.getElementById("orderBy").value;
                loadList(document.getElementById("search").value, order, 0, 10, sessionId);
                break;
            case 500:
                msg.innerHTML="Error al actualizar pares de intercambio, intente nuevamente."
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                        
                    }, 3000);
                //Se repinta el listado desde el offset seleccionado
                            var order = document.getElementById("orderBy").value;
                            loadList(document.getElementById("search").value, order, 0, 10, sessionId);
            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 deleteElement(){
    var par = {};
    par.id= parseInt(deleteCityId);
    par.sessionid = sessionId;
    callWS("GET", "pairs/delete", par, rspDelete);
    return 0;
}
function rspDelete(status, rsp){
    var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                var respuesta = JSON.parse(rsp);
                console.log(respuesta);
                document.getElementById("myModal").style.display = "none";
                msg.innerHTML="Par eliminado con éxito";
                msg.classList.add("goodEdit");
                msg.style.display="block";
                
                //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");
                    }
                    
                    var filter = document.getElementById("search").value;
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    //Se repinta el listado desde el offset seleccionado
                    var order = document.getElementById("orderBy").value;
                    loadList(filter, order, 0, 10, sessionId);
                
                setTimeout(function() {
                    msg.classList.remove("goodEdit");
                    msg.style.display="none";
                }, 3000);

            break;
            case 204://Registro sin modificar
                var respuesta = JSON.parse(rsp);
                console.log(respuesta)
                break;
            break;
            case 304:
                document.getElementById("myModal").style.display = "none";
                msg.innerHTML="Existen dependencias que no permiten eliminar este par"
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
                break;
            case 400://Registro sin modificar
                var respuesta = JSON.parse(rsp);
                console.log(respuesta)
                break;
            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 privilegios para realizar esta acción."
                    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 interno, intente nuevamente."
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
            break;
            default:
                var respuesta = JSON.parse(rsp);
                msg.innerHTML= respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
        }
}