//Variables globales
var sessionId = sessionStorage.getItem("sessionId");
var pagerNumber = 10;
var globalOffset = 0;
window.onload = function(){
    initApp();
    //loadListCurrencies();
    loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    setInterval(function(){
        console.log(globalOffset);
        loadList(document.getElementById("search").value, document.getElementById("orderBy").value, globalOffset, pagerNumber, sessionId, false);
    },45000);
    
    var selectOrderBy = document.getElementById("orderBy");
    selectOrderBy.addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("typeFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    document.getElementById("rangeFilter").addEventListener("change", function(){
        loadList(document.getElementById("search").value, selectOrderBy.value, 0, pagerNumber, sessionId);
    });
    //Asignar evento barra de busqueda
    document.getElementById("search").addEventListener("change",function(){
        loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });
    document.getElementById("search").addEventListener("keyup",function(e){
        if(e.keyCode==13)loadList(this.value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
    });

    //Crear
    document.getElementById("addData").addEventListener('click', function (event) {
        //document.getElementById("cancelM").parentElement.classList.add("noShow");
        var tagusers = document.getElementById("searchUser").parentElement;
        tagusers.classList.remove("disabledBox");
        tagusers.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
        tagusers.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
        var tags = document.getElementById("addTags").parentElement;
        tags.classList.remove("disabledBox");
        tags.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
        tags.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
        
        
        document.getElementById("cancelM").innerHTML = "CANCELAR";
        document.getElementById("aceptM").innerHTML = "ENVIAR";
        document.getElementById("modalcTit").innerHTML = "Nuevo Mensaje";
        document.getElementById("addDate").value = "";
        document.getElementById("addDescription").value = "";
        document.getElementById("depFilter").value = "";
        document.getElementById("addTags").value = "";
        document.getElementById("searchUser").setAttribute("userids","");
        document.getElementById("searchUser").value = "";
        //Etiquetas
        var tags = document.getElementById("modalconfir").getElementsByClassName("tag");
        for(var i=(tags.length-1);i>=0;i--){
            tags[i].parentElement.removeChild(tags[i]);
        }
        userEditId = 0;
        showModal("modalconfir");
    });
    document.getElementById("cancelM").addEventListener('click', function (event) {
        if(userEditId!==0)
            deleteMessage();
        else
            document.getElementById("modalconfir").style.display = "none";
    });
    document.getElementById("aceptM").addEventListener('click', function (event) {
        updateMessage();
        //transactionsUpdate();
    });
    /*//Detalles
    document.getElementById("addData1").addEventListener('click', function (event) {
            userEditId = 0;
            showModal();
    });
    */
    document.getElementById("cancelDet").addEventListener('click', function (event) {
        document.getElementById("modaldetails").style.display = "none";
    });
    /*funcion del ordenar**/
     
        var orderDirect = document.getElementById("orderDirect");
        if(orderDirect!==null){
            orderDirect.addEventListener("change",function(){
                document.getElementById("orderBy").dispatchEvent(new Event("change"));
            });
        }
        
    
    window.addEventListener("click", function(){ 
        var div=document.getElementById("searchResult");
        div.classList.add("noShow");
    });
    document.getElementById("sendEmail").addEventListener("click",function(){
        var box = this.children[0];
        if(box.classList.contains("fa-check-square")){
            box.classList.remove("fa-check-square");
            box.classList.add("fa-square");
        }else{
            box.classList.add("fa-check-square");
            box.classList.remove("fa-square");
        }
            
    });
    document.getElementById("sendSms").addEventListener("click",function(){
        var box = this.children[0];
        if(box.classList.contains("fa-check-square")){
            box.classList.remove("fa-check-square");
            box.classList.add("fa-square");
        }else{
            box.classList.add("fa-check-square");
            box.classList.remove("fa-square");
        }
            
    });
    tagLoad();
    loadDepartments("",1,0,999,sessionId);
    
}

function deleteMessage(){
    var par = {};
    par.id = userEditId;
    par.sessionid = sessionId;
    callWS("GET", "messages/delete", par, rspMessageDelete);
    return 0;
}
function rspMessageDelete(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            document.getElementById("modalconfir").style.display = "none";
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}

