//Variables globales
var sessionId = sessionStorage.getItem("sessionId");
var deleteCityId;
var editedCity = {};

window.onload = function(){
    initApp();
    
    loadCountries('', 1, 0, 1000, sessionId);
    
    var filter = document.getElementById("search").value;
    if(filter == null || filter == undefined){
        filter  = '';
    }
    
    //Obtener estados
    document.getElementById("addCountryId").addEventListener('change', function(){
        var filter = this.options[this.selectedIndex].text;
        if(filter != ''){
            loadRegions(filter, 1, 0, 1000, sessionId);
        }
    });
    
    // 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"); 
        if (this.dataset.privilegeCreate == "1"){
            updateElement(0, document.getElementById("addRegionId").value, document.getElementById("addCityName").value);
        }else{
            msg.innerHTML = "No posee privilegios para crear una ciudad";
            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);
    });
    
    /*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", "countries/list", par, respCountries);
    
    function respCountries(status, rsp){
        let countries = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                console.log(countries);
                var countriesList = document.getElementById("addCountryId");
                for (let i=0; i<countries.records.length; i++){
                    var op = document.createElement("option");
                    if(countries.records.length == 0){
                        op.text= "No hay paises definidos";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        countriesList.appendChild(op);
                    } else {
                        if(countries.records[i].status.id == 1){
                            op.text= countries.records[i].dsc;
                            op.value = countries.records[i].id;
                            countriesList.appendChild(op);
                        }
                    }
                }
                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
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", "cities/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 Ciudades 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 Ciudades";
                    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);
                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;
        }
        tableLine.innerHTML = `<div class="cell1" style="width: 30%;">
                                    <div class="divCellCnt">
                                       <select class="inputRow selectOrderBy" id="countryName/${dataC[i].country.id}/${dataC[i].id}" disabled>
                                            ${makeListCountry(dataC[i])}
                                       </select>
                                    </div>
                                </div>
                                <div class="cell1" style="width: 30%;">
                                    <div class="divCellCnt">
                                       <select class="inputRow selectOrderBy" id="countryName/${dataC[i].state.id}/${dataC[i].id}" disabled>
                                            ${makeListRegions(dataC[i].state)}
                                       </select>
                                    </div>
                                </div>
                                <div class="cell1" style="width: 30%;">
                                    <div class="divCellCnt">
                                       <input class="inputRow" value="${dataC[i].dsc}" id="countryName/${dataC[i].id}" disabled>
                                    </div>
                                </div>
                                <div class="cell1" style="width: 10%;">
                                    <div class="divCellCnt countriesicons" id="countriesIcons/${dataC[i].id}">
                                        <a id="edit/${dataC[i].id}/${dataC[i].country.id}/${dataC[i].state.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}/${dataC[i].country.id}/${dataC[i].state.id}"><i class="fas fa-check-circle"></i></a>
                                        <a id="editClose/${dataC[i].id}/${dataC[i].country.id}/${dataC[i].state.id}"><i class="far fa-times-circle"></i></a>
                                    </div>
                                </div>`;
        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 idcity = (this.id).split("/")[1];
            var idcountry = (this.id).split("/")[2];
            var idregion = (this.id).split("/")[3];
            console.log(this.id);
            cleanAll();
            
            document.getElementById("countriesIcons/"+idcity).classList.add("nShow");
            document.getElementById("countriesIconsEdit/"+idcity).classList.remove("nShow");
            document.getElementById("line/"+idcity).classList.add("editLine");
            document.getElementById("countryName/"+idcountry+"/"+idcity).disabled = false;
            //Consultamos los estados del pais a editar
            var countryname = document.getElementById("countryName/"+idcountry+"/"+idcity).options[document.getElementById("countryName/"+idcountry+"/"+idcity).selectedIndex].text;
            
            removeOptions(document.getElementById("countryName/"+idregion+"/"+idcity));
            
            document.getElementById("countryName/"+idcountry+"/"+idcity).addEventListener('change', function(){
                var countryname = document.getElementById("countryName/"+idcountry+"/"+idcity).options[document.getElementById("countryName/"+idcountry+"/"+idcity).selectedIndex].text;
                par.filter = countryname;
                par.order = 1;
                par.offset = 0;
                par.numofrec = 1000;
                par.sessionid = sessionId;
                //Especifico el servicio, los parametros y la funcion de retorno del listado listado
                callWS("GET", "regions/list", par, respRegions);
                
            })
            
            var par = {};
            //Se pasa el document.getElementById("search").value por el parametro filter.
            par.filter = countryname;
            par.order = 1;
            par.offset = 0;
            par.numofrec = 1000;
            par.sessionid = sessionId;
            //Especifico el servicio, los parametros y la funcion de retorno del listado listado
            callWS("GET", "regions/list", par, respRegions);
    
            function respRegions(status, rsp){
                let regions = JSON.parse(rsp);
                var msg = document.getElementById("messageApi");
                switch(status){
                    case 200:
                        console.log(regions);
                        var regionsList = document.getElementById("countryName/"+idregion+"/"+idcity);
                        //Limpiamos las regiones
                        removeOptions(regionsList);
                        if(regions.records == null){
                            var op = document.createElement("option");
                            op.text= 'Estado';
                            op.disabled = true;
                            op.selected = true;
                            op.value = '';
                            regionsList.appendChild(op);
                            
                            op = document.createElement("option");
                            op.text= "No hay Estados definidos";
                            op.disabled = true;
                            op.value = "";
                            op.selected = false;
                            regionsList.appendChild(op);
                        }else{
                            for (let i=0; i<regions.records.length; i++){
                                if(i == 0){
                                    var op = document.createElement("option");
                                    op.text= 'Estado';
                                    op.disabled = true;
                                    op.selected = true;
                                    op.value = '';
                                    regionsList.appendChild(op);
                                }
                                var op = document.createElement("option");
                                if(regions.records[i].status.id == 1){
                                    op.text= regions.records[i].dsc;
                                    op.value = regions.records[i].id;
                                    op.selected = idregion == regions.records[i].id ? true : false;
                                    regionsList.appendChild(op);
                                }
                            }
                        }
                    break;
                }
            }
                    
            document.getElementById("countryName/"+idregion+"/"+idcity).disabled = false;
            document.getElementById("countryName/"+idcity).disabled = false;
            document.getElementById("countryName/"+idcity).focus();
        });
        }else{
            var msg = document.getElementById("messageApi");
            element.addEventListener("click", function(){
                var msg = document.getElementById("messageApi");
                msg.innerHTML="No posee los privilegios para actualizar ciudades.";
                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 id = (this.id).split("/")[1];
            var idcountry = (this.id).split("/")[2];
            var idregion = (this.id).split("/")[3];
            document.getElementById("countriesIcons/"+id).classList.remove("nShow");
            document.getElementById("countriesIconsEdit/"+id).classList.add("nShow");
            document.getElementById("line/"+id).classList.remove("editLine");
            document.getElementById("countryName/"+id).disabled = true;
            
            var i, L = document.getElementById("countryName/"+idcountry+"/"+id).options.length - 1;
            var countriesList = document.getElementById("countryName/"+idcountry+"/"+id);
            for(i = L; i >= 0; i--) {
                if(countriesList.options[i].value == idcountry){
                    countriesList.options[i].selected = true;
                }
            }
            
            document.getElementById("countryName/"+idcountry+"/"+id).disabled = true;
            var par = {};
            par.id = id;
            par.sessionid = sessionId;
            //llamamos al servicio
            callWS("GET", "cities/entry", par, respList);
            
            function respList(status, rsp){
                let city = JSON.parse(rsp);
                switch(status){
                    case 200:
                        console.log(city);
                        var regionsList = document.getElementById("countryName/"+idregion+"/"+id);
                        //Limpiamos las regiones
                        removeOptions(regionsList);
                        var op = document.createElement("option");
                        op.text= city.entry.region.dsc;
                        op.selected = true;
                        op.value = city.entry.region.id;
                        regionsList.appendChild(op);
                    break;
                }
            }
            
            document.getElementById("countryName/"+idregion+"/"+id).disabled = true;
        });
    });
    document.querySelectorAll('[id^="editConfirm/"]').forEach(function (element) {
        element.addEventListener('click', function (event) {
            var id= (this.id).split("/")[1];
            var idcountry = (this.id).split("/")[2];
            var idregion = (this.id).split("/")[3];
            editedRegion = {
                cityid: id,
                countryid: idcountry,
                regionid: idregion
            };
            updateElement(id, document.getElementById("countryName/"+idregion+"/"+id).value, document.getElementById("countryName/"+id).value);
        });
    });
    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("countryName/"+id).value;
                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 ciudades";
                msg.classList.add("msgError");
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError");
                    msg.style.display="none";
                }, 3000);
            });
            
        }
    });
}

function makeListCountry(data){
    var listOp = '';
    var listCountries = document.getElementById('addCountryId');
    for (let j=0; j<listCountries.options.length; j++){
        var op = document.createElement("option");
        if(listCountries.options.length == 0){
            listOp += `<option value="" disabled selected>No hay paises definidos</option>`;
        } else {
            listOp += `<option value="${listCountries.options[j].value}" ${data.country.id == listCountries.options[j].value ? 'selected' : ''}>${listCountries.options[j].text}</option>`;
        }
    }
    
    return listOp;
}

function makeListRegions(data){
    var listOp = '';
    listOp += `<option value="${data.id}" selected>${data.dsc}</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 loadRegions(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", "regions/list", par, respRegions);
    
    function respRegions(status, rsp){
        let regions = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                console.log(regions);
                var regionsList = document.getElementById("addRegionId");
                //Limpiamos las regiones
                removeOptions(regionsList);
                if(regions.records == null){
                    var op = document.createElement("option");
                    op.text= 'Estado';
                    op.disabled = true;
                    op.selected = true;
                    op.value = '';
                    regionsList.appendChild(op);
                    
                    op = document.createElement("option");
                    op.text= "No hay Estados definidos";
                    op.disabled = true;
                    op.value = "";
                    op.selected = false;
                    regionsList.appendChild(op);
                }else{
                    for (let i=0; i<regions.records.length; i++){
                        if(i == 0){
                            var op = document.createElement("option");
                            op.text= 'Estado';
                            op.disabled = true;
                            op.selected = true;
                            op.value = '';
                            regionsList.appendChild(op);
                        }
                        var op = document.createElement("option");
                        if(regions.records[i].status.id == 1){
                            op.text= regions.records[i].dsc;
                            op.value = regions.records[i].id;
                            regionsList.appendChild(op);
                        }
                    }
                }
                
                //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);*/
        }
    }
}

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