function updateMessage(){
    var date = document.getElementById("addDate").value;
    
    var emailVal = document.getElementById("searchUser").value;
    var emailVarr = emailVal.split(",");
    var users = document.getElementById("searchUser").getAttribute("userids");
    var cntuser = "";
    var arrayids = [];
    
    for(var i=0;i<emailVarr.length;i++){
        cntuser = users.split("&dv");
        for(var x=0;x<cntuser.length;x++){
            if(cntuser[x].split("&id")[0].trim() == emailVarr[i]){
                var exist = false;
                for(var y=0;y<arrayids.length;y++){
                    if(cntuser[x].split("&id")[1].trim()==arrayids[y]){
                        exist = true;
                    }
                }
                if(!exist)arrayids.push(cntuser[x].split("&id")[1]);
            }
        }
    }
    var realids = "";
    for(var i=0;i<arrayids.length;i++){
        if(realids=="")realids = arrayids[i];
        else realids = realids+"-"+arrayids[i];
    }
    
    
    var email = 0;//document.getElementById("addDescription").value ;
    var box = document.getElementById("sendEmail").children[0];
    if(box.classList.contains("fa-check-square")){
        email = 1;
    }
    var sms = 0;//document.getElementById("pairFilter1").value ;
    var box = document.getElementById("sendSms").children[0];
    if(box.classList.contains("fa-check-square")){
        sms = 1;
    }
    var tags = document.getElementById("addTags").value;
    var txt = document.getElementById("addDescription").value;
    var msg = document.getElementById("msgErrorC");
    
    var ref = document.getElementById("depFilter").value;
    
    if(date === "" || (users === "" && tags==="") || txt === "" || ref === ""){
        msg.innerText="Por favor complete todos los campos obligatorios. Al menos 1 destinatario, departamento, fecha y mensaje";
        msg.style.display="block";
        setTimeout(function() {
            msg.style.display="";
        }, 3000);
        return 0;
    }
    // Validamos que la fecha sea una valida
    let dateSticked = new Date('1950-12-12');
    let dateForm = new Date(date);
    
    if(dateSticked > dateForm){
        console.log('fallo 1');
        msg.innerText="Formato de fecha inválido.";
        msg.style.display="block";
        setTimeout(function() {
            msg.style.display="";
        }, 4000);
        return 0;
    }
    
    let dateForValid = dateformatted(date).replace('T',' ');
    
    if(!dateRegEx(dateForValid)){
        
        msg.innerText="Formato de fecha inválido.";
        msg.style.display="block";
        setTimeout(function() {
            msg.style.display="";
        }, 4000);
        return 0;
    }
    
    var par = {};
    par.id = userEditId;
    par.date = date.replace("T"," ");
    par.email = email;
    par.sms = sms;
    par.tags = tags;
    par.userids = realids;
    par.msg = txt;
    par.ref = ref;
    par.sessionid = sessionId;
    
    callWS("POST", "messages/update", par, rspMessageUpdate);
    return 0;
}
function rspMessageUpdate(status, rsp){
    var msg = document.getElementById("msgErrorC");
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            document.getElementById("modalconfir").style.display = "none";
            break;
        case 400:
            var rsp = JSON.parse(rsp);
            msg.innerText =rsp.msg;
            msg.style.display="block";
            setTimeout(function() {
                msg.style.display="";
            }, 3000);
            break;
        case 401:
            msg.innerText="Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.style.display="block";
            setTimeout(function() {
                msg.style.visibility="";
                myLogout();
            }, 4000);
        break;
        case 410:
            msg.innerText="El mensaje es muy largo para ser enviado por SMS. Limite 150 caracteres";
            msg.style.display="block";
            setTimeout(function() {
                msg.style.display="";
            }, 3000);
        break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            console.log(rsp);
    }
}




/***FUNCIONAMIENTO DE USUARIOS DESTINATARIOS LISTA**/
//BUSQUEDA INTELIGENTE
var cleared=null;
//document.getElementById("searchUser")
function myUsers(value){
    var par = {};
    par.filter = value;
    par.offset = 0;
    par.order = "1";
    par.numofrecords = 2000;
    par.sessionid = sessionId;
    callWS("GET", "appusers/list", par, rspUser);
    return 0;
}
function rspUser(status, rsp){
    switch(status){
        case 200:
           // console.log(JSON.parse(rsp));
            var resp=JSON.parse(rsp);
            var lista=document.getElementById("resultsC");
            var div=document.getElementById("searchResult");
            div.classList.remove("noShow");
            mySearchAddUser(lista,resp.records,resp.numofrecords);
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                msg.classList.add("msgError"); 
                msg.style.display="block";
                setTimeout(function() {
                    msg.classList.remove("msgError"); 
                    myLogout()
                    msg.style.display="none";
                }, 3000);
                break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            alert("Error 500 "+resSeller.msg);
            console.log(JSON.parse(rsp));
            break;
            default:
            //console.log(rsp);
    }
}
function mySearchAddUser(lista,data,num){
    lista.innerHTML = "";
    if(num===0){
      var line = document.createElement("li"); 
      line.innerHTML ='<span class="smallRsp">No tenemos registros que coincidan con su busqueda.</span>';
      lista.appendChild(line);
    }else{
        for(navLink of data){
            var line = document.createElement("li");
            line.classList.add("myNewLineUser");
            line.id="user-"+navLink.id;
            line.innerHTML ='<p class="nameResult"> '+navLink.usr+'</p>';
                lista.appendChild(line);
        }  
    }
    document.querySelectorAll('[class="myNewLineUser"]').forEach(function (element) {
        element.addEventListener('mousedown', function (event) {
            var id=element.id.split("-")[1];
            var email = element.children[0].innerHTML;
            var inputUser= document.getElementById("searchUser");
            if(id!==null && id!==undefined &&id!==""){
                if(inputUser.getAttribute("userids") !== "")
                    var ids = inputUser.getAttribute("userids")+"&dv"+(email+"&id"+id);
                else
                    var ids = email+"&id"+id;
                    
                inputUser.setAttribute("userids", ids) ;
            }
            var inputUser= document.getElementById("ubicartaginpt");
            inputUser.value = this.firstElementChild.innerHTML;
        });
        element.addEventListener('click', function (event) {
            setTimeout(function(){
                var inputUser= document.getElementById("ubicartaginpt");
                inputUser.value = "";
            },500);
        });
    });
}