function updateElement(id,regionid,dsc){
    var par = {};
    par.id= parseInt(id);
    par.dsc=dsc;
    par.regionid = regionid;
    par.status=1;
    par.sessionid = sessionId;
    callWS("GET", "cities/update", par, rspUpdate);
    
    function rspUpdate(status, rsp){
    var respuesta = JSON.parse(rsp);
    var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                
                if(id !== 0){
                    //Es una actualizacion
                    document.getElementById("countriesIcons/"+editedRegion.cityid).classList.remove("nShow");
                    document.getElementById("countriesIconsEdit/"+editedRegion.cityid).classList.add("nShow");
                    document.getElementById("line/"+editedRegion.cityid).classList.remove("editLine");
                    document.getElementById("countryName/"+editedRegion.cityid).disabled = true;
                    document.getElementById("countryName/"+editedRegion.countryid+"/"+editedRegion.cityid).disabled = true;
                    document.getElementById("countryName/"+editedRegion.regionid+"/"+editedRegion.cityid).disabled = true;
                    msg.innerHTML="Ciudad actualizada 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('addCountryId').value = '';
                    document.getElementById('addRegionId').value = '';
                    document.getElementById('addCityName').value = '';
                    msg.innerHTML="Ciudad creada 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 403:
                    msg.innerHTML="No posee los privilegios para actualizar Ciudades."
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
                    break;
            case 500:
                msg.innerHTML="Error al actualizar Ciudades, intente nuevamente."
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
            break;
            default:
                msg.innerHTML= respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
        }
    }
}

function deleteElement(){
    var par = {};
    par.id= parseInt(deleteCityId);
    par.sessionid = sessionId;
    callWS("GET", "cities/delete", par, rspDelete);
    return 0;
}
function rspDelete(status, rsp){
    var msg = document.getElementById("messageApi");
    var respuesta = JSON.parse(rsp);
        switch(status){
            case 200:
                console.log(respuesta);
                document.getElementById("myModal").style.display = "none";
                msg.innerHTML="Ciudad eliminada 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
                console.log(respuesta)
            break;
            case 400://Registro sin modificar
                console.log(respuesta)
            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:
                msg.innerHTML= respuesta.msg;
                msg.classList.add("msgError");
                msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");
                        msg.style.display="none";
                    }, 3000);
        }
}