function rspUserEntry(status, rsp){
    switch(status){
        case 200:
            console.log(JSON.parse(rsp));
            var resp=JSON.parse(rsp).entry;
            var inputUser= document.getElementById("searchUser");
            inputUser.value=resp.usr;
            userSelected=resp.id;
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}

//contador de tags para saber cuando se borró uno.
var lastTags=0;
function tagLoad(){
    // or just enhance all tag inputs on the page: 
    //Asignar api tag-master a campos input tipo tags
    [].forEach.call(document.querySelectorAll('input[type="tags"]'), tagsInput);
    
    //Espero a que se le asigne el formato de la api al campo 
    setTimeout(function(){
        if(document.getElementsByClassName("tagInptEle").length>0){
            var tagCnt = document.getElementsByClassName("tagInptEle");
            for(var i=0;i<tagCnt.length;i++){
                var tagsInpt = tagCnt[i].getElementsByTagName("input")[0];
                
                if(tagCnt[i].previousElementSibling.getAttribute("id")=="searchUser"){
                    tagsInpt.addEventListener("keyup", function(e){
                        if(this.value.length>0){
                            //if(this.value[0] !== "#")this.value = "#"+this.value;
                        }
                    });
                    
                    tagsInpt.setAttribute("id","ubicartaginpt");
                    tagsInpt.addEventListener("keyup", function(e){
                        if(this.value.length >= 3){
                            if(cleared !== null){
                                clearTimeout(cleared);
                            }
                            cleared= setTimeout(function(){ myUsers(document.getElementById("ubicartaginpt").value.replace("#","")); }, 1000);
                        }
                        //SI SE ESCRIBE EN EL CAMPO USUARIOS SE DESHABILITAN LOS TAGS
                        var opele = document.getElementById("ubicartaginpt2").parentElement.previousElementSibling.parentElement;
                        var tagcnt = this.parentElement;
                        if(this.value.length>0 || tagcnt.getElementsByClassName("tag").length>0){
                            if(!opele.classList.contains("disabledBox")){
                                opele.classList.add("disabledBox");
                                opele.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                                opele.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                            }
                        }else{
                            opele.classList.remove("disabledBox");
                            opele.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
                            opele.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
                        }
                        
                        if(e.keyCode == 46){
                            var users,ids;
                            var inpt = document.getElementById("searchUser");
                            var val = inpt.value;
                            users = inpt.getAttribute("usersE").split("&dv");
                            ids = inpt.getAttribute("userids").split("&dv");
                        }
                        
                    });
                }else{
                    tagsInpt.setAttribute("id","ubicartaginpt2");
                    tagsInpt.addEventListener("keyup", function(e){
                        if(this.value.length>0){
                            if(this.value[0] !== "#")this.value = "#"+this.value;
                        }
                        
                        //SI SE ESCRIBE EN EL CAMPO TAGS SE DESHABILITAN LOS USUARIOS (o si existen etiquetas de antes)
                        var opele = document.getElementById("ubicartaginpt").parentElement.previousElementSibling.parentElement;
                        var tagcnt = this.parentElement;
                        if(this.value.length>0 || tagcnt.getElementsByClassName("tag").length>0){
                            if(!opele.classList.contains("disabledBox")){
                                opele.classList.add("disabledBox");
                                opele.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                                opele.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                            }
                        }else{
                            opele.classList.remove("disabledBox");
                            opele.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
                            opele.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
                    }
                    });
                    
                }
                
            }
            
        }
    },800);
}
var tagsEntry = [];
function drawTags(tbl,rsp){
    if(rsp!==null&&rsp!==undefined){
        var rsp = rsp.split(" ");
        var tagsCnt = tbl.getElementsByClassName("tagInptEle")[0];
        var tagsInpt = tagsCnt.getElementsByTagName("input")[0];
        
        var span = tagsCnt.getElementsByTagName("span");
        if(span.length>0){
            
            
            //Blanquear etiquetas
            var clone = span[0];
            for(var x=0;x<span.length;x++){
                tagsCnt.removeChild(span[0]);
            }
            
            for(var i=0;i<rsp.length;i++){
                var nd = clone.cloneNode(true);
                nd.setAttribute("data-tag",rsp[i]);
                nd.innerHTML = rsp[i];
                tagsCnt.insertBefore(nd, tagsInpt);
            }
        }else{
            tagsInpt.value = rsp[0];
            tagsInpt.dispatchEvent(new Event('paste'));
            tagsEntry = rsp;
            setTimeout(function(){
                for(var i=1;i<tagsEntry.length;i++){
                    var nd = span[0].cloneNode(true);
                    nd.setAttribute("data-tag",tagsEntry[i]);
                    nd.innerHTML = tagsEntry[i];
                    tagsCnt.insertBefore(nd, tagsInpt);
                }
                tagsInpt.dispatchEvent(new Event('keydown'));
            },500);
        }
    }
}

//Función para cargar listado
function loadList(filter, order, offset, numofrec, sessionid,wait=true){
    var par = {};
    //var currencyid = document.getElementById("pairFilter").value;
    //Se pasa el document.getElementById("search").value por el parametro filter.
        if(filter !== "" && filter !== undefined && filter !== null)
        par.filter = filter;
        //if(currencyid !== "" && currencyid !== undefined && currencyid !== null)
        //par.currencyid = currencyid;
        var order = Math.abs(order);
        var dir = document.getElementById("orderDirect").value;
        if(dir=="desc")order="-"+order;
        par.order = order;
        par.offset = offset;
        par.numofrec = numofrec;
        par.type = document.getElementById("typeFilter").value;
        par.daterange = document.getElementById("rangeFilter").value;
        par.sessionid = sessionid;
        //Especifico el servicio, los parametros y la funcion de retorno del listado listado
        callWS("GET", "messages/list", par, respList,wait);
        return 0;
}
//Función para el retorno del listado listado
function respList(status, rsp){
            let currencies = JSON.parse(rsp);
            var msg = document.getElementById("msgErrorC");
            switch(status){
                case 200:
                    console.log(currencies);
                    let newnumofrec = parseInt(currencies.numofrecords);
                        if (currencies.numofrecords === 0){
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                            var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null){
                                table.appendChild(nodeClone);
                            }
                            /**-hasta aqui-**/
                            //document.getElementById("noCurrencieDefine").style.display = "block";
                            //document.getElementById("msgInTable").innerHTML="No Posee Balances definidos";
                            document.getElementById("paginator").style.display= "none";
                        }else{
                            if(newnumofrec <= pagerNumber){
                                document.getElementById("paginator").style.display= "none";    
                            } else {
                                document.getElementById("paginator").style.display= ""; 
                                drawPags(newnumofrec, "numbersPaginator");
                            }
                            /*Blanquear tabla*/
                            var nodeNoDelete = document.getElementById("noCurrencieDefine");
                            if (nodeNoDelete ){
                                var nodeClone = nodeNoDelete.cloneNode(true);   
                                nodeClone.style.display="none";
                            }
                           var table = document.getElementById("bodyTableCurrencies");
                            table.innerHTML = "";
                            if(nodeClone!==undefined && nodeClone!==null)table.appendChild(nodeClone);
                            /**-hasta aqui-**/
                            //Pintar registros
                            paintRowsList(currencies);
                     }
                    break;
                case 400:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError");
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError");   
                        msg.style.display="none";
                    }, 5000);
                    break;
                    break;
                case 401:
                    msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
                case 500:
                    msg.innerHTML=" Error Interno";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
                    break;
                default:
                    msg.innerHTML=currencies.msg;
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        msg.style.display="none";
                    }, 3000);
            }
}

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

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

function showModal(id){
    //document.getElementById('txid').value = txId;
    var modal = document.getElementById(id);
    modal.style.display = "block";
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}

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

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

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

/*function showModal(){
    //document.getElementById('txid').value = txId;
    var modal = document.getElementById("modalconfir1");
    modal.style.display = "block";
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
}*/

function openDetail(id){
    var req = {};
    var sessionId = sessionStorage.getItem("sessionId");
    req.sessionid = sessionId;
    req.id = id;
    callWS("GET", "messages/entry", req, rspMessageEntry);
}

function rspMessageEntry(status, rsp){
    switch(status){
        case 200:
            
        console.log(JSON.parse(rsp));
        var rsp = JSON.parse(rsp);
        var sentdate = rsp.entry.sentdate.date;
        if(sentdate !== null){
        //Si el mensaje no ha sido envíado puede ser modificado
            
            showModal("modaldetails");
            var date = rsp.entry.date.formatted;
            document.getElementById("dateDet").innerHTML = date;
            var users = document.createElement("div");
            dataC = rsp.entry;
            if(dataC.users.length>1){
                var span = document.createElement("span");
                span.style.textDecoration = "underline";
                span.style.fontSize = "100%";
                span.style.position = "relative";
                span.innerHTML = "+"+(dataC.users.length-1).toString()+" Destinatarios";
                span.style.cursor = "pointer";
                span.addEventListener("mouseenter",function(){
                    this.getElementsByClassName("privList")[0].style.display = "block";
                    this.getElementsByClassName("privList")[0].style.opacity = "1";
                });
                span.addEventListener("mouseleave",function(){
                    this.getElementsByClassName("privList")[0].style.display = "";
                    this.getElementsByClassName("privList")[0].style.opacity = "";
                });
                
                
                //Contenedor de lista visual de usuarios
                var list = document.createElement("div");
                list.classList.add("privList");
                list.innerHTML    =   '   <div class="privArrow"></div>'+
                            '   <div class="privListCnt">'+
                            '       <div class="privTbl" style="padding-left:3px">'+
                            '           <div class="headerLine">Total: '+dataC.users.length+' destinatarios</div>'+
                            '       </div>'+
                            '    </div>';
                span.appendChild(list);
                users.innerHTML = dataC.users[0].user + "; ";
                users.appendChild(span);
                var cnt = users.getElementsByClassName("privTbl");
                if(cnt.length>0){
                    cnt = cnt[0];
                    for(var x=0;x<dataC.users.length;x++){
                        var span = document.createElement("span");
                        span.style.display = "block";
                        span.style.fontWeight = "bold";
                        span.style.paddingBottom = "5px";
                        span.classList.add("blacktext");
                        span.innerHTML = dataC.users[x].user;
                        cnt.appendChild(span);
                    }
                }
            }else{
                users.innerHTML = dataC.users[0].user + " ";
            }
            document.getElementById("destDet").innerHTML = "";
            //Si es tipo 2 EL USUARIO RECIBIO
            if(rsp.entry.type==2){
                document.getElementById("destDet").appendChild(users);
                document.getElementById("refDet").innerHTML = rsp.entry.ref.dsc;
            }else{
            //Si es tipo 1 EL USUARIO ENVIÓ EL CMS RECIBE
                document.getElementById("refDet").innerHTML = "";
                document.getElementById("refDet").appendChild(users);
                document.getElementById("destDet").innerHTML = rsp.entry.ref.dsc;
                loadList(document.getElementById("search").value, document.getElementById("orderBy").value, 0, pagerNumber, sessionId);
            }
            document.getElementById("msgDet").innerHTML = rsp.entry.message;
        }else{
        //Si no ha sido enviado se carga la pantalla de "crear", con la posibilidad de eliminarlo
            
            document.getElementById("cancelM").innerHTML = "ELIMINAR";
            document.getElementById("aceptM").innerHTML = "GUARDAR";
            document.getElementById("modalcTit").innerHTML = "Editar Mensaje";
            document.getElementById("cancelM").parentElement.classList.remove("noShow");
            var date = rsp.entry.date.date.replace(" ", "T");
            document.getElementById("addDate").value = date;
            document.getElementById("addDescription").value = rsp.entry.message;
            document.getElementById("depFilter").value = "";
            document.getElementById("addTags").value = "";
            
            if(rsp.entry.ref.dsc !== "")document.getElementById("depFilter").value = rsp.entry.ref.dsc;
            
            var users = "";
            var userids = "";
            
            var sentSms = false;
            var sentEmail = false;
            for(var i=0;i<rsp.entry.users.length;i++){
                if(users.length>0)users+= " "
                users += rsp.entry.users[i].user;
                
                if(userids.length>0)userids+="-";
                userids += rsp.entry.users[i].id;
                
                //Si un usuario recibe el mensaje por email se marca cómo que si se envió igual para SMS
                if(rsp.entry.users[i].email !== null){
                    sentEmail = true
                }
                if(rsp.entry.users[i].sms !== null){
                    sentSms = true
                }
            }
            var box = document.getElementById("sendEmail").children[0];
            if(!sentEmail){
                box.classList.remove("fa-check-square");
                box.classList.add("fa-square");
            }else{
                box.classList.add("fa-check-square");
                box.classList.remove("fa-square");
            }
            
            var box = document.getElementById("sendSms").children[0];
            if(!sentSms){
                box.classList.remove("fa-check-square");
                box.classList.add("fa-square");
            }else{
                box.classList.add("fa-check-square");
                box.classList.remove("fa-square");
            }
            var tagusers = document.getElementById("searchUser").parentElement.getElementsByClassName("tag");
            var tags = document.getElementById("addTags").parentElement.getElementsByClassName("tag");
            for(var i=0;i<tagusers.length;i++){
                tagusers[i].parentElement.removeChild(tagusers[i]);
            }
            for(var i=0;i<tags.length;i++){
                tags[i].parentElement.removeChild(tags[i]);
            }
            var tagusers = document.getElementById("searchUser").parentElement;
            tagusers.classList.remove("disabledBox");
            tagusers.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
            tagusers.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
            var tags = document.getElementById("addTags").parentElement;
            tags.classList.remove("disabledBox");
            tags.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "";
            tags.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].removeAttribute("disabled");
            
            
            document.getElementById("searchUser").value = users.replace(" ",",");
            document.getElementById("searchUser").getAttribute("userids", userids);
            setTimeout(function(){
                if(rsp.entry.tags !== "" && rsp.entry.tags !== null){
                    drawTags(document.getElementById("addTags").parentElement,rsp.entry.tags);
                    var tagusers = document.getElementById("searchUser").parentElement;
                    tagusers.classList.add("disabledBox");
                    tagusers.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                    tagusers.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                    
                    var tags = document.getElementById("addTags").parentElement;
                    tags.classList.add("disabledBox");
                    tags.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                    tags.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                }else{
                    drawTags(document.getElementById("searchUser").parentElement, users);
                    var tags = document.getElementById("addTags").parentElement;
                    tags.classList.add("disabledBox");
                    tags.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                    tags.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                    
                    var tagusers = document.getElementById("searchUser").parentElement;
                    tagusers.classList.add("disabledBox");
                    tagusers.getElementsByClassName("tagInptEle")[0].style.backgroundColor = "transparent";
                    tagusers.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].setAttribute("disabled","");
                    
                }
                setTimeout(function(){
                    var tags = document.getElementsByClassName("tag");
                    for(var i=0;i<tags.length;i++){
                        tags[i].style.pointerEvents = "none";
                    }
                },1000);
            },500);
            
            
            
            userEditId = rsp.entry.id;
            showModal("modalconfir");
        }
        
        
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML="Sesión expirada o inválida, vuelva a iniciar sesión";
                    msg.classList.add("msgError"); 
                    msg.style.display="block";
                    setTimeout(function() {
                        msg.classList.remove("msgError"); 
                        myLogout()
                        msg.style.display="none";
                    }, 3000);
                    break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller=JSON.parse(rsp);
            console.log(JSON.parse(rsp));
            break;
        default:
            //console.log(rsp);
    }
}

function loadDepartments(filter, order, offset, numofrec, sessionid){
    var par = {};
    //Se pasa el document.getElementById("search").value por el parametro filter.
    par.filter = filter;
    par.order = '1'
    par.offset = offset;
    par.numofrec = numofrec;
    par.sessionid = sessionid;
    //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "departments/list", par, respDep);
    
    function respDep(status, rsp){
        let countries = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch(status){
            case 200:
                var countriesList = document.getElementById("depFilter");
                if(countries.records!==null){
                    for (let i=0; i<countries.records.length; i++){
                        var op = document.createElement("option");
                        if(countries.records.length == 0){
                            op.text= "No hay departamentos definidos";
                            op.disabled = true;
                            op.value = " ";
                            op.selected = true;
                            countriesList.appendChild(op);
                        } else {
                            if(countries.records[i].id !== null){
                                op.text= countries.records[i].dsc;
                                op.value = countries.records[i].id;
                                countriesList.appendChild(op);
                            }
                        }
                    }
                    var filter = document.getElementById("search").value;
                    if(filter == null || filter == undefined){
                        filter  = '';
                    }
                    loadList(filter, 1, 0, 10, sessionId);
                }else{
                    var op = document.createElement("option");
                    op.text= "No hay departamentos definidos";
                    op.disabled = true;
                    op.value = " ";
                    op.selected = true;
                    countriesList.appendChild(op);
                }
                break;
            case 403:
                var countriesList = document.getElementById("depFilter");
                /*
                for (let i=0; i<countries.records.length; i++){
                    var op = document.createElement("option");
                    if(countries.records.length == 0){
                        op.text= "No hay departamentos definidos";
                        op.disabled = true;
                        op.value = " ";
                        op.selected = true;
                        countriesList.appendChild(op);
                    } else {
                        if(countries.records[i].id !== null){
                            op.text= countries.records[i].dsc;
                            op.value = countries.records[i].id;
                            countriesList.appendChild(op);
                        }
                    }
                }
                var filter = document.getElementById("search").value;
                if(filter == null || filter == undefined){
                    filter  = '';
                }
                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);*/
        }
    }
}

//Aqui se pintan los registros
function paintRowsList(data){
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if(pageInPaginator){
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    rowCurrencie.innerHTML = "";
    var filas;
    let newnumofrec = parseInt(data.numofrecords);
    if (newnumofrec > pagerNumber){
        filas = newnumofrec - ((parseInt(pageInPaginator) - 1) * pagerNumber);
        if(filas > pagerNumber){
            filas = pagerNumber;
        }
    } else {
        filas = newnumofrec;
    }
    
    
    //type 0 = impar, 1 = par
    let type = 0;
    let dataC = data.records;
    for (let i=0; i<filas; i++){
        var tableLine = document.createElement("div");
        tableLine.classList.add("tableLine");
        tableLine.id= "line/"+dataC[i].id;
        if(type === 0){
            tableLine.classList.add("rowImpar");
            type=type+1;
        }else if(type === 1){
            type = 0;
        }
        let typeElmnt ;
        
        var readed = 0;
        var notreaded = 0;
        
        var readedMsg = false;
        var intermedio = false;
        for(var x=0;x<dataC[i].users.length;x++){
            if(dataC[i].users[x].readed!==null)readed = readed+1;
            else notreaded = notreaded+1;
        }
        if(notreaded == 0 && readed == dataC[i].users.length)readedMsg = true;
        else if(notreaded > 0 && readed > 0){readedMsg = true; intermedio = true;}
        if(!readedMsg){
            typeElmnt = '<i class="far fa-square iconBlue" title="No leídos"></i>';
        }else if(readedMsg && intermedio){
            typeElmnt = '<i class="fas fa-check-square iconGray" title="Leído parcialmente"></i>';
        }else{
            typeElmnt = '<i class="fas fa-check-square iconBlue" title="Leídos"></i>';
        }
        let typeLoad;
        //SI ES TIPO 2 EL USUARIO RECIBE CMS ENVIA
        if(dataC[i].type === 2){
            typeLoad = '<i class="fas fa-upload iconBlue"></i>';
        }else{
        //SI ES TIPO 1 EL USUARIO ENVIA CMS RECIBE
            typeLoad = '<i class="fas fa-download iconBlue"></i>';
        }
        
        tableLine.addEventListener('click', function (event) {
            openDetail(this.getAttribute("msgid"));
        });
        tableLine.setAttribute("msgid",dataC[i].id);
        
        var users = document.createElement("div");
        users.classList.add("cntusersFmt");
        if(dataC[i].users.length>1){
            var span = document.createElement("span");
            span.style.textDecoration = "underline";
            span.style.fontSize = "100%";
            span.style.position = "relative";
            span.innerHTML = "+"+(dataC[i].users.length-1).toString()+" Usuarios";
            span.style.cursor = "pointer";
            span.addEventListener("mouseenter",function(){
                this.getElementsByClassName("privList")[0].style.display = "block";
                this.getElementsByClassName("privList")[0].style.opacity = "1";
            });
            span.addEventListener("mouseleave",function(){
                this.getElementsByClassName("privList")[0].style.display = "";
                this.getElementsByClassName("privList")[0].style.opacity = "";
            });
            
            
            //Contenedor de lista visual de usuarios
            var list = document.createElement("div");
            list.classList.add("privList");
            list.innerHTML    =   '   <div class="privArrow"></div>'+
                        '   <div class="privListCnt">'+
                        '       <div class="privTbl" style="padding-left:3px">'+
                        '           <div class="headerLine">Total: '+dataC[i].users.length+' destinatarios</div>'+
                        '       </div>'+
                        '    </div>';
            span.appendChild(list);
            users.innerHTML = dataC[i].users[0].user + "; ";
            users.appendChild(span);
        }else{
            users.innerHTML = dataC[i].users[0].user + " ";
        }
        
        
        tableLine.innerHTML = '<div class="cell1">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+typeElmnt+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell2">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+typeLoad+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell3">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span>'+dataC[i].date.formatted+'</span>'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell4">'+
                                                    '<div class="divCellCnt">'+
                                                    '</div>'+
                                                '</div>'+
                                                '<div class="cell5">'+
                                                    '<div class="divCellCnt">'+
                                                        '<span style="max-height:30px;overflow:hidden;display:block;">'+dataC[i].message+'</span>'+
                                                    '</div>'+
                                                '</div>';
        rowCurrencie.appendChild(tableLine);
        
        //Agregar nuevo formato de usuario a columna correspondiente de la linea insertada
        tableLine.children[3].children[0].appendChild(users);
        var cnt = tableLine.getElementsByClassName("privTbl");
        if(cnt.length>0){
            cnt = cnt[0];
            for(var x=0;x<dataC[i].users.length;x++){
                var span = document.createElement("span");
                span.style.display = "block";
                span.style.fontWeight = "bold";
                span.style.paddingBottom = "5px";
                span.classList.add("blacktext");
                span.innerHTML = dataC[i].users[x].user;
                cnt.appendChild(span);
            }
        }
    }

}
