
//Guardar entry del usuario
var upsess = false, validsess = false, portexn = false, xchexn = false; paythirds = false;
var loadupd = false, loadvalid = false, loadport = false, loadxch = false; loadpayt = false;
var saveloop = "";
window.onload = function () {
    decimCoin = 0;
    var sessionId = sessionStorage.getItem("sessionId");
    initApp();
    loadActs();
    LoadLevels(sessionId);
    var filter = document.getElementById("search").value;
    if (filter == null || filter == undefined) {
        filter = '';
    }
    LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
    document.getElementById("registerFilter").addEventListener("change", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }

        //Se desmarca la pagina anterior
        var pSel = document.getElementsByClassName("pSelect");
        if (pSel.length > 0) pSel[0].classList.remove("pSelect");

        //Colocamos la pagina 1
        var page1 = document.getElementsByClassName("pages")[0];
        if (page1 != undefined) {
            page1.classList.add("pSelect");
        }

        LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, this.value, sessionId);
    });

    document.getElementById("closeModalDetailNatural").addEventListener("click", function () {
        var modal = document.getElementById("modalDetailNatural");
        modal.style.display = "none";

        blankForm(modal);
    });
    document.getElementById("modalDetailNatural").addEventListener("click", function (e) {
        e = window.event || e;
        if (this === e.target || e.target === this.children[0]) {
            // put your code here
            var modal = document.getElementById("modalDetailNatural");
            modal.style.display = "none";

            blankForm(modal);
        }
    });
    document.getElementById("modalDetailLegal").addEventListener("click", function (e) {
        e = window.event || e;
        if (this === e.target || e.target === this.children[0]) {
            // put your code here
            var modal = document.getElementById("modalDetailLegal");
            modal.style.display = "none";

            blankForm(modal);
        }
    });


    document.getElementById("buttonCloseModalImage").addEventListener("click", function () {
        document.getElementById("modalImage").style.opacity = "";
        setTimeout(function () {
            document.getElementById("modalImage").style.display = "";
        }, 300);
    });

    document.getElementById("groupTagLegal").addEventListener("click", function () {
        document.getElementById("tagLegal").focus();
    });

    document.getElementById("groupTagNatural").addEventListener("click", function () {
        document.getElementById("tagNatural").focus();
    });
    /*
    document.getElementById("tagNatural").addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
          AddTagPersonLegal(this, 'tagLegalPerson');
        }
    });
    
    document.getElementById("tagLegal").addEventListener('keypress', function (e) {
        if (e.key === 'Enter') {
          AddTagPersonLegal(this, 'tagNaturalPerson');
        }
    });
    */
    document.getElementById("swichtStatusLegal").addEventListener("click", function () {
        if (this.classList.contains("active")) {
            this.classList.remove("active");
            this.firstElementChild.classList.remove("balActive");
        } else {
            this.classList.add("active");
            this.firstElementChild.classList.add("balActive");
        }
    });


    document.getElementById("swichtStatusNatural").addEventListener("click", function () {
        if (this.classList.contains("active")) {
            this.classList.remove("active");
            this.firstElementChild.classList.remove("balActive");
        } else {
            this.classList.add("active");
            this.firstElementChild.classList.add("balActive");
        }
    });

    document.getElementById("buttonAceptModalLegal").addEventListener("click", function () {
        var modal = document.getElementById("modalDetailLegal");
        const id = modal.dataset.idModalLegal;
        //updateSessionLegal(id, 2);
        validateSessionLegal(id);

        //document.getElementById("closeModalDetailLegal").dispatchEvent(new Event("click")); 
    });

    document.getElementById("buttonAceptModalNatural").addEventListener("click", function () {
        var modal = document.getElementById("modalDetailNatural");
        const id = modal.dataset.idModalNatural;
        validateSessionNatural(id);

        //document.getElementById("closeModalDetailLegal").dispatchEvent(new Event("click")); 
    });

    document.getElementById("closeModalDetailLegal").addEventListener("click", function () {
        document.getElementById("levelLegal").value = "";
        document.getElementById("riskLevelLegal").value = "";

        var modal = document.getElementById("modalDetailLegal");
        modal.style.display = "none";
        blankForm(modal);
        /*
        document.getElementById("venezuelanLegal").innerHTML = "";
        document.getElementById("typeCompany").innerHTML = "";
        document.getElementById("identificationLegal").innerHTML = "";
        document.getElementById("reasonSocial").innerHTML = "";
        document.getElementById("comercialName").innerHTML = "";
        document.getElementById("dateCreateCompany").innerHTML = "";
        document.getElementById("countryCompany").innerHTML = "";
        document.getElementById("stateCompany").innerHTML = "";
        document.getElementById("cityCompany").innerHTML = "";
        document.getElementById("codePostal").innerHTML = "";
        document.getElementById("phoneLegal").innerHTML = "";
        document.getElementById("webSite").innerHTML = "";
        document.getElementById("numberPartners").innerHTML = "";
        
        document.getElementById("legalRepresentative").innerHTML = "";
        document.getElementById("identificationRepresentative").innerHTML = "";
        document.getElementById("phoneRepresentative").innerHTML = "";
        document.getElementById("personExposed").innerHTML = "";
        document.getElementById("nameEntity").innerHTML = "";
        document.getElementById("jobPerforms").innerHTML = "";
        document.getElementById("countryPersonExposed").innerHTML = "";
        document.getElementById("identificationPersonExposed").innerHTML = "";
        var tabPartner = document.getElementById("partner-data");
        var elements = document.querySelectorAll('[data-partner="partnerNoRep"]');
        for(let i=0; i<elements.length; i++){
            tabPartner.removeChild(elements[i]);
        }
        
        document.getElementById("countryResidence").innerHTML = "";
        document.getElementById("stateResidence").innerHTML = "";
        document.getElementById("cityResidence").innerHTML = "";
        document.getElementById("streetResidence").innerHTML = "";
        document.getElementById("houseNumber").innerHTML = "";
        document.getElementById("branchOffice").innerHTML = "";
        
        document.getElementById("economicAct").innerHTML = "";
        document.getElementById("anualIncome").innerHTML = "";
        document.getElementById("worth").innerHTML = "";
        
        var tabImagesLegal = document.getElementById("images-data-legal");
        var image = document.querySelectorAll('[data-image="imagesLegalRemovible"]');
        for(let i=0; i<image.length; i++){
            tabImagesLegal.removeChild(image[i]);
        }
        
        document.getElementById("averageMonth").innerHTML = "";
        document.getElementById("mountOp").innerHTML = "";
        document.getElementById("typeOp").innerHTML = "";
        document.getElementById("relationGruop").innerHTML = "";
        
        var tabAccounts = document.getElementById("accounts-legal");
        var account = document.querySelectorAll('[data-account="accountsLegalRemovible"]');
        for(let i=0; i<account.length; i++){
            tabAccounts.removeChild(account[i]);
        }*/

    });

    var tabLinks = document.getElementsByClassName("tablinksNatural");
    for (let i = 0; i < tabLinks.length; i++) {
        tabLinks[i].addEventListener("click", function () {
            openTabInNaturalModal(this);

            drawLevelMarks("modalDetailNatural");
        })
    }

    var tabLinks = document.getElementsByClassName("tablinksLegal");
    for (let j = 0; j < tabLinks.length; j++) {
        tabLinks[j].addEventListener("click", function () {
            openTabInLegalModal(this);

            drawLevelMarks("modalDetailLegal");
        })
    }

    var validCols = document.getElementsByClassName("validCol");
    for (let k = 0; k < validCols.length; k++) {
        const iValid = validCols[k].children[0];
        const iPending = validCols[k].children[1]
        const iRejected = validCols[k].children[2];
        iValid.addEventListener("click", function () {
            ActRow(iValid, 'valid');
        });

        iPending.addEventListener("click", function () {
            ActRow(iPending, 'pending');
        });
        iRejected.addEventListener("click", function () {
            ActRow(iRejected, 'invalid');
        });
    }

    document.getElementById("orderBy").addEventListener("change", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }
        LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, this.value, document.getElementById("registerFilter").value, sessionId);
    });

    document.getElementById("rangeFilter").addEventListener("change", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }
        LoadSessions(filter, this.value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
    });

    document.getElementById("statusFilter").addEventListener("change", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }
        LoadSessions(filter, document.getElementById("rangeFilter").value, this.value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
    });

    document.getElementById("levelFilter").addEventListener("change", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }
        LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, this.value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
    });

    // Event "click" arrows active Selects
    document.getElementById("arrowRangeFilter").addEventListener("mouseover", function () {
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content = iconContainer.parentElement;
        content.removeChild(iconContainer);
        setTimeout(function () {
            content.appendChild(node);
        }, 2000);
    });

    document.getElementById("arrowLevelFilter").addEventListener("mouseover", function () {
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content = iconContainer.parentElement;
        content.removeChild(iconContainer);
        setTimeout(function () {
            content.appendChild(node);
        }, 2000);
    });

    document.getElementById("arrowStatusFilter").addEventListener("mouseover", function () {
        var iconContainer = this.parentElement;
        var node = iconContainer.cloneNode(true);
        var content = iconContainer.parentElement;
        content.removeChild(iconContainer);
        setTimeout(function () {
            content.appendChild(node);
        }, 2000);
    });

    // Event to input search
    document.getElementById("search").addEventListener("change", function () {
        if (this.value == null || this.value == undefined) {
            filter = '';
        } else {
            filter = this.value;
        }
        LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
    });

    /*funcion del ordenar**/

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

    //CARGAR TAGS EVENTO
    tagLoad();

    //NUEVO MODELO SESIONES 09_01_2022
    var tabLinks = document.getElementsByClassName("tablinksLvls");
    for (let i = 0; i < tabLinks.length; i++) {
        tabLinks[i].addEventListener("click", function () {
            tablinks = document.getElementsByClassName("tablinksLvls");
            for (i = 0; i < tablinks.length; i++) {
                tablinks[i].parentNode.classList.remove("activeTab");
            }
            var scrollCnt = document.getElementById("scrollCnt");
            var nwHeight = 20 + document.getElementById(this.getAttribute("data-name")).offsetHeight + document.getElementById(this.getAttribute("data-name")).previousElementSibling.offsetHeight;
            scrollCnt.style.height = nwHeight + "px";
            scrollCnt.firstElementChild.style.marginLeft = (-100 * this.getAttribute("pos")) + "%";
            this.parentNode.classList.add("activeTab");
        })
    }

    //Cerrar popup
    document.getElementById("backListBtn").addEventListener("click", function () {
        var filter = document.getElementById("search").value;
        if (filter == null || filter == undefined) {
            filter = '';
        }
        var pSel = document.getElementsByClassName("pSelect");
        var offset = 0;
        if (pSel.length > 0) offset = (pSel[0].innerHTML - 1) * pagerNumber;
        var order = document.getElementById("orderBy").value;
        LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, sessionId);

    });
    document.getElementById("saveEntryBtn").addEventListener("click", function () {
        saveloop = setInterval(function () {
            var ele = document.getElementById("saveEntryBtn");
            if (!upsess) {
                if (!loadupd) {
                    updateSession(ele.getAttribute("usrid"));
                }
            } else {
                loadupd = true;
            }
            if (!validsess) {
                if (!loadvalid && loadupd) {
                    validateSession(ele.getAttribute("usrid"));
                }
            } else {
                loadvalid = true;
            }
            if (!portexn) {
                if (!loadport && loadvalid) {
                    updtPortfolioExn(ele.getAttribute("usrid"));
                }
            } else {
                loadport = true;
            }
            if (!xchexn) {
                if (!loadxch && loadport) {
                    updtExchageExn(ele.getAttribute("usrid"));
                }
            } else {
                loadxch = true;
            }

            if (!paythirds) {//Este nivel determina si se debe o no tomar en consideración este guardar
                if (!loadpayt && loadxch) {//Este valida si fue ejecutado y si el anterior también ya culminó para guardar si lo requiere, se ejecuta 1 sola vez
                    updtPayThirds(ele.getAttribute("usrid"));
                }
            } else {
                loadpayt = true;
            }

            if (loadvalid && loadupd && loadxch && loadport && loadpayt) {
                loadvalid = false; loadupd = false; loadxch = false; loadport = false; loadpayt = false;
                clearInterval(saveloop);

            }
        }, 600);
    });
    //Evento switch del status del usuario
    document.getElementById("usrStatus").addEventListener("click", function () {
        if (this.classList.contains("active")) {
            this.classList.remove("active");
            this.firstElementChild.classList.remove("balActive");
        } else {
            this.classList.add("active");
            this.firstElementChild.classList.add("balActive");
        }
    });
    //Evento switch del pago movil para pagos a terceros
    document.getElementById("switchPm").addEventListener("click", function () {
        if (this.getAttribute("disabled") == null || this.getAttribute("disabled") == undefined) {
            if (this.classList.contains("active")) {
                this.classList.remove("active");
                this.firstElementChild.classList.remove("balActive");
            } else {
                this.classList.add("active");
                this.firstElementChild.classList.add("balActive");
            }
        }
    });



}
function addLineAcc(cnt, id, lbl, val, valid = "", first = false) {
    var line = cnt.children[0].cloneNode(true);
    line.style.display = "";
    //Agregar evento a campo status prueba 1
    var statuscell = line.getElementsByClassName("statusLvlCell");
    //Validamos si es par o impar para el fondo de la linea
    var qty = cnt.getElementsByClassName("rowLvlInf").length;
    if (qty % 2 == 0) line.classList.add("rowImpar");
    else line.classList.remove("rowImpar");

    line.getElementsByClassName("markBgLvl")[0].style.display = "";


    var value = "";
    if (val !== "" && val !== null && val !== undefined) {
        line.classList.add("accVal");
        arr = val.split("_-*-_");
        if (arr.length > 1) {
            value = arr[0];
            line.setAttribute("accid", arr[1]);
        }
    }
    if ((value !== "" && value != 'null' && value != 'undefined')) {
        if (!validsess) {
            for (var i = 0; i < statuscell.length; i++) {
                statuscell[i].addEventListener("click", function () {
                    var cnt = this.parentElement;
                    var actv = cnt.getElementsByClassName("lvlCellActv");
                    if (actv.length > 0) {
                        actv[0].classList.remove("lvlCellActv");
                    }
                    this.classList.add("lvlCellActv");
                    var bgbox = cnt.getElementsByClassName("markBgLvl")[0];
                    bgbox.style.left = this.offsetLeft + "px";
                    var color = "";
                    switch (this.getAttribute("label")) {
                        case '0':
                            color = "#F5AC3E";
                            break;
                        case '1':
                            color = "#85BB4F";
                            break;
                        case '-1':
                            color = "#C04F5D";
                            break;
                    }
                    bgbox.style.backgroundColor = color;
                });
            }

        }
        line.getElementsByClassName("cellInfTbl")[3].innerHTML = value;
    } else {
        valid = "";
        line.getElementsByClassName("cellInfTbl")[3].innerHTML = "";
        line.getElementsByClassName("markBgLvl")[0].style.display = "none";
    }

    var pos = "";
    switch (valid.toString()) {
        case '0':
            pos = "0";
            break;
        case '1':
            pos = "1";
            break;
        case '-1':
            pos = "2";
            break;
        default:
            pos = "";
            break;
    }
    line.getElementsByClassName("cellInfTbl")[0].setAttribute("upid", id);
    if (first) {
        line.getElementsByClassName("cellInfTbl")[1].innerHTML = first;
    } else {
        line.getElementsByClassName("cellInfTbl")[1].innerHTML = "";
    }
    line.getElementsByClassName("cellInfTbl")[2].innerHTML = lbl;
    cnt.appendChild(line);
    //Se marca el correcto luego de insertado
    if (pos !== "") {
        var cell = line.getElementsByClassName("statusLvlCell");
        cell[pos].dispatchEvent(new Event("click"));
    }
    //Se marca el correcto luego de insertado
    if (validsess) {
        var statuscell = line.getElementsByClassName("statusLvlCell");
        var actv = line.getElementsByClassName("lvlCellActv");
        var bgbox = line.getElementsByClassName("markBgLvl")[0];
        if (actv.length > 0) {
            actv[0].classList.remove("lvlCellActv");
        }
        line.getElementsByClassName("markBgLvl")[0].style.display = "none";
        if (pos !== "") {
            line.getElementsByClassName("markBgLvl")[0].style.display = "";
            statuscell[pos].classList.add("lvlCellActv");
            bgbox.style.left = statuscell[pos].offsetLeft + "px";
        }
        var color = "";
        switch (pos) {
            case '0':
                color = "#F5AC3E";
                break;
            case '1':
                color = "#85BB4F";
                break;
            case '-1':
                color = "#C04F5D";
                break;
        }
        bgbox.style.backgroundColor = color;
    }
}
function addLineInf(cnt, id, lbl, val, valid = "", type = false) {
    var line = cnt.children[0].cloneNode(true);
    line.style.display = "";
    //Agregar evento a campo status prueba 1
    var statuscell = line.getElementsByClassName("statusLvlCell");
    //Validamos si es par o impar para el fondo de la linea
    var qty = cnt.getElementsByClassName("rowLvlInf").length;
    if (qty % 2 == 0) line.classList.add("rowImpar");
    else line.classList.remove("rowImpar");

    line.getElementsByClassName("markBgLvl")[0].style.display = "";
    if ((val !== "" && val !== null && val !== undefined)) {
        if (!validsess) {
            if ((id !== 'terms' && id !== 'declaration')) {
                for (var i = 0; i < statuscell.length; i++) {
                    statuscell[i].addEventListener("click", function () {
                        var cnt = this.parentElement;
                        var actv = cnt.getElementsByClassName("lvlCellActv");
                        if (actv.length > 0) {
                            actv[0].classList.remove("lvlCellActv");
                        }
                        this.classList.add("lvlCellActv");
                        var bgbox = cnt.getElementsByClassName("markBgLvl")[0];
                        bgbox.style.left = this.offsetLeft + "px";
                        var color = "";
                        switch (this.getAttribute("label")) {
                            case '0':
                                color = "#F5AC3E";
                                break;
                            case '1':
                                color = "#85BB4F";
                                break;
                            case '-1':
                                color = "#C04F5D";
                                break;
                        }
                        bgbox.style.backgroundColor = color;
                    });
                }
            }
        }
    } else {
        line.getElementsByClassName("markBgLvl")[0].style.display = "none";
        valid = "";
    }

    var pos = "";
    switch (valid.toString()) {
        case '0':
            pos = "0";
            break;
        case '1':
            pos = "1";
            break;
        case '-1':
            pos = "2";
            break;
        default:
            pos = "";
            break;
    }
    line.getElementsByClassName("cellInfTbl")[0].setAttribute("upid", id);
    line.getElementsByClassName("cellInfTbl")[1].innerHTML = lbl;
    line.getElementsByClassName("cellInfTbl")[2].innerHTML = "";
    if (type == "up" && val !== "") {
        line.getElementsByClassName("cellInfTbl")[2].classList.add("upvalue");
        line.getElementsByClassName("cellInfTbl")[2].innerHTML = 'Ver Requisito ';
        line.getElementsByClassName("cellInfTbl")[2].setAttribute("url", val);
        line.getElementsByClassName("cellInfTbl")[2].addEventListener("click", function () {
            var url = this.getAttribute("url");
            window.open(url, '_blank');
        });
    } else if (type == "prtnr") {
        var value = "";
        line.classList.add("prnrval");
        if (val !== "" && val !== null && val !== undefined) {
            arr = val.split("_-*-_");
            if (arr.length > 1) {
                value = arr[0];
                line.setAttribute("prtnrid", arr[1]);
            }
        }
        line.getElementsByClassName("cellInfTbl")[2].innerHTML = value;
    } else if (val !== "") {
        line.getElementsByClassName("cellInfTbl")[2].classList.remove("upvalue");
        line.getElementsByClassName("cellInfTbl")[2].innerHTML = val;
    } else {

    }
    cnt.appendChild(line);
    //Se marca el correcto luego de insertado
    if (pos !== "") {
        var cell = line.getElementsByClassName("statusLvlCell");
        cell[pos].dispatchEvent(new Event("click"));
    }
    if (id == 'terms' || id == 'declaration' || validsess) {
        var statuscell = line.getElementsByClassName("statusLvlCell");
        var actv = line.getElementsByClassName("lvlCellActv");
        var bgbox = line.getElementsByClassName("markBgLvl")[0];
        if (actv.length > 0) {
            actv[0].classList.remove("lvlCellActv");
        }
        line.getElementsByClassName("markBgLvl")[0].style.display = "none";
        if (pos !== "") {
            line.getElementsByClassName("markBgLvl")[0].style.display = "";
            statuscell[pos].classList.add("lvlCellActv");
            bgbox.style.left = statuscell[pos].offsetLeft + "px";
        }
        var color = "";
        switch (pos) {
            case '0':
                color = "#F5AC3E";
                break;
            case '1':
                color = "#85BB4F";
                break;
            case '-1':
                color = "#C04F5D";
                break;
        }
        bgbox.style.backgroundColor = color;
    }
}
var dataNat = {
    //Natural
    'venezuelan': 'Ciudadano Venezolano',
    'fname': 'Nombres',
    'flastname': 'Apellidos',
    'phone': 'Teléfono',
    'birthdate': 'Fecha de Nacimiento',
    'doctype': 'Tipo de Documento',
    'doc': 'Documento de Identidad',
    'countryid': 'País de Residencia',
    'declaration': 'Declaración Jurada',
    'terms': 'Términos y Condiciones',
    'gender': 'Sexo',
    'american': 'Ciudadano Americano',
    'maritalstatus': 'Estado Civil',
    'profession': 'Profesión',
    'economicactivity': 'Actividad Económica',
    'regionid': 'Estado de Residencia',
    'cityid': 'Ciudad / Municipio',
    'company': 'Nombre de Empresa',
    'ocupation': 'Ocupación',
    'independentdealer': 'Comerciante independiente',
    'street': 'Dirección de Residencia',
    'postalcode': 'Código Postal',
    'doccountryid': 'País Emisor de Documento de Identidad',
    'docissue': 'Fecha de Emisión',
    'docexpiry': 'Fecha de Expiración',
    'politicallyexposed': 'Persona Expuesta Políticamente (PEP)',
    'affiliationbody': 'Nombre del ente adscrito',
    'positionheld': 'Cargo que Desempeña',
    'pepcountryid': 'País',
    'peprelatedid': 'Identificación del relacionado',
    'anualincome': 'Ingreso Anual ($)',
    'patrimony': 'Patrimonio ($)',
    'ocupation': 'Ocupación',
    'qtymonthlyop': 'Cantidad de Operaciones Promedio Mensuales',
    'amountmonthlyop': 'Monto ($) de Operaciones Promedio Mensuales',
    'prefertypeop': 'Tipo de operación que estima realizar',
    'economicrelation': 'Posee relación con algún grupo económico'
};
var dataJur = {
    //Jurídicos
    'name': 'Razón Social',
    'comercialname': 'Siglas',
    'doccountryid': 'País de Registro',
    'docregionid': 'Estado de Registro',
    'doccityid': 'Ciudad de Registro',
    'ctype': 'Tipo de Compañia',
    'doc': 'Número de Identificación',
    'venezuelan': 'Empresa Venezolana',
    'phone': 'Teléfono',
    'website': 'Sitio Web',
    'postalcode': 'Código Postal',
    'creationdate': 'Fecha de Creación',
    'economicactivity': 'Actividad Económica',
    'politicallyexposed': 'Persona Expuesta Políticamente (PEP)',
    'anualincome': 'Ingreso Anual ($)',
    'patrimony': 'Patrimonio ($)',
    'ocupation': 'Ocupación',
    'qtymonthlyop': 'Cantidad de Operaciones Promedio Mensuales',
    'amountmontlyop': 'Monto ($) de Operaciones Promedio Mensuales',
    'prefertypeop': 'Tipo de operación que estima realizar',
    'economicrelation': 'Posee relación con algún grupo económico',
    'countryid': 'País de Residencia',
    'regionid': 'Estado de Residencia',
    'cityid': 'Ciudad de Residencia',
    'street': 'Calle / Avenida',
    'domicile': 'Casa / Apartamento Nro.',
    'branchoffices': 'Número de Sucursales',
    'declaration': 'Declaración Jurada',
    'terms': 'Términos y Condiciones',
    //Socios
    'partners': "Número de Socios",
    'reppartner': "Representante Legal es Socio",
    'lgname': "Representante Legal",
    'lgdoc': "Cédula del Representante Legal",
    'lgphone': "Teléfono del Representante Legal",
    'lgpoliticallyexposed': 'Persona Expuesta Políticamente (PEP)',
    'lgaffiliationbody': 'Nombre del ente adscrito',
    'lgpositionheld': 'Cargo que Desempeña',
    'lgpepcountryid': 'País',
    'lgpeprelatedid': 'Identificación del relacionado',
    'prtname': "Nombre Completo Socio ",
    'prtdoc': "Cédula Socio ",
    'prtphone': "Teléfono Socio ",
    'prtpoliticallyexposed': 'Persona Expuesta Políticamente (PEP) Socio ',
    'prtaffiliationbody': 'Nombre del ente adscrito Socio ',
    'prtpositionheld': 'Cargo que Desempeña Socio ',
    'prtpepcountryid': 'País Socio ',
    'prtpeprelatedid': 'Identificación del relacionado Socio ',
}

function blankEntry(id) {
    var cnt = id;
    var clone = cnt.firstElementChild;
    nwnode = clone.cloneNode(true);
    nwnode.style.display = "none";
    cnt.innerHTML = "";
    cnt.appendChild(nwnode);
}
//Lo más generico posible
function drawEntry(lvl, rsp) {
    var cnt = "";
    switch (lvl) {
        case '0.5':
            cnt = document.getElementById("tblInitialLvl");
            break;
        case '1':
            cnt = document.getElementById("tblBasicLvl");
            break;
        case '2':
            cnt = document.getElementById("tblMiddleLvl");
            break;
        case '3':
            cnt = document.getElementById("tblAdvancedLvl");
            break;
    }
    document.getElementById("saveEntryBtn").setAttribute("usrid", rsp.entry.id);
    blankEntry(cnt);
    var lvlfields = "";
    var lvluploads = "";
    var partnerfields = "";
    for (var i = 0; i < rsp.entry.levelfields.length; i++) {
        if (rsp.entry.levelfields[i].level == lvl) {
            lvlfields = rsp.entry.levelfields[i].typefields;
            lvluploads = rsp.entry.levelfields[i].uploadsId;
            if (rsp.entry.levelfields[i].partnerfields !== null && rsp.entry.levelfields[i].partnerfields != undefined) {
                partnerfields = rsp.entry.levelfields[i].partnerfields;
            }
        }
        if (rsp.entry.type.id == 1) {
            if (lvl == 1) {
                lvlfields = lvlfields + ",company";
                if (rsp.entry.person.politicalexposed.value == "Si") {
                    lvlfields = lvlfields + 'affiliationbody,positionheld,pepcountryid,peprelatedid';
                }
            }
        } else {
            if (lvl == '0.5') {
                lvlfields = "";
                lvluploads = "";
            } else if (lvl == '1') {
                lvlfields = lvlfields + ",comercialname,website,venezuelan";
            }
        }
    }
    var data = {};
    if (rsp.entry.type.id == 1) {
        data = dataNat;
    } else {
        data = dataJur;
    }
    for (let i in rsp) {
        if (i == 'entry') {
            for (let j in rsp[i]) {
                if (j == 'person' || j == 'company') {
                    for (let k in rsp[i][j]) {
                        if (rsp[i][j][k]) {
                            if (k == 'uploads') {
                                for (let l in rsp[i][j][k]) {
                                    var obj = rsp[i][j][k][l];
                                    var lbl = obj['dsc'];
                                    if (obj['id'] == 9 && (rsp.entry.type.id == 1)) {
                                        var dscarr = obj['dsc'].split("/");
                                        if (dscarr.length >= 2) {
                                            lbl = lbl.replace("Contrato de alquiler", "RIF");
                                            lbl = lbl.replace("Comprobante de registro de información fiscal", "RIF");
                                            lbl = lbl.replace("Rental Agreement", "RIF");
                                            lbl = lbl.replace("Proof of tax information registration", "RIF");
                                        }
                                    }
                                    var id = parseFloat(obj['id']);
                                    var val = obj['url'];
                                    var valid = obj['validated'];
                                    if (lbl !== undefined && (lvluploads.indexOf(id) > -1)) addLineInf(cnt, id, lbl, val, valid, "up");
                                }
                            }
                            //Si llegamos acá y es un objeto debemos ir un nivel más adentro y no existe el "update" campo identificador
                            if (typeof rsp[i][j][k] === 'object' && rsp[i][j][k]['update'] == null) {
                                for (let l in rsp[i][j][k]) {
                                    var obj = rsp[i][j][k][l];
                                    if (obj) {
                                        if (obj['update']) {
                                            var id = obj['update'];
                                            var lbl = data[id];

                                            var val = "";
                                            if (obj['value'] != undefined && obj['value'] != null) {
                                                val = obj['value'];
                                            } else if (obj['number'] != undefined && obj['number'] != null) {
                                                val = obj['number'];
                                            } else if (obj['dsc'] != undefined && obj['dsc'] != null) {
                                                val = obj['dsc'];
                                                if (obj['update'] == 'prefertypeop') {
                                                    var optypes = [{ "id": 1, "dsc": "Cripto - Cripto (C-C)" }, { "id": 2, "dsc": "Cripto - Dinero Fiat (C-DF)" },
                                                    { "id": 3, "dsc": "Dinero Fiat - Cripto (DF-C)" }];

                                                    var dscval = "";
                                                    if (obj['id'] !== "" && obj['id'] != null) {
                                                        var ids = obj['id'].split("-");
                                                        for (var z = 0; z < optypes.length; z++) {
                                                            if (ids.indexOf((optypes[z].id).toString()) > -1) {
                                                                dscval += optypes[z].dsc + " /";
                                                            }
                                                        }
                                                    }
                                                    if (dscval != "") dscval = dscval.substring(0, dscval.length - 1);
                                                    val = dscval;
                                                }
                                            } else if (obj['formatted'] != undefined && obj['formatted'] != null) {
                                                val = obj['formatted'];
                                            }

                                            //Se valida si es el campo número de socios y se muestra el array de socios cargados
                                            if (obj['update'] == 'partners') {
                                                val = "";//PARA QUE NO SE PINTE
                                                lbl = undefined;
                                            }


                                            var valid = obj['valid'];
                                            var filesvalid = lvlfields.split(",");
                                            if (lbl !== undefined && (filesvalid.indexOf(obj['update']) > -1)) addLineInf(cnt, id, lbl, val, valid);
                                        }
                                    } else {

                                    }
                                }
                            } else { //Si no es un objeto podemos buscar los valores
                                if (rsp[i][j][k]['update']) {
                                    var obj = rsp[i][j][k];
                                    if (obj['update']) {
                                        var id = obj['update'];
                                        var lbl = data[id];
                                        var val = "";
                                        if (obj['value'] != undefined && obj['value'] != null) {
                                            val = obj['value'];
                                        } else if (obj['number'] != undefined && obj['number'] != null) {
                                            val = obj['number'];
                                        } else if (obj['dsc'] != undefined && obj['dsc'] != null) {
                                            val = obj['dsc'];
                                            if (obj['update'] == 'prefertypeop') {
                                                var optypes = [{ "id": 1, "dsc": "Cripto - Cripto (C-C)" }, { "id": 2, "dsc": "Cripto - Dinero Fiat (C-DF)" },
                                                { "id": 3, "dsc": "Dinero Fiat - Cripto (DF-C)" }];
                                                var dscval = "";
                                                if (obj['id'] !== "" && obj['id'] != null) {
                                                    var ids = obj['id'].split("-");
                                                    for (var z = 0; z < optypes.length; z++) {
                                                        if (ids.indexOf((optypes[z].id).toString()) > -1) {
                                                            dscval += optypes[z].dsc + " /";
                                                        }
                                                    }
                                                }
                                                if (dscval != "") dscval = dscval.substring(0, dscval.length - 1);
                                                val = dscval;
                                            }
                                        } else if (obj['formatted'] != undefined && obj['formatted'] != null) {
                                            val = obj['formatted'];
                                        }
                                        //Se valida si es el campo número de socios y se muestra el array de socios cargados
                                        if (obj['update'] == 'partners') {
                                            val = "";//PARA QUE NO SE PINTE
                                            lbl = undefined;
                                        }

                                        var valid = obj['valid'];
                                        var filesvalid = lvlfields.split(",");
                                        if (lbl !== undefined && (filesvalid.indexOf(obj['update']) > -1)) addLineInf(cnt, id, lbl, val, valid);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (rsp.entry.type.id == 2 && lvl == 1) {//SE VALIDA SOLO SI ES JURÍDICO  
        if (rsp.entry.company.partners !== null) {
            //# SE PINTA EL NUMERO DE SOCIOS COMO VALOR PARTNERS
            var id = 'partners';
            var lbl = data[id];
            var val = "";
            if (rsp.entry.company.reppartner.value == "Si") {
                val = rsp.entry.company.partners.length;
            } else {
                val = rsp.entry.company.partners.length - 1;
            }
            var valid = rsp.entry.company.partnersnumber.valid;
            addLineInf(cnt, id, lbl, val, valid);


            if (rsp.entry.company.partners.length > 0) {   //SE VALIDA EL ARREGLO DE SOCIOS                                         
                var prtcnt = 0;
                var prnrid = "";
                (rsp.entry.company.partners).forEach(function (prtnr) { //SE RECORRE COMPLETO Y SE ARMAN LAS LINEAS    
                    var pref = 'prt';
                    prnrid = prtnr['id'];
                    if (prtnr['legalrep'].value == 1) pref = 'lg';
                    else prtcnt = prtcnt + 1;
                    var lbl = undefined;
                    var notreq = 'affiliationbody,positionheld,pepcountryid,peprelatedid';

                    //#NEW SE INDICA SI EL REPRESENTANTE LEGAL ES SOCIO O NO    
                    var id = 'reppartner';
                    var lbl = data[id];
                    var val = rsp.entry.company.reppartner.value;
                    var valid = rsp.entry.company.reppartner.valid;
                    if (pref == 'lg') addLineInf(cnt, id, lbl, val, valid);

                    for (let m in prtnr) {
                        var obj = prtnr[m];
                        var id = obj['update'];
                        if (prtnr['legalrep'].value == 1) {
                            lbl = data[pref + id];
                        } else {
                            lbl = data[pref + id] + "" + prtcnt;
                        }
                        if (id) {
                            var value = "";
                            if (obj['value'] != 'null' && obj['value'] != undefined) {
                                value = obj['value'];
                            } else if (obj['dsc'] != 'null' && obj['dsc'] != undefined) {
                                value = obj['dsc'];
                            }
                            var val = value + "_-*-_" + prnrid;//Lo concatenamos con el id del socio que nos permite identificarlo luego (para no adicionar otro par a la funcion)
                            var valid = obj['valid'];
                            if (obj['update'] !== 'legalrep') {
                                if (prtnr['politicalexposed'].value == "No" && !(notreq.indexOf(id) > -1)) {
                                    if (lbl !== undefined && (partnerfields.indexOf(id) > -1)) addLineInf(cnt, id, lbl, val, valid, "prtnr");
                                } else if (prtnr['politicalexposed'].value == "Si") {
                                    if (lbl !== undefined) addLineInf(cnt, id, lbl, val, valid, "prtnr");
                                } else if ((notreq.indexOf(id) == -1)) {
                                    if (lbl !== undefined && (partnerfields.indexOf(id) > -1)) addLineInf(cnt, id, lbl, val, valid, "prtnr");
                                }

                            }
                        }
                    }
                })
            }
        }
    }

    if (/*j=='declaration'*/true) {//Validamos siempre la declaración y los términos y condiciones fuera del person
        var id = 'declaration';
        var lbl = data[id];
        var val = "";
        if (rsp.entry.declaration != undefined && rsp.entry.declaration != null) {
            val = rsp.entry.declaration.value;
        }
        if (lbl !== undefined && (lvlfields.indexOf(id) > -1)) addLineInf(cnt, id, lbl, val, rsp.entry.declaration.valid);

        var id = 'terms';
        var lbl = data[id];
        var val = "";
        if (rsp.entry.terms != undefined && rsp.entry.terms != null) {
            val = rsp.entry.terms.value;
        }
        if (lbl !== undefined && (lvlfields.indexOf(id) > -1)) addLineInf(cnt, id, lbl, val, rsp.entry.terms.valid);
    }
}

function LoadLevels(sessionId) {
    req = {};
    req.sessionid = sessionId;
    callWS("GET", "levels/list", req, respuesta);
    function respuesta(status, rsp) {
        let resp = JSON.parse(rsp);
        var levelsFilter = document.getElementById("levelFilter");
        var msgError = document.getElementById("msgErrorLevelFilter");
        switch (status) {
            case 200:
                for (let i = 0; i < resp.numofrecords; i++) {
                    var option = document.createElement("option");
                    option.innerHTML = resp.records[i].name;
                    option.value = resp.records[i].id;
                    levelsFilter.appendChild(option);
                }
                break;

            case 400:
            case 403:
            case 500:

                break;

            case 401:
                myLogout();
                break;

            default:
                break;
        }
    }
}

function loadLevels(usrid = "", sel = "") {
    var parms = {};
    parms.sessionid = sessionStorage.getItem("sessionId");
    if (usrid !== "") parms.userid = usrid;
    var respuesta = function (status, rsp) {
        let resp = JSON.parse(rsp);
        switch (status) {
            case 200:
                var levelsList = document.getElementById("levelsList");
                levelsList.innerHTML = "";
                var selected = false;
                if (resp.records.length) {
                    for (let i = 0; i < resp.records.length; i++) {
                        var option = document.createElement("option");
                        option.innerHTML = resp.records[i].name;
                        option.value = resp.records[i].id;
                        if (sel == resp.records[i].id) {
                            option.setAttribute("selected", "");
                            selected = true;
                        }
                        levelsList.appendChild(option);
                    }
                    if (!selected) {
                        levelsList.options[levelsList.options.length - 1].setAttribute("selected", "");
                        updateSession(document.getElementById("saveEntryBtn").getAttribute("usrid"));
                    }
                }
                break;
            case 400:
            case 403:
            case 500:
                console.log(resp);
                break;
            case 401:
                myLogout();
                break;
            default:
                msg.style.display = "block";
                levelsList.disabled = true;
                setTimeout(function () {
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }
    callWS("GET", "appusers/levelslist", parms, respuesta);
}

function LoadLevelsList(type, id, sel, success = function () { }) {
    var sessionId = sessionStorage.getItem("sessionId");
    var levelsList = "";
    var msg = "";
    req = {};
    req.userid = id;
    if (type === 2) {
        levelsList = document.getElementById("levelLegal");
        msg = document.getElementById("errorLevelNat");
    } if (type === 1) {
        levelsList = document.getElementById("levelNatural");
        msg = document.getElementById("errorLevelLegal");
    }
    req.sessionid = sessionId;

    var respuesta = function (status, rsp) {
        let resp = JSON.parse(rsp);
        switch (status) {
            case 200:
                console.log(" resp.records ", resp.records);
                levelsList.innerHTML = "";
                var selected = false;
                if (resp.records.length) {
                    for (let i = 0; i < resp.records.length; i++) {
                        var option = document.createElement("option");
                        option.innerHTML = resp.records[i].name;
                        option.value = resp.records[i].id;
                        if (sel == resp.records[i].id) {
                            option.setAttribute("selected", "");
                            selected = true;
                        }
                        if (type === 2) {
                            option.classList.add("levelLegalOp")
                        } else {
                            option.classList.add("levelNaturalOp")
                        }
                        levelsList.appendChild(option);
                    }
                    if (!selected) {
                        levelsList.options[(levelsList.options.length - 1)].setAttribute("selected", "");
                    }
                    levelsList.disabled = false;
                }
                success();
                break;

            case 400:
            case 403:
            case 500:
                msg.style.display = "block";
                levelsList.disabled = true;
                setTimeout(function () {
                    msg.style.display = "none";
                }, 3000);

                break;

            case 401:
                myLogout();
                break;

            default:
                msg.style.display = "block";
                levelsList.disabled = true;
                setTimeout(function () {
                    msg.style.display = "none";
                }, 3000);
        }
    }

    callWS("GET", "appusers/levelslist", req, respuesta);
}
function LoadSessions(filter, range, status, level, offset, order, numofrecords, sessionid) {
    var par = {};
    par.filter = filter;
    par.range = range;

    if (status == 2) {
        par.reqverify = 1;
    } else {
        par.status = status;
    }
    par.level = level;
    par.offset = offset;
    var order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if (dir == "desc") order = "-" + order;
    par.order = order;
    par.numofrecords = numofrecords;
    par.sessionid = sessionid;
    pagerNumber = numofrecords;
    callWS("GET", "appusers/list", par, respuesta);
    function respuesta(status, rsp) {
        let resp = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                console.log("respuesta", resp);
                if (resp.numofrecords === 0) {
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noCurrencieDefine");
                    if (nodeNoDelete) {
                        var nodeClone = nodeNoDelete.cloneNode(true);
                        nodeClone.style.display = "none";
                    }
                    var table = document.getElementById("bodyTableCurrencies");
                    table.innerHTML = "";
                    if (nodeClone !== undefined && nodeClone !== null) table.appendChild(nodeClone);
                    /**-hasta aqui-**/
                    document.getElementById("noCurrencieDefine").style.display = "flex";
                    document.getElementById("msgInTable").innerHTML = "No hay sesiones definidas";
                    document.getElementById("paginator").style.display = "none";
                } else {

                    document.getElementById("listUserTbl").style.display = "";
                    document.getElementById("entryUserTbl").style.display = "none";
                    if (resp.numofrecords <= 10) {
                        document.getElementById("paginator").style.display = "none";
                    } else {
                        document.getElementById("paginator").style.display = "";
                        drawPags(resp.numofrecords, "numbersPaginator");
                    }
                    /*Blanquear tabla*/
                    var nodeNoDelete = document.getElementById("noCurrencieDefine");
                    if (nodeNoDelete) {
                        var nodeClone = nodeNoDelete.cloneNode(true);
                        nodeClone.style.display = "none";
                    }
                    var table = document.getElementById("bodyTableCurrencies");
                    table.innerHTML = "";
                    if (nodeClone !== undefined && nodeClone !== null) table.appendChild(nodeClone);
                    /**-hasta aqui- **/
                    //Pintar registros
                    paintRows(resp);


                }
                break;

            case 400:
                msg.innerHTML = resp.errmsg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                msg.innerHTML = "Sesi\u00F3n expirada o inv\u00E1lida, vuelva a iniciar sesi\u00F3n";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    myLogout();
                    msg.style.display = "none";
                }, 3000);
                break;

            case 403:
                msg.innerHTML = "No posee privilegio para ver sesiones";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                msg.innerHTML = "Error Interno";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            default:
                msg.innerHTML = resp.errmsg;
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
        }
    }
}

function paintRows(rows) {
    var pageInPaginator = document.getElementsByClassName("pSelect")[0];
    if (pageInPaginator) {
        pageInPaginator = pageInPaginator.innerHTML;
    }
    var rowCurrencie = document.getElementById("bodyTableCurrencies");
    var filas;
    if (rows.numofrecords > rows.records.length) {
        filas = parseInt(rows.numofrecords) - ((parseInt(pageInPaginator) - 1) * rows.records.length);
        if (filas > rows.records.length) {
            filas = rows.records.length;
        }
    } else {
        filas = rows.numofrecords;
    }
    for (let i = 0; i < filas; i++) {
        var divContent = document.createElement("div");
        var div0 = document.createElement("div");
        var div1 = document.createElement("div");
        var div2 = document.createElement("div");
        var div3 = document.createElement("div");
        var div4 = document.createElement("div");
        var div5 = document.createElement("div");
        var div6 = document.createElement("div");
        div0.classList.add("cell0");
        div1.classList.add("cell1");
        div2.classList.add("cell2");
        div3.classList.add("cell3");
        div4.classList.add("cell4");
        div5.classList.add("cell5");
        div6.classList.add("cell6");
        var divCnt0 = document.createElement("div");
        var divCnt1 = document.createElement("div");
        var divCnt2 = document.createElement("div");
        var divCnt3 = document.createElement("div");
        var divCnt4 = document.createElement("div");
        var divCnt5 = document.createElement("div");
        var divCnt6 = document.createElement("div");
        divCnt0.classList.add("divCellCnt");
        divCnt1.classList.add("divCellCnt");
        divCnt2.classList.add("divCellCnt");
        divCnt3.classList.add("divCellCnt");
        divCnt4.classList.add("divCellCnt");
        divCnt5.classList.add("divCellCnt");
        divCnt6.classList.add("divCellCnt");
        var inputEmail = document.createElement("span");
        var inputName = document.createElement("span");
        var inputSymbol = document.createElement("span");
        var inputStatus = document.createElement("span");
        var p = document.createElement("p");
        var p2 = document.createElement("p");
        var iconEdit = document.createElement("i");
        var p2fa = document.createElement("p");
        var iconEdit2fa = document.createElement("i");
        const index = i;

        iconEdit.classList.add("fas");
        iconEdit.classList.add("fa-eye");
        iconEdit.style.cursor = 'pointer';
        iconEdit.setAttribute("id", "iconEdit" + index);
        iconEdit.addEventListener("click", function () {
            OpenDetail(rows.records[i]);
        });

        p.setAttribute("id", "p" + index);
        p.appendChild(iconEdit);
        p.classList.add("iconVerCnt");
        divCnt5.appendChild(p);
        div5.appendChild(divCnt5);

        if (rows.records[i].login2fa == 1) {
            iconEdit2fa.classList.add("fas");
            iconEdit2fa.classList.add("fa-check-square");

            iconEdit2fa.style.cursor = 'pointer';
            iconEdit2fa.setAttribute("id", "icon2fa-" + index);
            iconEdit2fa.addEventListener("click", function () {
                OpenDeactivate2fa(rows.records[i].id, rows.records[i].usr, rows.records[i].fullname);
            });

            p2fa.setAttribute("id", "edit2fa-" + index);
            p2fa.appendChild(iconEdit2fa);
            divCnt6.appendChild(p2fa);
            div6.appendChild(divCnt6);
        }

        inputEmail.setAttribute("id", "inputName" + index);
        inputEmail.innerHTML = rows.records[i].usr;
        divCnt0.appendChild(inputEmail);
        div0.appendChild(divCnt0);

        inputName.disabled = true;
        //inputName.classList.add("inputRowCurrencie");
        inputName.setAttribute("id", "inputName" + index);
        if (rows.records[i].fullname) {
            inputName.innerHTML = rows.records[i].fullname;//rows.records[i].name + " " + rows.records[i].lastname.split(" ")[0];    
        }
        divCnt1.appendChild(inputName);
        div1.appendChild(divCnt1);

        inputSymbol.disabled = true;
        //inputSymbol.classList.add("inputRowCurrencie");
        inputSymbol.setAttribute("id", "inputSymbol" + index)
        inputSymbol.innerHTML = rows.records[i].lastsession.formatted;
        divCnt2.appendChild(inputSymbol);
        div2.appendChild(divCnt2);

        inputStatus.disabled = true;
        //inputStatus.classList.add("inputRowCurrencie");
        inputStatus.setAttribute("id", "inputStatus" + index);
        inputStatus.dataset.id = rows.records[i].level.id;
        inputStatus.innerHTML = rows.records[i].level.dsc;
        divCnt3.appendChild(inputStatus);
        div3.appendChild(divCnt3);

        /***CREAR SWITCH***/
        var cell, cont, swichBg, swichBal;
        cell = document.createElement("DIV"); cell.classList.add("switchCell");
        cont = document.createElement("DIV"); cont.classList.add("switchCont");
        swichBg = document.createElement("DIV"); swichBg.classList.add("switch");
        swichBg.setAttribute("id", "userStatus" + index);
        swichBal = document.createElement("DIV"); swichBal.classList.add("switchBal");
        if (rows.records[i].status.id == 1) {
            swichBg.classList.add("active");
            swichBal.classList.add("balActive");
        }
        swichBg.appendChild(swichBal);
        swichBg.addEventListener("click", function () {
            if (this.classList.contains("active")) {
                this.classList.remove("active");
                this.firstElementChild.classList.remove("balActive");
            } else {
                this.classList.add("active");
                this.firstElementChild.classList.add("balActive");
            }
            UpdateStatusRow("liSession" + index, this);
        });
        cont.appendChild(swichBg);
        cell.appendChild(cont);
        divCnt4.appendChild(cell);
        div4.appendChild(divCnt4);
        //div4.style.paddingLeft = "28px";

        divContent.classList.add("rowCurrencie");
        if (i % 2 === 0) {
            divContent.classList.add("rowImpar");
        }
        divContent.setAttribute("id", "liSession" + index);
        divContent.dataset.id = rows.records[i].id;

        var modified = rows.records[i].modified;
        div3.children[0].classList.add("divLvlCol");
        if (modified) {
            var modify = document.createElement("div");
            modify.classList.add("exclamation");
            modify.innerHTML = '<i class="fas fa-exclamation-circle"></i>';
            div3.children[0].appendChild(modify);
        }

        divContent.appendChild(div0);
        divContent.appendChild(div1);
        divContent.appendChild(div2);
        divContent.appendChild(div3);
        divContent.appendChild(div6);
        divContent.appendChild(div4);
        divContent.appendChild(div5);

        divContent.style.display = "table";
        divContent.style.width = "94%";

        rowCurrencie.appendChild(divContent);
    }

    for (let j = rows.records.length; j < 10; j++) {
        var divContent = document.createElement("div");
        var inputName = document.createElement("input");
        var inputSymbol = document.createElement("div");
        var inputStatus = document.createElement("div");
        const index = j;

        inputName.classList.add("inputRowCurrencie");
        inputSymbol.classList.add("inputRowCurrencie");
        inputStatus.classList.add("inputRowCurrencie");
        inputName.disabled = true;
        divContent.classList.add("rowCurrencie");
        if (j % 2 === 0) {
            divContent.classList.add("rowImpar");
        }
        divContent.appendChild(inputName);
        divContent.appendChild(inputSymbol);
        divContent.appendChild(inputStatus);
        divContent.style.display = "table";
        divContent.style.width = "94%";
        //divContent.style.cursor = "none";

        rowCurrencie.appendChild(divContent);
    }
}

var pagerNumber = 10;
function drawPags(numofrecords, tbl) {
    var sessionId = sessionStorage.getItem("sessionId");
    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;
            if (filter == null || filter == undefined) {
                filter = '';
            }
            LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, 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;
            if (filter == null || filter == undefined) {
                filter = '';
            }
            LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, 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;
            if (filter == null || filter == undefined) {
                filter = '';
            }
            LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, 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;
                    if (filter == null || filter == undefined) {
                        filter = '';
                    }
                    LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, 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;
                    if (filter == null || filter == undefined) {
                        filter = '';
                    }
                    LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, offset, order, document.getElementById("registerFilter").value, sessionId);
                }
            }
        });
        numbersPaginator.setAttribute("arrowsEvent", true);
    }


}
function OpenDeactivate2fa(userId, email, name) {
    document.getElementById("dataDeactivate").innerHTML = '<span style="font-weight:bold">' + email + '</span><br>' + name;
    var modalConfirm = document.getElementById("modalConfirm");
    modalConfirm.style.display = "table";
    document.getElementById("buttonCancelModal").addEventListener("click", function () {
        modalConfirm.style.display = "none";
    });
    document.getElementById("closeModal").addEventListener("click", function () {
        modalConfirm.style.display = "none";
    });
    document.getElementById("buttonAceptModal").addEventListener("click", function () {
        deactivate2FA(userId);
    });
}

function deactivate2FA(id) {
    var req = {
        'sessionid': sessionStorage.getItem("sessionId"),
        'usrid': id
    }

    callWS('GET', 'login2fa/deactivate', req, response);

    function response(status, rsp) {
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                location.reload();
                break;
            case 400:
                break;
            case 401:
                document.getElementById("modalConfirm").style.display = "none";
                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;
                break;
            case 500:
                break;
            default:
                break;
        }
    }
}
function OpenDetail(row) {
    var sessionId = sessionStorage.getItem("sessionId");
    req.id = row.id;
    callWS("GET", "appusers/entry", req, respuesta);
    function respuesta(status, rsp) {
        let resp = JSON.parse(rsp);
        var msg = document.getElementById("messageApi");
        switch (status) {
            // Success
            case 200:
                document.getElementById("entryUserTbl").style.display = "";
                document.getElementById("listUserTbl").style.display = "none";


                //Etiquetas se blanquea primero y luego de pintan
                var tags = document.getElementById("entryTragsCnt").getElementsByClassName("tag");
                for (var i = 0; i < tags.length; i++) {
                    tags[i].parentElement.removeChild(tags[i]);
                }
                drawTags(document.getElementById("entryTragsCnt"), resp.entry.tags);

                upsess = false;
                document.getElementById("riskLevel").removeAttribute("disabled");
                document.getElementById("usrStatus").style.pointerEvents = "";
                document.getElementById("levelsList").removeAttribute("disabled");
                if (!resp.privileges.updateuser) {
                    upsess = true; loadupd = true;
                    document.getElementById("riskLevel").setAttribute("disabled", "");
                    document.getElementById("usrStatus").style.pointerEvents = "none";
                    document.getElementById("levelsList").setAttribute("disabled", "");
                    document.getElementById("entryTragsCnt").getElementsByTagName("input")[1].setAttribute("disabled", "");
                }

                validsess = false;
                document.getElementsByClassName("tablinksLvls")[5].parentElement.style.display = "";
                if (!resp.privileges.validateuser) {
                    validsess = true; loadvalid = true;
                }
                //DRAW INTERCAMBIOS EXONERACIONES
                xchexn = false;
                if (resp.privileges.readxchgfees) {
                    if (!resp.privileges.updatexchgfees) {//Si no tiene los privilegios se enciende esto y no entra en el ciclo de guardar y salta al otro paso
                        xchexn = true; loadxch = true;
                    }
                    paintFeesPairs(resp.pairs);
                } else {
                    xchexn = true; loadxch = true;
                    document.getElementsByClassName("tablinksLvls")[5].parentElement.style.display = "none";
                }
                //DRAW PORTAFOLIOS
                portexn = false;
                document.getElementsByClassName("tablinksLvls")[6].parentElement.style.display = "";
                if (resp.privileges.readportfoliofees) {
                    if (!resp.privileges.updateportfoliofees) {
                        portexn = true; loadport = true;
                    }
                    paintFeesCurr(resp.currencies);
                } else {
                    portexn = true; loadport = true;
                    document.getElementsByClassName("tablinksLvls")[6].parentElement.style.display = "none";
                }

                for (type of resp.entry.paymentstothirdsparty) {
                    if (type.pagomovil != undefined) {
                        //Seteamos el pago a tercero
                        if (!resp.privileges.updatepaythirdsparty || resp.entry.level.id <= 0) {
                            paythirds = true; loadpayt = true;
                            document.getElementById("switchPm").setAttribute("disabled", "");
                        } else {
                            paythirds = false; loadpayt = false;
                            document.getElementById("switchPm").removeAttribute("disabled");
                        }
                        if (type.pagomovil) {
                            document.getElementById("switchPm").classList.add("active");
                            document.getElementById("switchPm").firstElementChild.classList.add("balActive");
                        } else {
                            document.getElementById("switchPm").classList.remove("active");
                            document.getElementById("switchPm").firstElementChild.classList.remove("balActive");
                        }
                    } else {
                        paythirds = true; loadpayt = true;
                    }
                }


                document.getElementById("usrEmail").innerHTML = resp.entry.usr;
                document.getElementById("lastSessionUsr").innerHTML = resp.entry.lastsession;
                var name = "";
                var iniLvl = 0;
                if (resp.entry.type.id == 1) {
                    iniLvl = 0;
                    name = resp.entry.person.firstname.value + " " + resp.entry.person.firstlastname.value;
                    var tabLinks = document.getElementsByClassName("tablinksLvls");//Se oculta el nivel inicial porque no hace falta
                    if (tabLinks.length > 0) tabLinks[0].parentElement.style.display = "";
                } else {
                    iniLvl = 1;
                    name = resp.entry.company.name.value;
                    var tabLinks = document.getElementsByClassName("tablinksLvls");
                    if (tabLinks.length > 0) tabLinks[0].parentElement.style.display = "none";
                }
                document.getElementById("usrFullName").innerHTML = name;
                document.getElementById("riskLevel").value = resp.entry.risklevel.id;
                if (resp.entry.status.id) {
                    document.getElementById("usrStatus").classList.add("active");
                    document.getElementById("usrStatus").firstElementChild.classList.add("balActive");
                } else {
                    document.getElementById("usrStatus").classList.remove("active");
                    document.getElementById("usrStatus").firstElementChild.classList.remove("balActive");
                }
                drawEntry('0.5', resp);
                drawEntry('1', resp);
                drawEntry('2', resp);
                drawEntry('3', resp);
                var rsp = resp; //Se pintan las cuentas siguiendo el mismo formato del draw entry prtnrs
                blankEntry(document.getElementById("tblAccounts"));
                if (rsp.entry.accounts !== "" && rsp.entry.accounts !== null) {
                    if (rsp.entry.accounts.length > 0) {   //SE VALIDA EL ARREGLO DE CUENTAS    
                        var acccnt = 0;
                        var accid = "";
                        (rsp.entry.accounts).forEach(function (account) { //SE RECORRE COMPLETO Y SE ARMAN LAS LINEAS   
                            accid = account.id;
                            for (let m in account) {
                                var first = "";
                                if (m.indexOf('details') > -1) {
                                    if (m.indexOf('details1') > -1) {
                                        first = account.paymentmethod.name + " (" + account.currency.symbol + ")";
                                    }
                                    lbl = account.paymentmethod[m];
                                    val = account[m].value + "_-*-_" + accid;//Lo concatemos con el id del socio que nos permite identificarlo luego (para no adicionar otro par a la funcion)
                                    valid = account[m].valid;
                                    if (lbl != null && lbl !== undefined)
                                        addLineAcc(document.getElementById("tblAccounts"), m, lbl, val, valid, first);
                                }
                            }
                        })
                    }
                }
                loadLevels(resp.entry.id, resp.entry.level.id);
                //SE MARCA EL NIVEL INICIAL 
                var tabLinks = document.getElementsByClassName("tablinksLvls");
                if (tabLinks.length > 0) tabLinks[iniLvl].dispatchEvent(new Event("click"));


                break;

            //rsp.errmsg
            case 400:
                console.log("status ", status, " resp ", rsp);
                break;

            //Sesion Invalida
            case 401:
                console.log("status ", status, " resp ", rsp);
                break;

            // No posee Privilegios
            case 403:
                console.log("status ", status, " resp ", rsp);
                break;

            // Sesion no encontrada
            case 404:
                console.log("status ", status, " resp ", rsp);
                break;

            // Error Interno
            case 500:
                console.log("status ", status, " resp ", rsp);
                break;
        }
    }

}
function paintFeesCurr(data) {
    var tbl = document.getElementById("tblExnPortfolio");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data;
    var nwnode;

    if (levels.length > 0) {
        tbl.innerHTML = "";
        clone.style.display = "";
        nwnode = clone.cloneNode(true);
        var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
        currcnt.innerHTML = "";

        //PINTAR ETIQUETAS DE LA MONEDA
        for (var i = 0; i < levels.length; i++) {
            var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
            var span = document.createElement("span");
            span.innerHTML = levels[i].symbol;
            span.setAttribute("id", i + "currency");
            span.setAttribute("currid", levels[i].id);
            span.setAttribute("basedecim", '2');
            maxbar.appendChild(span);
            currcnt.appendChild(maxbar);
        }
        //LINEA DEPOSITO, RETIROS, TRANSFERENCIAS
        for (var x = 0; x < 3; x++) {
            var nml = nwnode.getElementsByClassName("maxBars6")[x];
            var nmlCnt = nml.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            var pct = nwnode.getElementsByClassName("maxBars6")[x];
            var pctCnt = pct.getElementsByClassName("dualbar")[1].getElementsByClassName("maxLineBar")[0];
            nmlCnt.innerHTML = ""; pctCnt.innerHTML = "";

            var exn = nwnode.getElementsByClassName("maxBars5")[x];
            var exnCnt = exn.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            exnCnt.innerHTML = "";
            var ntot = nwnode.getElementsByClassName("maxBars4")[x];
            var totCnt = ntot.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            totCnt.innerHTML = "";
            for (var i = 0; i < levels.length; i++) {
                var tot = 0;
                var field = "";//Campo que se exonera
                var exonerated = "";//Monto exonerado si existe. 
                //COMISION NOMINAL Y PORCENTUAL
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                input.setAttribute("disabled", "");
                input.setAttribute("id", i + "pctFee" + x);
                switch (x) {
                    case 0:
                        if (levels[i].fees.deposits.pctfee) {
                            input.value = levels[i].fees.deposits.pctfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.deposits.pctfee.number);
                            tot = levels[i].fees.deposits.pctfee.number;
                            field = levels[i].fees.deposits.pctfee.field;
                            if (levels[i].fees.deposits.pctfee.exonerated) {
                                exonerated = levels[i].fees.deposits.pctfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                    case 1:
                        if (levels[i].fees.withdrawals.pctfee) {
                            input.value = levels[i].fees.withdrawals.pctfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.withdrawals.pctfee.number);
                            tot = levels[i].fees.withdrawals.pctfee.number;
                            field = levels[i].fees.withdrawals.pctfee.field;
                            if (levels[i].fees.withdrawals.pctfee.exonerated) {
                                exonerated = levels[i].fees.withdrawals.pctfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                    case 2:
                        if (levels[i].fees.xfer.pctfee) {
                            input.value = levels[i].fees.xfer.pctfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.xfer.pctfee.number);
                            tot = levels[i].fees.xfer.pctfee.number;
                            field = levels[i].fees.xfer.pctfee.field;
                            if (levels[i].fees.xfer.pctfee.exonerated) {
                                exonerated = levels[i].fees.xfer.pctfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                }
                maxbar.appendChild(input);
                nmlCnt.appendChild(maxbar);
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                input.setAttribute("disabled", "");
                input.setAttribute("id", i + "nmlFee" + x);
                switch (x) {
                    case 0:
                        if (levels[i].fees.deposits.nmalfee) {
                            input.value = levels[i].fees.deposits.nmalfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.deposits.nmalfee.number);
                            tot = levels[i].fees.deposits.nmalfee.number;
                            field = levels[i].fees.deposits.nmalfee.field;
                            if (levels[i].fees.deposits.nmalfee.exonerated) {
                                exonerated = levels[i].fees.deposits.nmalfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                    case 1:
                        if (levels[i].fees.withdrawals.nmalfee) {
                            input.value = levels[i].fees.withdrawals.nmalfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.withdrawals.nmalfee.number);
                            tot = levels[i].fees.withdrawals.nmalfee.number;
                            field = levels[i].fees.withdrawals.nmalfee.field;
                            if (levels[i].fees.withdrawals.nmalfee.exonerated) {
                                exonerated = levels[i].fees.withdrawals.nmalfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                    case 2:
                        if (levels[i].fees.xfer.nmalfee) {
                            input.value = levels[i].fees.xfer.nmalfee.formatted;
                            field = levels[i].fees.xfer.nmalfee.field;
                            input.setAttribute("datanumber", levels[i].fees.xfer.nmalfee.number);
                            tot = levels[i].fees.xfer.nmalfee.number;
                            if (levels[i].fees.xfer.nmalfee.exonerated) {
                                exonerated = levels[i].fees.xfer.nmalfee.exonerated;
                            }
                        } else {
                            input.value = "";
                        }
                        break;
                }
                maxbar.appendChild(input);
                pctCnt.appendChild(maxbar);
                //EXONERACIÓN
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                input.setAttribute("id", i + "portExon" + x);
                input.setAttribute("field", field);
                input.addEventListener("change", function () {
                    if (this.value > 100 || this.value < 0) {
                        this.value = "";
                    }
                    var pos = this.getAttribute("id");
                    var posarr = [];
                    posarr = pos.split("portExon");
                    var tot = 0;
                    var pct = ""; nml = "";
                    pct = document.getElementById(posarr[0] + "pctFee" + posarr[1]).getAttribute("datanumber");
                    nml = document.getElementById(posarr[0] + "nmlFee" + posarr[1]).getAttribute("datanumber");
                    if (pct != "" && pct != null && pct != undefined) {
                        tot = pct;
                    } else {
                        tot = nml;
                    }

                    if (this.value != "") tot = (tot - (tot * (this.value / 100)));
                    document.getElementById(posarr[0] + ("totPort") + posarr[1]).setAttribute("datanumber", tot);
                    var decim = (tot.toString()).split(".");
                    if (decim.length > 1) decim = decim[1].length + 1;
                    else decim = 2;

                    document.getElementById(posarr[0] + ("totPort") + posarr[1]).value = number_format(tot, decim);
                });
                if (exonerated != "") {
                    input.setAttribute("datanumber", exonerated.number);
                    input.value = exonerated.formatted;
                }
                if (portexn) {
                    input.setAttribute("disabled", "");
                }
                input.classList.add("portfolioExn");
                maxbar.appendChild(input);
                exnCnt.appendChild(maxbar);
                //ORDEN TOTAL
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                var exon = 0;
                if (exonerated != "") exon = exonerated.number;

                var decim = (tot.toString()).split(".");
                if (decim.length > 1) decim = decim[1].length + 1;
                else decim = 2;

                if (tot != "") tot = (tot - (tot * (exon / 100)));
                input.setAttribute("datanumber", tot);
                input.setAttribute("id", i + "totPort" + x);
                input.setAttribute("disabled", "");
                input.value = number_format(tot, decim);
                maxbar.appendChild(input);
                totCnt.appendChild(maxbar);
            }

            tbl.appendChild(nwnode);
        }
        //Se recorren los campos y se les da formato y funcionamiento
        var fds = nwnode.getElementsByTagName("input");
        var list = [];
        for (var y = 0; y < fds.length; y++) {
            fds[y].setAttribute("type", "text");
            list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto
            fds[y].addEventListener("keydown", function (e) {
                if (e.keyCode == 13) {
                    this.dispatchEvent(new Event("focusout"));
                    this.dispatchEvent(new Event("focusin"));
                    this.dispatchEvent(new Event("change"));
                }
            });


        }
        formatAmount(list);
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
function paintFeesPairs(data) {
    var tbl = document.getElementById("tblExnExch");
    //Utilizo siempre el registro inicial para pintar los demás bloques.
    var clone = tbl.children[0].cloneNode(true);
    var levels = data;
    var nwnode;

    if (levels.length > 0) {
        tbl.innerHTML = "";
        clone.style.display = "";
        nwnode = clone.cloneNode(true);
        var currcnt = nwnode.getElementsByClassName("currencybars1")[0];
        currcnt.innerHTML = "";

        //PINTAR ETIQUETAS DEL PAR
        for (var i = 0; i < levels.length; i++) {
            var maxbar = document.createElement("div"); maxbar.classList.add("currencyTab");
            var span = document.createElement("span");
            span.innerHTML = levels[i].name;
            span.setAttribute("id", i + "currencyPair");
            span.setAttribute("pairid", levels[i].id);
            span.setAttribute("basedecim", '2');
            maxbar.appendChild(span);
            currcnt.appendChild(maxbar);
        }
        //LINEA MARKET Y LIMITE
        for (var x = 0; x < 2; x++) {
            var tOrden = nwnode.getElementsByClassName("maxBars6")[x];
            var tOrdenCnt = tOrden.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            tOrdenCnt.innerHTML = "";
            var exn = nwnode.getElementsByClassName("maxBars5")[x];
            var exnCnt = exn.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            exnCnt.innerHTML = "";
            var ntot = nwnode.getElementsByClassName("maxBars4")[x];
            var totCnt = ntot.getElementsByClassName("dualbar")[0].getElementsByClassName("maxLineBar")[0];
            totCnt.innerHTML = "";
            for (var i = 0; i < levels.length; i++) {
                var exonerated = "";
                var tot = 0;
                //COMISIÓN
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                input.setAttribute("disabled", "");
                switch (x) {
                    case 0:

                        input.setAttribute("id", (i + "lmtPct"));
                        if (levels[i].fees.limit.pctfee) {
                            input.value = levels[i].fees.limit.pctfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.limit.pctfee.number);
                            field = levels[i].fees.limit.pctfee.field;
                            if (levels[i].fees.limit.pctfee.exonerated) {
                                exonerated = levels[i].fees.limit.pctfee.exonerated;
                            }
                            tot = levels[i].fees.limit.pctfee.number;
                            if (exonerated != "") tot = (tot - (tot * (exonerated.number / 100)));
                        } else {
                            input.value = "";
                        }
                        break;
                    case 1:
                        input.setAttribute("id", (i + "mktPct"));
                        if (levels[i].fees.market.pctfee) {
                            input.value = levels[i].fees.market.pctfee.formatted;
                            input.setAttribute("datanumber", levels[i].fees.market.pctfee.number);
                            field = levels[i].fees.market.pctfee.field;
                            if (levels[i].fees.market.pctfee.exonerated) {
                                exonerated = levels[i].fees.market.pctfee.exonerated;
                            }
                            tot = levels[i].fees.market.pctfee.number;
                            if (exonerated != "") tot = (tot - (tot * (exonerated.number / 100)));
                        } else {
                            input.value = "";
                        }
                        break;
                }
                maxbar.appendChild(input);
                tOrdenCnt.appendChild(maxbar);
                //EXONERACIÓN
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("lvlpos", i);
                input.setAttribute("id", (i + "xchExnPct" + x));
                if ((i + 1) == levels.length) {
                    input.addEventListener("keydown", function (e) {
                        if (e.keyCode == 9) {
                            e.preventDefault();
                        }
                    });
                }
                input.addEventListener("change", function () {
                    if (this.value > 100 || this.value < 0) {
                        this.value = "";
                    }
                    var pos = this.getAttribute("id");
                    var posarr = [];
                    posarr = pos.split("xchExnPct");
                    var tot = 0;
                    if (posarr[1] == 0) {
                        tot = document.getElementById(posarr[0] + ("lmtPct")).getAttribute("datanumber");
                    } else {
                        tot = document.getElementById(posarr[0] + ("mktPct")).getAttribute("datanumber");
                    }
                    if (this.value != "") tot = (tot - (tot * (this.value / 100)));
                    document.getElementById(posarr[0] + ("xchTotPct") + posarr[1]).setAttribute("datanumber", tot);
                    document.getElementById(posarr[0] + ("xchTotPct") + posarr[1]).value = number_format(tot, 2);
                });
                if (exonerated != "") {
                    input.setAttribute("datanumber", exonerated.number);
                    input.value = number_format(exonerated.number, 0);
                }
                if (xchexn) {
                    input.setAttribute("disabled", "");
                }
                input.classList.add("xchExn");
                input.setAttribute("field", field);
                maxbar.appendChild(input);
                exnCnt.appendChild(maxbar);
                //ORDEN TOTAL
                var maxbar = document.createElement("div"); maxbar.classList.add("maxBar");
                var input = document.createElement("input");
                input.setAttribute("id", (i + "xchTotPct" + x));
                input.value = number_format(tot, 2);
                input.setAttribute("disabled", "");
                input.setAttribute("datanumber", tot);
                maxbar.appendChild(input);
                totCnt.appendChild(maxbar);
            }

            tbl.appendChild(nwnode);
        }
        //Se recorren los campos y se les da formato y funcionamiento
        var fds = nwnode.getElementsByTagName("input");
        var list = [];
        for (var y = 0; y < fds.length; y++) {
            fds[y].setAttribute("type", "text");
            list.push(fds[y].getAttribute("id")); //Se inserta al arreglo para dar formato de monto
            fds[y].addEventListener("keydown", function (e) {
                if (e.keyCode == 13) {
                    this.dispatchEvent(new Event("focusout"));
                    this.dispatchEvent(new Event("focusin"));
                    this.dispatchEvent(new Event("change"));
                }
            });


        }
        formatAmount(list);
    } else {
        //Si no hay registros se blanquea pero se deja oculto el nodo de referencia
        nwnode = clone.cloneNode(true);
        nwnode.style.display = "none";
        tbl.innerHTML = "";
        tbl.appendChild(nwnode);
    }
}
//Esta funcion recorre los las columnas de iconos validando si ya tiene texto asignado si no eliminar los 3 colores
function blankEmpty() {
    var validCols = document.getElementsByClassName("validCol");
    for (var i = 0; i < validCols.length; i++) {
        var posval = 2;
        var win = validCols[i].parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id;
        var blank = true;

        if (win == 'retirement-accounts' || win == 'accounts-legal') {
            posval = 3;
        } else if (win == 'support-images' || win == 'images-data-legal' || win == "") {
            blank = false;
        }

        //Si el texto del valor está vacío y es válida blanquear esa pantalla se ejecuta
        //if(validCols[i].parentElement.children[posval].children[0]==null);
        if (blank) {
            if (validCols[i].parentElement.children[posval].children[0].textContent.trim() == "") {
                //Remueve la clase del coloreado
                validCols[i].children[0].classList.remove("fas");
                validCols[i].children[1].classList.remove("fas");
                validCols[i].children[2].classList.remove("fas");
                //Quita el color
                validCols[i].children[0].style.color = "";
                validCols[i].children[1].style.color = "";
                validCols[i].children[2].style.color = "";
                //Agrega la clase tipo vacío
                validCols[i].children[0].classList.add("far");
                validCols[i].children[1].classList.add("far");
                validCols[i].children[2].classList.add("far");
            }
        }
    }
}
function openTabInNaturalModal(ele) {
    var i, tabcontent, tablinks;
    var actTab = document.getElementById(ele.dataset.name);
    tabcontent = document.getElementsByClassName("tabcontentNatural");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    actTab.style.display = "table";
    tablinks = document.getElementsByClassName("tablinksNatural");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].parentNode.classList.remove("activeTab");
    }
    ele.parentNode.classList.add("activeTab");
}

function openTabInLegalModal(ele) {
    var i, tabcontent, tablinks;
    var actTab = document.getElementById(ele.dataset.name);

    tabcontent = document.getElementsByClassName("tabcontentLegal");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    actTab.style.display = "table";
    tablinks = document.getElementsByClassName("tablinksLegal");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].parentNode.classList.remove("activeTab");
    }
    ele.parentNode.classList.add("activeTab");
}

function updtPortfolioExn(id) {
    var req = {}
    req.userid = id;
    //Primero se recorren los campos de exoneraciones aver cuales se envían
    var portExn = document.getElementsByClassName("portfolioExn");
    var fields = "";
    var currs = "";
    var amos = "";
    for (var i = 0; i < portExn.length; i++) {
        if (portExn[i].getAttribute("datanumber") != 'NaN' &&
            portExn[i].getAttribute("datanumber") != '' &&
            portExn[i].getAttribute("datanumber") != null) {
            amos += portExn[i].getAttribute("datanumber") + "-";
            var pos = portExn[i].getAttribute("id");
            var posarr = [];
            posarr = pos.split("portExon");
            currs += document.getElementById(posarr[0] + "currency").getAttribute("currid") + "-";
            fields += portExn[i].getAttribute("field") + "|";
        }
    }
    amos = amos.substr(0, amos.length - 1);
    currs = currs.substr(0, currs.length - 1);
    fields = fields.substr(0, fields.length - 1);
    req.currencyids = currs;
    req.exonerated = amos;
    req.preffeefields = fields;
    req.sessionid = sessionStorage.getItem("sessionId");
    var respuesta = function (status, rsp) {
        if (rsp) {
            var resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("errorEntryCnt");
        loadport = true;
        switch (status) {
            case 200:
            case 304:
                break;
            case 204:
            case 400:
                msg.classList.add("msgError");
                msg.innerHTML = resp.msg;
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 401:
                myLogout();
                break;
            case 403:
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar las exoneraciones del portafolio";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 409:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 500:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }
    if (req.currencyids != '')
        callWS("GET", "appusers/portfolioexn", req, respuesta);
    else {
        portexn = true;
        loadport = true;
    }
}

function updtExchageExn(id) {
    var req = {}
    req.userid = id;
    //Primero se recorren los campos de exoneraciones aver cuales se envían
    var xchExn = document.getElementsByClassName("xchExn");
    var fields = "";
    var pairids = "";
    var amos = "";
    for (var i = 0; i < xchExn.length; i++) {
        if (xchExn[i].getAttribute("datanumber") != 'NaN' &&
            xchExn[i].getAttribute("datanumber") != '' &&
            xchExn[i].getAttribute("datanumber") != null) {
            amos += xchExn[i].getAttribute("datanumber") + "-";
            var pos = xchExn[i].getAttribute("id");
            var posarr = [];
            posarr = pos.split("xchExnPct");
            pairids += document.getElementById(posarr[0] + "currencyPair").getAttribute("pairid") + "-";
            fields += xchExn[i].getAttribute("field") + "|";
        }
    }
    if (amos !== "") amos = amos.substr(0, amos.length - 1);
    if (pairids !== "") pairids = pairids.substr(0, pairids.length - 1);
    if (fields !== "") fields = fields.substr(0, fields.length - 1);
    req.pairids = pairids;
    req.exonerated = amos;
    req.preffeefields = fields;
    req.sessionid = sessionStorage.getItem("sessionId");
    var respuesta = function (status, rsp) {
        if (rsp) {
            var resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("errorEntryCnt");
        loadxch = true;
        switch (status) {
            case 200:
            case 304:

                break;
            case 204:
            case 400:
                msg.classList.add("msgError");
                msg.innerHTML = resp.msg;
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 401:
                myLogout();
                break;
            case 403:
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar las exoneraciones del portafolio";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 409:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 500:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }
    if (req.pairids != '')
        callWS("GET", "appusers/xchangeexn", req, respuesta);
    else {
        xchexn = true;
        loadxch = true;
    }
}

function updtPayThirds(id) {
    var req = {}
    req.userid = id;
    req.pagomovil = (document.getElementById("switchPm").classList.contains("active")) ? 1 : 0;
    req.sessionid = sessionStorage.getItem("sessionId");
    console.log("rquest");
    var respuesta = function (status, rsp) {
        if (rsp) resp = JSON.parse(rsp);
        var msg = document.getElementById("errorEntryCnt");
        switch (status) {
            case 200:
            case 304:
                break;
            case 204:
            case 400:
                msg.classList.add("msgError");
                msg.innerHTML = resp.msg;
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 401:
                myLogout();
                break;
            case 403:
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar los pagos a terceros";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 409:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
            case 500:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }

    loadpayt = true;
    callWS("POST", "appusers/paymentstothirdsparty", req, respuesta);
}

function updateSession(id) {
    var req = {};
    req.id = id;
    req.level = document.getElementById("levelsList").value;
    var status = -1;
    var stEle = document.getElementById("usrStatus");
    if (stEle.classList.contains("active")) {
        status = 1;
    } else {
        status = 0;
    }

    req.status = status;
    req.risklevel = document.getElementById("riskLevel").value;
    req.sessionid = sessionStorage.getItem("sessionId");
    var tagBar = document.getElementsByClassName("tagInptEle");
    var parmTag = "";
    if (tagBar.length > 0) {
        var tags = tagBar[0].getElementsByClassName("tag");
        for (var i = 0; i < tags.length; i++) {
            parmTag += tags[i].getAttribute("data-tag") + " ";
        }
        parmTag = parmTag.substr(0, parmTag.length - 1);
    }
    if (parmTag !== "") req.tags = parmTag;
    var respuesta = function (status, rsp) {
        if (rsp) {
            let resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("errorEntryCnt");
        switch (status) {
            case 200:
            case 304:
                loadupd = true;
                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n actualizada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);
                break;

            case 204:
            case 400:
                if (req.status == 0 && stEle.classList.contains("active")) {
                    stEle.classList.remove("active")
                } else if (req.status == 1 && !(stEle.classList.contains("active"))) {
                    stEle.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = resp.errmsg;
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                if (req.status == 0 && stEle.classList.contains("active")) {
                    stEle.classList.remove("active")
                } else if (req.status == 1 && !(stEle.classList.contains("active"))) {
                    stEle.classList.add("active")
                }
                myLogout();
                break;

            case 403:
                if (req.status == 0 && stEle.classList.contains("active")) {
                    stEle.classList.remove("active")
                } else if (req.status == 1 && !(stEle.classList.contains("active"))) {
                    stEle.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar la sesi\u00F3n";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 409:
                if (req.status == 0 && stEle.classList.contains("active")) {
                    stEle.classList.remove("active")
                } else if (req.status == 1 && !(stEle.classList.contains("active"))) {
                    stEle.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                if (req.status == 0 && stEle.classList.contains("active")) {
                    stEle.classList.remove("active")
                } else if (req.status == 1 && !(stEle.classList.contains("active"))) {
                    stEle.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }
    callWS("GET", "appusers/update", req, respuesta);
}

function UpdateStatusRow(idLi, ele) {
    var sessionId = sessionStorage.getItem("sessionId");
    var iLi = idLi.replace("liSession", "");
    var li = document.getElementById(idLi);
    var level = document.getElementById("inputStatus" + iLi).dataset.id;
    var status = -1;
    if (ele.classList.contains("active")) {
        status = 1;
    } else {
        status = 0;
    }

    req = {};
    req.id = li.dataset.id;
    req.level = level;
    req.status = status;
    req.risklevel = '';
    req.sessionid = sessionId;

    callWS("GET", "appusers/update", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp) {
            let resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n actualizada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);
                break;

            case 204:
            case 400:
                if (req.status == 0 && ele.classList.contains("active")) {
                    ele.classList.remove("active")
                } else if (req.status == 1 && !(ele.classList.contains("active"))) {
                    ele.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = resp.errmsg;
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                if (req.status == 0 && ele.classList.contains("active")) {
                    ele.classList.remove("active")
                } else if (req.status == 1 && !(ele.classList.contains("active"))) {
                    ele.classList.add("active")
                }
                myLogout();
                break;

            case 403:
                if (req.status == 0 && ele.classList.contains("active")) {
                    ele.classList.remove("active")
                } else if (req.status == 1 && !(ele.classList.contains("active"))) {
                    ele.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar la sesi\u00F3n";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 409:
                if (req.status == 0 && ele.classList.contains("active")) {
                    ele.classList.remove("active")
                } else if (req.status == 1 && !(ele.classList.contains("active"))) {
                    ele.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                if (req.status == 0 && ele.classList.contains("active")) {
                    ele.classList.remove("active")
                } else if (req.status == 1 && !(ele.classList.contains("active"))) {
                    ele.classList.add("active")
                }
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }
    }
}

// Tab 'Status' Modal Legal Person
function paintTabStatusLegal(rsp) {
    var dataCompany = rsp.entry;
    var status = dataCompany.status.id;
    var level = dataCompany.level.id;

    if (status === 1) {
        if (!document.getElementById("swichtStatusLegal").classList.contains("active")) {
            document.getElementById("swichtStatusLegal").classList.add("active");
            document.getElementById("swichtStatusLegal").firstElementChild.classList.add("balActive");
        }
    } else {
        if (document.getElementById("swichtStatusLegal").classList.contains("active")) {
            document.getElementById("swichtStatusLegal").classList.remove("active");
            document.getElementById("swichtStatusLegal").firstElementChild.classList.remove("balActive");
        }
    }

    var levelLegal = document.getElementById("levelLegal");
    levelLegal.value = level;
}

// Tab 'Basic Data' Modal Legal Person
function paintTabDataBasicLegal(rsp) {
    var bd = document.getElementById("basic-data-legal").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }


    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    var dataCompany = rsp.entry.company;
    // Venezuelan
    var validVenezuelan = dataCompany.venezuelan.valid;
    var venezuelanLegal = document.getElementById("venezuelanLegal");
    if (dataCompany.venezuelan.value !== "") {
        if (validVenezuelan === 0) {
            document.getElementById("venezuelanLegalPending").classList.remove("far");
            document.getElementById("venezuelanLegalPending").classList.add("fas");
            document.getElementById("venezuelanLegalPending").dataset.updateLbl = dataCompany.venezuelan.update + "-pending";
            document.getElementById("venezuelanLegalPending").style.color = colorPending;
        } else if (validVenezuelan === 1) {
            document.getElementById("venezuelanLegalValid").classList.remove("far");
            document.getElementById("venezuelanLegalValid").classList.add("fas");
            document.getElementById("venezuelanLegalValid").dataset.updateLbl = dataCompany.venezuelan.update + "-valid";
            document.getElementById("venezuelanLegalValid").style.color = colorValid;
        } else if (validVenezuelan === -1) {
            document.getElementById("venezuelanLegalRejected").classList.remove("far");
            document.getElementById("venezuelanLegalRejected").classList.add("fas");
            document.getElementById("venezuelanLegalRejected").dataset.updateLbl = dataCompany.venezuelan.update + "-invalid";
            document.getElementById("venezuelanLegalRejected").style.color = colorRejected
        }
        var venezuelan = dataCompany.venezuelan.value;

        if (venezuelan === 1) {
            venezuelanLegal.innerHTML = "Sí";
        } else if (venezuelan === 0) {
            venezuelanLegal.innerHTML = "No";
        }
    }
    venezuelanLegal.parentElement.parentElement.setAttribute("upid", dataCompany.venezuelan.update);


    //type company
    var validTypeCompany = dataCompany.type.valid;
    var typeCompany = document.getElementById("typeCompany");
    if (dataCompany.type.dsc !== "") {
        if (validTypeCompany === 0) {
            document.getElementById("typeCompanyPending").classList.remove("far");
            document.getElementById("typeCompanyPending").classList.add("fas");
            document.getElementById("typeCompanyPending").dataset.updateLbl = dataCompany.type.update + "-pending";
            document.getElementById("typeCompanyPending").style.color = colorPending;
        } else if (validTypeCompany === 1) {
            document.getElementById("typeCompanyValid").classList.remove("far");
            document.getElementById("typeCompanyValid").classList.add("fas");
            document.getElementById("typeCompanyValid").dataset.updateLbl = dataCompany.type.update + "-valid";
            document.getElementById("typeCompanyValid").style.color = colorValid;
        } else if (validTypeCompany === -1) {
            document.getElementById("typeCompanyRejected").classList.remove("far");
            document.getElementById("typeCompanyRejected").classList.add("fas");
            document.getElementById("typeCompanyRejected").dataset.updateLbl = dataCompany.type.update + "-invalid";
            document.getElementById("typeCompanyRejected").style.color = colorRejected
        }

        if (dataCompany.type.dsc) {
            typeCompany.innerHTML = dataCompany.type.dsc;
        }
    }
    typeCompany.parentElement.parentElement.setAttribute("upid", dataCompany.type.update);



    //number id
    var validIdentificationLegal = dataCompany.document.dsc.valid;
    var identificationLegal = document.getElementById("identificationLegal");
    if (dataCompany.document.dsc.value !== "") {
        if (validIdentificationLegal === 0) {
            document.getElementById("identificationLegalPending").classList.remove("far");
            document.getElementById("identificationLegalPending").classList.add("fas");
            document.getElementById("identificationLegalPending").dataset.updateLbl = dataCompany.document.dsc.update + "-pending";
            document.getElementById("identificationLegalPending").style.color = colorPending;
        } else if (validIdentificationLegal === 1) {
            document.getElementById("identificationLegalValid").classList.remove("far");
            document.getElementById("identificationLegalValid").classList.add("fas");
            document.getElementById("identificationLegalValid").dataset.updateLbl = dataCompany.document.dsc.update + "-valid";
            document.getElementById("identificationLegalValid").style.color = colorValid;
        } else if (validIdentificationLegal === -1) {
            document.getElementById("identificationLegalRejected").classList.remove("far");
            document.getElementById("identificationLegalRejected").classList.add("fas");
            document.getElementById("identificationLegalRejected").dataset.updateLbl = dataCompany.document.dsc.update + "-invalid";
            document.getElementById("identificationLegalRejected").style.color = colorRejected
        }

        if (dataCompany.document.dsc.value) {
            identificationLegal.innerHTML = dataCompany.document.dsc.value;
        }
    }
    identificationLegal.parentElement.parentElement.setAttribute("upid", dataCompany.document.dsc.update);


    //reason social
    var validreasonSocial = dataCompany.name.valid;
    var reasonSocial = document.getElementById("reasonSocial");
    if (dataCompany.name.value !== "") {
        if (validIdentificationLegal === 0) {
            document.getElementById("reasonSocialPending").classList.remove("far");
            document.getElementById("reasonSocialPending").classList.add("fas");
            document.getElementById("reasonSocialPending").dataset.updateLbl = dataCompany.name.update + "-pending";
            document.getElementById("reasonSocialPending").style.color = colorPending;
        } else if (validIdentificationLegal === 1) {
            document.getElementById("reasonSocialValid").classList.remove("far");
            document.getElementById("reasonSocialValid").classList.add("fas");
            document.getElementById("reasonSocialValid").dataset.updateLbl = dataCompany.name.update + "-valid";
            document.getElementById("reasonSocialValid").style.color = colorValid;
        } else if (validIdentificationLegal === -1) {
            document.getElementById("reasonSocialRejected").classList.remove("far");
            document.getElementById("reasonSocialRejected").classList.add("fas");
            document.getElementById("reasonSocialRejected").dataset.updateLbl = dataCompany.name.update + "-invalid";
            document.getElementById("reasonSocialRejected").style.color = colorRejected
        }

        if (dataCompany.name.value) {
            reasonSocial.innerHTML = dataCompany.name.value;
        }
    }
    reasonSocial.parentElement.parentElement.setAttribute("upid", dataCompany.name.update);


    //initiales or name comapny
    var validcomercialname = dataCompany.comercialname.valid;
    var comercialname = document.getElementById("comercialName");
    if (dataCompany.comercialname.value !== "") {
        if (validcomercialname === 0) {
            document.getElementById("comercialNamePending").classList.remove("far");
            document.getElementById("comercialNamePending").classList.add("fas");
            document.getElementById("comercialNamePending").dataset.updateLbl = dataCompany.comercialname.update + "-pending";
            document.getElementById("comercialNamePending").style.color = colorPending;
        } else if (validcomercialname === 1) {
            document.getElementById("comercialNameValid").classList.remove("far");
            document.getElementById("comercialNameValid").classList.add("fas");
            document.getElementById("comercialNameValid").dataset.updateLbl = dataCompany.comercialname.update + "-valid";
            document.getElementById("comercialNameValid").style.color = colorValid;
        } else if (validcomercialname === -1) {
            document.getElementById("comercialNameRejected").classList.remove("far");
            document.getElementById("comercialNameRejected").classList.add("fas");
            document.getElementById("comercialNameRejected").dataset.updateLbl = dataCompany.comercialname.update + "-invalid";
            document.getElementById("comercialNameRejected").style.color = colorRejected
        }

        if (dataCompany.comercialname.value) {
            comercialname.innerHTML = dataCompany.comercialname.value;
        }
    }
    comercialname.parentElement.parentElement.setAttribute("upid", dataCompany.comercialname.update);


    //date create
    var validdateCreateCompany = dataCompany.datecreated.valid;
    var dateCreateCompany = document.getElementById("dateCreateCompany");
    if (dataCompany.datecreated.formatted !== "") {
        if (validdateCreateCompany === 0) {
            document.getElementById("dateCreateCompanyPending").classList.remove("far");
            document.getElementById("dateCreateCompanyPending").classList.add("fas");
            document.getElementById("dateCreateCompanyPending").dataset.updateLbl = dataCompany.datecreated.update + "-pending";
            document.getElementById("dateCreateCompanyPending").style.color = colorPending;
        } else if (validdateCreateCompany === 1) {
            document.getElementById("dateCreateCompanyValid").classList.remove("far");
            document.getElementById("dateCreateCompanyValid").classList.add("fas");
            document.getElementById("dateCreateCompanyValid").dataset.updateLbl = dataCompany.datecreated.update + "-valid";
            document.getElementById("dateCreateCompanyValid").style.color = colorValid;
        } else if (validdateCreateCompany === -1) {
            document.getElementById("dateCreateCompanyRejected").classList.remove("far");
            document.getElementById("dateCreateCompanyRejected").classList.add("fas");
            document.getElementById("dateCreateCompanyRejected").dataset.updateLbl = dataCompany.datecreated.update + "-invalid";
            document.getElementById("dateCreateCompanyRejected").style.color = colorRejected
        }

        if (dataCompany.datecreated.formatted) {
            dateCreateCompany.innerHTML = dataCompany.datecreated.formatted;
        }
    }
    dateCreateCompany.parentElement.parentElement.setAttribute("upid", dataCompany.datecreated.update);

    //country 
    var validcountryCompany = dataCompany.document.country.valid;
    var countryCompany = document.getElementById("countryCompany");
    if (dataCompany.document.country.dsc !== "") {
        if (validcountryCompany === 0) {
            document.getElementById("countryCompanyPending").classList.remove("far");
            document.getElementById("countryCompanyPending").classList.add("fas");
            document.getElementById("countryCompanyPending").dataset.updateLbl = dataCompany.document.country.update + "-pending";
            document.getElementById("countryCompanyPending").style.color = colorPending;
        } else if (validcountryCompany === 1) {
            document.getElementById("countryCompanyValid").classList.remove("far");
            document.getElementById("countryCompanyValid").classList.add("fas");
            document.getElementById("countryCompanyValid").dataset.updateLbl = dataCompany.document.country.update + "-valid";
            document.getElementById("countryCompanyValid").style.color = colorValid;
        } else if (validcountryCompany === -1) {
            document.getElementById("countryCompanyRejected").classList.remove("far");
            document.getElementById("countryCompanyRejected").classList.add("fas");
            document.getElementById("countryCompanyRejected").dataset.updateLbl = dataCompany.document.country.update + "-invalid";
            document.getElementById("countryCompanyRejected").style.color = colorRejected
        }

        if (dataCompany.document.country.dsc) {
            countryCompany.innerHTML = dataCompany.document.country.dsc;
        }
    }
    countryCompany.parentElement.parentElement.setAttribute("upid", dataCompany.document.country.update);


    //state
    var validstateCompany = dataCompany.document.region.valid;
    var stateCompany = document.getElementById("stateCompany");
    if (dataCompany.document.region.value !== "") {
        if (validcountryCompany === 0) {
            document.getElementById("stateCompanyPending").classList.remove("far");
            document.getElementById("stateCompanyPending").classList.add("fas");
            document.getElementById("stateCompanyPending").dataset.updateLbl = dataCompany.document.region.update + "-pending";
            document.getElementById("stateCompanyPending").style.color = colorPending;
        } else if (validcountryCompany === 1) {
            document.getElementById("stateCompanyValid").classList.remove("far");
            document.getElementById("stateCompanyValid").classList.add("fas");
            document.getElementById("stateCompanyValid").dataset.updateLbl = dataCompany.document.region.update + "-valid";
            document.getElementById("stateCompanyValid").style.color = colorValid;
        } else if (validcountryCompany === -1) {
            document.getElementById("stateCompanyRejected").classList.remove("far");
            document.getElementById("stateCompanyRejected").classList.add("fas");
            document.getElementById("stateCompanyRejected").dataset.updateLbl = dataCompany.document.region.update + "-invalid";
            document.getElementById("stateCompanyRejected").style.color = colorRejected
        }

        if (dataCompany.document.region.dsc) {
            stateCompany.innerHTML = dataCompany.document.region.dsc;
        }
    }
    stateCompany.parentElement.parentElement.setAttribute("upid", dataCompany.document.region.update);
    //city
    var validcityCompany = dataCompany.document.city.valid;
    var cityCompany = document.getElementById("cityCompany");
    if (dataCompany.document.city.value !== "") {
        if (validcityCompany === 0) {
            document.getElementById("cityCompanyPending").classList.remove("far");
            document.getElementById("cityCompanyPending").classList.add("fas");
            document.getElementById("cityCompanyPending").dataset.updateLbl = dataCompany.document.city.update + "-pending";
            document.getElementById("cityCompanyPending").style.color = colorPending;
        } else if (validcityCompany === 1) {
            document.getElementById("cityCompanyValid").classList.remove("far");
            document.getElementById("cityCompanyValid").classList.add("fas");
            document.getElementById("cityCompanyValid").dataset.updateLbl = dataCompany.document.city.update + "-valid";
            document.getElementById("cityCompanyValid").style.color = colorValid;
        } else if (validcityCompany === -1) {
            document.getElementById("cityCompanyRejected").classList.remove("far");
            document.getElementById("cityCompanyRejected").classList.add("fas");
            document.getElementById("cityCompanyRejected").dataset.updateLbl = dataCompany.document.city.update + "-invalid";
            document.getElementById("cityCompanyRejected").style.color = colorRejected
        }

        if (dataCompany.document.city.dsc) {
            cityCompany.innerHTML = dataCompany.document.city.dsc;
        }
    }
    cityCompany.parentElement.parentElement.setAttribute("upid", dataCompany.document.city.update);
    //cod postal
    var validcodePostal = dataCompany.document.postalcode.valid;
    var codePostal = document.getElementById("codePostal");
    if (dataCompany.document.postalcode.value !== "") {
        if (validcityCompany === 0) {
            document.getElementById("codePostalPending").classList.remove("far");
            document.getElementById("codePostalPending").classList.add("fas");
            document.getElementById("codePostalPending").dataset.updateLbl = dataCompany.document.postalcode.update + "-pending";
            document.getElementById("codePostalPending").style.color = colorPending;
        } else if (validcityCompany === 1) {
            document.getElementById("codePostalValid").classList.remove("far");
            document.getElementById("codePostalValid").classList.add("fas");
            document.getElementById("codePostalValid").dataset.updateLbl = dataCompany.document.postalcode.update + "-valid";
            document.getElementById("codePostalValid").style.color = colorValid;
        } else if (validcityCompany === -1) {
            document.getElementById("codePostalRejected").classList.remove("far");
            document.getElementById("codePostalRejected").classList.add("fas");
            document.getElementById("codePostalRejected").dataset.updateLbl = dataCompany.document.postalcode.update + "-invalid";
            document.getElementById("codePostalRejected").style.color = colorRejected;
        }
        if (dataCompany.document.postalcode.value) {
            codePostal.innerHTML = dataCompany.document.postalcode.value;
        }
    }
    codePostal.parentElement.parentElement.setAttribute("upid", dataCompany.document.postalcode.update);

    //number phone
    var validphoneLegal = dataCompany.phone.valid;
    var phoneLegal = document.getElementById("phoneLegal");
    if (dataCompany.phone.value !== "") {
        if (validphoneLegal === 0) {
            document.getElementById("phoneLegalPending").classList.remove("far");
            document.getElementById("phoneLegalPending").classList.add("fas");
            document.getElementById("phoneLegalPending").dataset.updateLbl = dataCompany.phone.update + "-pending";
            document.getElementById("phoneLegalPending").style.color = colorPending;
        } else if (validphoneLegal === 1) {
            document.getElementById("phoneLegalValid").classList.remove("far");
            document.getElementById("phoneLegalValid").classList.add("fas");
            document.getElementById("phoneLegalValid").dataset.updateLbl = dataCompany.phone.update + "-valid";
            document.getElementById("phoneLegalValid").style.color = colorValid;
        } else if (validphoneLegal === -1) {
            document.getElementById("phoneLegalRejected").classList.remove("far");
            document.getElementById("phoneLegalRejected").classList.add("fas");
            document.getElementById("phoneLegalRejected").dataset.updateLbl = dataCompany.phone.update + "-invalid";
            document.getElementById("phoneLegalRejected").style.color = colorRejected
        }
        if (dataCompany.phone.value) {
            phoneLegal.innerHTML = dataCompany.phone.value;
        }
    }
    phoneLegal.parentElement.parentElement.setAttribute("upid", dataCompany.phone.update);

    //url web
    var validwebSite = dataCompany.website.valid;
    var webSite = document.getElementById("webSite");
    if (dataCompany.website.value !== "") {
        if (validwebSite === 0) {
            document.getElementById("webSitePending").classList.remove("far");
            document.getElementById("webSitePending").classList.add("fas");
            document.getElementById("webSitePending").dataset.updateLbl = dataCompany.website.update + "-pending";
            document.getElementById("webSitePending").style.color = colorPending;
        } else if (validwebSite === 1) {
            document.getElementById("webSiteValid").classList.remove("far");
            document.getElementById("webSiteValid").classList.add("fas");
            document.getElementById("webSiteValid").dataset.updateLbl = dataCompany.website.update + "-valid";
            document.getElementById("webSiteValid").style.color = colorValid;
        } else if (validwebSite === -1) {
            document.getElementById("webSiteRejected").classList.remove("far");
            document.getElementById("webSiteRejected").classList.add("fas");
            document.getElementById("webSiteRejected").dataset.updateLbl = dataCompany.website.update + "-invalid";
            document.getElementById("webSiteRejected").style.color = colorRejected
        }
        if (dataCompany.website.value) {
            webSite.innerHTML = dataCompany.website.value;
        }
    }
    webSite.parentElement.parentElement.setAttribute("upid", dataCompany.website.update);

    //number partners

    var validnumberPartners = dataCompany.partnersnumber.valid;
    var numberPartners = document.getElementById("numberPartners");
    if (dataCompany.partnersnumber.value !== "") {
        if (validnumberPartners === 0) {
            document.getElementById("numberPartnersPending").classList.remove("far");
            document.getElementById("numberPartnersPending").classList.add("fas");
            document.getElementById("numberPartnersPending").dataset.updateLbl = dataCompany.partnersnumber.update + "-pending";
            document.getElementById("numberPartnersPending").style.color = colorPending;
        } else if (validnumberPartners === 1) {
            document.getElementById("numberPartnersValid").classList.remove("far");
            document.getElementById("numberPartnersValid").classList.add("fas");
            document.getElementById("numberPartnersValid").dataset.updateLbl = dataCompany.partnersnumber.update + "-valid";
            document.getElementById("numberPartnersValid").style.color = colorValid;
        } else if (validnumberPartners === -1) {
            document.getElementById("numberPartnersRejected").classList.remove("far");
            document.getElementById("numberPartnersRejected").classList.add("fas");
            document.getElementById("numberPartnersRejected").dataset.updateLbl = dataCompany.partnersnumber.update + "-invalid";
            document.getElementById("numberPartnersRejected").style.color = colorRejected
        }
        if (dataCompany.partnersnumber.value) {
            numberPartners.innerHTML = dataCompany.partnersnumber.value;
        }
    }
    numberPartners.parentElement.parentElement.setAttribute("upid", dataCompany.partnersnumber.update);

}

// Tab 'Partner Data' Modal Legal Person
function paintTabDataPartnersLegal(rsp) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    var dataCompany = rsp.entry.company.partners;
    var legalrep = {};
    if (dataCompany != null) {
        for (let i = 0; i < (rsp.entry.company.partnersnumber.value + 1); i++) {
            var lines = 4;
            if (i <= dataCompany.length) {
                if (dataCompany[i] !== undefined && dataCompany[i] !== null) {
                    if (dataCompany[i].politicalexposed.value == 1) lines = 8;
                }
            }

            for (var x = 0; x < lines; x++) {
                // Partners i
                var row = document.createElement("div");
                row.classList.add("row-tabCnt");

                var validCol = document.createElement("div");
                validCol.classList.add("validCol");
                var iValid = document.createElement("i");
                var iPending = document.createElement("i");
                var iRejected = document.createElement("i");
                iValid.classList.add("far");
                iValid.classList.add("fa-check-circle");
                iPending.classList.add("far");
                iPending.classList.add("fa-pause-circle");
                iRejected.classList.add("far");
                iRejected.classList.add("fa-times-circle");


                var prntName = "";
                var val = ""; var valid = 1; var update = "";

                prntName = "Socio " + (i);
                if (i == 0) prntName = " Representante Legal";
                switch (x) {
                    case 0:
                        lbl = "Nombre " + prntName;
                        if (i <= dataCompany.length) {
                            if (dataCompany[i] !== undefined && dataCompany[i] !== null) {
                                val = dataCompany[i].name.value;
                                valid = dataCompany[i].name.valid;
                                update = dataCompany[i].name.update;
                            }
                        }
                        break;
                    case 1:
                        lbl = "Identificación  " + prntName;
                        if (i <= dataCompany.length) {
                            if (dataCompany[i] !== undefined && dataCompany[i] !== null) {
                                val = dataCompany[i].document.value;
                                valid = dataCompany[i].document.valid;
                                update = dataCompany[i].document.update;
                            }
                        }
                        break;
                    case 2:
                        lbl = "Teléfono  " + prntName;
                        if (i <= dataCompany.length) {
                            if (dataCompany[i] !== undefined && dataCompany[i] !== null) {
                                val = dataCompany[i].phone.value;
                                valid = dataCompany[i].phone.valid;
                                update = dataCompany[i].phone.update;
                            }
                        }
                        break;
                    case 3:
                        lbl = "Persona Políticamente Expuesta " + prntName;
                        if (i <= dataCompany.length) {
                            if (dataCompany[i] !== undefined && dataCompany[i] !== null) {
                                if (dataCompany[i].politicalexposed.value == 1) val = "Si";
                                else if (dataCompany[i].politicalexposed.value == 0) val = "No";
                                else val = "";
                                valid = dataCompany[i].politicalexposed.valid;
                                update = dataCompany[i].politicalexposed.update;
                            }
                        }
                        break;
                    case 4://De aca para bajo no se valida que exista porque se valida en las lines arriba
                        lbl = "Nombre del ente de adscripción " + prntName;
                        val = dataCompany[i].affiliationbody.value;
                        valid = dataCompany[i].affiliationbody.valid;
                        update = dataCompany[i].affiliationbody.update;
                        break;
                    case 5:
                        lbl = "Cargo que desempeña " + prntName;
                        val = dataCompany[i].positionheld.value;
                        valid = dataCompany[i].positionheld.valid;
                        update = dataCompany[i].positionheld.update;
                        break;
                    case 6:
                        lbl = "País " + prntName;
                        val = dataCompany[i].pepcountryid.dsc;
                        valid = dataCompany[i].pepcountryid.valid;
                        update = dataCompany[i].pepcountryid.update;
                        break;
                    case 7:
                        lbl = "Identificación del relacionado " + prntName;
                        val = dataCompany[i].peprelatedid.value;
                        valid = dataCompany[i].peprelatedid.valid;
                        update = dataCompany[i].peprelatedid.update;
                        break;
                }

                if (val !== "") {
                    if (valid === 0) {
                        iPending.classList.remove("far");
                        iPending.classList.add("fas");
                        iPending.dataset.prtnrUpload = update + "-pending"
                        iPending.style.color = colorPending;
                    } else if (valid === 1) {
                        iValid.classList.remove("far");
                        iValid.classList.add("fas");
                        iValid.dataset.prtnrUpload = update + "-valid"
                        iValid.style.color = colorValid;
                    } else if (valid === -1) {
                        iRejected.classList.remove("far");
                        iRejected.classList.add("fas");
                        iRejected.dataset.prtnrUpload = update + "-invalid"
                        iRejected.style.color = colorRejected;
                    }

                    iValid.addEventListener("click", function () {
                        ActRow(this, 'valid');
                    });
                    iPending.addEventListener("click", function () {
                        ActRow(this, 'pending');
                    });
                    iRejected.addEventListener("click", function () {
                        ActRow(this, 'invalid');
                    });
                }

                validCol.appendChild(iValid);
                validCol.appendChild(iPending);
                validCol.appendChild(iRejected);

                var fieldName = document.createElement("div");
                fieldName.classList.add("fieldCol");
                var p = document.createElement("p");
                p.innerHTML = lbl;
                fieldName.style.width = "40%";
                fieldName.appendChild(p);
                /*
                var fieldCol = document.createElement("div");
                fieldCol.classList.add("fieldCol");
                var p = document.createElement("p");
                p.innerHTML = val;    
                fieldCol.appendChild(p);*/

                var infoCol = document.createElement("div");
                infoCol.classList.add("infoCol");
                var pinf = document.createElement("p");
                pinf.innerHTML = val;
                infoCol.appendChild(pinf);

                if (x % 2 !== 0) {
                    row.classList.add("rowImpar");
                }
                row.appendChild(validCol);
                row.appendChild(fieldName);
                //row.appendChild(fieldCol);
                row.appendChild(infoCol);
                row.setAttribute("upid", update);

                var tabPartners = document.getElementById("partner-data");
                row.dataset.account = "parnersLegalRemovible";
                if (dataCompany[i] !== undefined && dataCompany[i] !== null)
                    row.dataset.partnerid = dataCompany[i].id;
                tabPartners.children[1].children[0].children[0].children[0].appendChild(row);
            }
        }
    }
    /*
    for(let i=0; i<dataCompany.length; i++){
        if(dataCompany[i].legalrep === 1){
            legalrep = dataCompany[i];
        } else{
            paintOtherPartner(dataCompany[i]);
        }
    }
    
  if(legalrep){
    // Name Representative Legal
    var validlegalRepresentative = 1;
    if(validlegalRepresentative === 0){
        document.getElementById("legalRepresentativePending").style.color = colorPending;
    } else if(validlegalRepresentative === 1) {
        document.getElementById("legalRepresentativeValid").style.color = colorValid;
    } else if(validlegalRepresentative === -1) {
        document.getElementById("legalRepresentativeRejected").style.color = colorRejected
    }
    var legalRepresentative = document.getElementById("legalRepresentative");
    if(legalrep.name){
        legalRepresentative.innerHTML = legalrep.name;
    }
    
    // Identification Representative Legal
    var valididentificationRepresentative = 1;
    if(valididentificationRepresentative === 0){
        document.getElementById("identificationRepresentativePending").style.color = colorPending;
    } else if(valididentificationRepresentative === 1) {
        document.getElementById("identificationRepresentativeValid").style.color = colorValid;
    } else if(valididentificationRepresentative === -1) {
        document.getElementById("identificationRepresentativeRejected").style.color = colorRejected
    }
    var identificationRepresentative = document.getElementById("identificationRepresentative");
    if(legalrep.document){
        identificationRepresentative.innerHTML = legalrep.document;
    }
    
    // Phone Representative Legal
    var validphoneRepresentative = 1;
    if(validphoneRepresentative === 0){
        document.getElementById("phoneRepresentativePending").style.color = colorPending;
    } else if(validphoneRepresentative === 1) {
        document.getElementById("phoneRepresentativeValid").style.color = colorValid;
    } else if(validphoneRepresentative === -1) {
        document.getElementById("phoneRepresentativeRejected").style.color = colorRejected
    }
    var phoneRepresentative = document.getElementById("phoneRepresentative");
    if(legalrep.phone){
        phoneRepresentative.innerHTML = legalrep.phone;
    }
    
    // Representative Exposed Legal
    var validphoneRepresentative = 1;
    if(validphoneRepresentative === 0){
        document.getElementById("personExposedPending").style.color = colorPending;
    } else if(validphoneRepresentative === 1) {
        document.getElementById("personExposedValid").style.color = colorValid;
    } else if(validphoneRepresentative === -1) {
        document.getElementById("personExposedRejected").style.color = colorRejected
    }
    var personExposed = document.getElementById("personExposed");
    var exposed = false;
    if(legalrep.politicalexposed === 1){
        personExposed.innerHTML = "Sí";
        exposed = true;
    } else {
        personExposed.innerHTML = "No";
        exposed = false;
    }
    
    if(exposed === true){
        // Name entity
        var validnameEntity = 1;
        if(validnameEntity === 0){
            document.getElementById("nameEntityPending").style.color = colorPending;
        } else if(validnameEntity === 1) {
            document.getElementById("nameEntityValid").style.color = colorValid;
        } else if(validnameEntity === -1) {
            document.getElementById("nameEntityRejected").style.color = colorRejected
        }
        var personExposed = document.getElementById("nameEntity");
        if(legalrep.affiliationbody){
            personExposed.innerHTML = legalrep.affiliationbody
        }
        
        // Job that performs
        var validjobPerforms = 1;
        if(validjobPerforms === 0){
            document.getElementById("jobPerformsPending").style.color = colorPending;
        } else if(validjobPerforms === 1) {
            document.getElementById("jobPerformsValid").style.color = colorValid;
        } else if(validjobPerforms === -1) {
            document.getElementById("jobPerformsRejected").style.color = colorRejected
        }
        var jobPerforms = document.getElementById("jobPerforms");
        if(legalrep.affiliationbody){
            jobPerforms.innerHTML = legalrep.positionheld;
        }
        
        // Country
        var validcountryPersonExposed = 1;
        if(validcountryPersonExposed === 0){
            document.getElementById("countryPersonExposedPending").style.color = colorPending;
        } else if(validcountryPersonExposed === 1) {
            document.getElementById("countryPersonExposedValid").style.color = colorValid;
        } else if(validcountryPersonExposed === -1) {
            document.getElementById("countryPersonExposedRejected").style.color = colorRejected
        }
        var countryPersonExposed = document.getElementById("countryPersonExposed");
        if(legalrep.pepcountryid){
            countryPersonExposed.innerHTML = legalrep.pepcountryid;
        }
        
        // Identification of the related
        var valididentificationPersonExposed = 1;
        if(valididentificationPersonExposed === 0){
            document.getElementById("identificationPersonExposedPending").style.color = colorPending;
        } else if(valididentificationPersonExposed === 1) {
            document.getElementById("identificationPersonExposedValid").style.color = colorValid;
        } else if(valididentificationPersonExposed === -1) {
            document.getElementById("identificationPersonExposedRejected").style.color = colorRejected
        }
        var identificationPersonExposed = document.getElementById("identificationPersonExposed");
        if(legalrep.peprelatedid){
            identificationPersonExposed.innerHTML = legalrep.peprelatedid;
        }
        
    } else {
        var exposedRows = document.getElementsByClassName("repesentativeExposed");
        for(let j=0; j<exposedRows.length; j++){
            exposedRows[j].style.display = 'none';
        }
    }
  }
  */

}

// Paint Partner
function paintOtherPartner(partner) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    //Name partner x
    var rowName = document.createElement("div");
    rowName.classList.add("row-tabCnt");

    var validColName = document.createElement("div");
    validColName.classList.add("validCol");

    var fieldColName = document.createElement("div");
    fieldColName.classList.add("fieldCol");
    var p = document.createElement("p");
    p.style.fontSize = "110%";
    p.style.fontWeight = "bold";
    p.innerHTML = "Socio " + partner.name;
    fieldColName.appendChild(p);

    var infoColName = document.createElement("div");
    infoColName.classList.add("infoCol");

    rowName.appendChild(validColName);
    rowName.appendChild(fieldColName);
    rowName.appendChild(infoColName);

    //Person x politically Exposed
    var rowExposed = document.createElement("div");
    rowExposed.classList.add("row-tabCnt");

    var validColExposed = document.createElement("div");
    validColExposed.classList.add("validCol");
    var iValidExposed = document.createElement("i");
    var iPendingExposed = document.createElement("i");
    var iRejectedExposed = document.createElement("i");
    iValidExposed.classList.add("far");
    iValidExposed.classList.add("fa-check-circle");
    iValidExposed.style.color = colorValid;
    iPendingExposed.classList.add("far");
    iPendingExposed.classList.add("fa-pause-circle");
    iRejectedExposed.classList.add("far");
    iRejectedExposed.classList.add("fa-times-circle");
    validColExposed.appendChild(iValidExposed);
    validColExposed.appendChild(iPendingExposed);
    validColExposed.appendChild(iRejectedExposed);

    var fieldColExposed = document.createElement("div");
    fieldColExposed.classList.add("fieldCol");
    var pField = document.createElement("p");
    pField.innerHTML = "Persona Politicamente Expuesta"
    fieldColExposed.appendChild(pField);

    var infoColExposed = document.createElement("div");
    infoColExposed.classList.add("infoCol");
    var p = document.createElement("p");
    if (partner.politicalexposed == 1) {
        p.innerHTML = 'Sí'
    } else if (partner.politicalexposed == 0) {
        p.innerHTML = 'No'
    } else {
        p.innerHTML = ''
    }
    infoColExposed.appendChild(p);

    rowExposed.appendChild(validColExposed);
    rowExposed.appendChild(fieldColExposed);
    rowExposed.appendChild(infoColExposed);

    var tabPartners = document.getElementById("partner-data");
    rowName.dataset.partner = "partnerNoRep";
    rowExposed.dataset.partner = "partnerNoRep";
    tabPartners.appendChild(rowName);
    tabPartners.appendChild(rowExposed);

    if (partner.politicalexposed == 1) {

        //Name entity x Exposed
        var rowEntity = document.createElement("div");
        rowEntity.classList.add("row-tabCnt");

        var validColEntity = document.createElement("div");
        var validColEntity = document.createElement("div");
        var iValidEntity = document.createElement("i");
        var iPendingEntity = document.createElement("i");
        var iRejectedEntity = document.createElement("i");
        iValidEntity.classList.add("far");
        iValidEntity.classList.add("fa-check-circle");
        iValidEntity.style.color = colorValid;
        iPendingEntity.classList.add("far");
        iPendingEntity.classList.add("fa-pause-circle");
        iRejectedEntity.classList.add("far");
        iRejectedEntity.classList.add("fa-times-circle");
        validColEntity.classList.add("validCol");
        validColEntity.appendChild(iValidEntity);
        validColEntity.appendChild(iPendingEntity);
        validColEntity.appendChild(iRejectedEntity);

        var fieldColEntity = document.createElement("div");
        fieldColEntity.classList.add("fieldCol");
        var pEntity = document.createElement("p");
        pEntity.innerHTML = "Nombre del ente de adscripci\u00F3n"
        fieldColEntity.appendChild(pEntity);

        var infoColEntity = document.createElement("div");
        infoColEntity.classList.add("infoCol");
        var pEntityInfo = document.createElement("p");
        if (partner.affiliationbody) {
            pEntityInfo.innerHTML = partner.affiliationbody;
        }
        infoColEntity.appendChild(pEntityInfo);

        rowEntity.appendChild(validColEntity);
        rowEntity.appendChild(fieldColEntity);
        rowEntity.appendChild(infoColEntity);

        //Job performs x Exposed
        var rowJob = document.createElement("div");
        rowJob.classList.add("row-tabCnt");

        var validColJob = document.createElement("div");
        var iValidJob = document.createElement("i");
        var iPendingJob = document.createElement("i");
        var iRejectedJob = document.createElement("i");
        iValidJob.classList.add("far");
        iValidJob.classList.add("fa-check-circle");
        iValidJob.style.color = colorValid;
        iPendingJob.classList.add("far");
        iPendingJob.classList.add("fa-pause-circle");
        iRejectedJob.classList.add("far");
        iRejectedJob.classList.add("fa-times-circle");
        validColJob.classList.add("validCol");
        validColJob.appendChild(iValidJob);
        validColJob.appendChild(iPendingJob);
        validColJob.appendChild(iRejectedJob);

        var fieldColJob = document.createElement("div");
        fieldColJob.classList.add("fieldCol");
        var pEntity = document.createElement("p");
        pEntity.innerHTML = "Cargo que desempe\u00F1a"
        fieldColJob.appendChild(pEntity);

        var infoColJob = document.createElement("div");
        infoColJob.classList.add("infoCol");
        var pJobInfo = document.createElement("p");
        if (partner.positionheld) {
            pJobInfo.innerHTML = partner.positionheld;
        }
        infoColJob.appendChild(pJobInfo);

        rowJob.appendChild(validColJob);
        rowJob.appendChild(fieldColJob);
        rowJob.appendChild(infoColJob);

        //Country x Exposed
        var rowCountry = document.createElement("div");
        rowCountry.classList.add("row-tabCnt");

        var validColCountry = document.createElement("div");
        var iValidcountry = document.createElement("i");
        var iPendingcountry = document.createElement("i");
        var iRejectedcountry = document.createElement("i");
        iValidcountry.classList.add("far");
        iValidcountry.classList.add("fa-check-circle");
        iValidcountry.style.color = colorValid;
        iPendingcountry.classList.add("far");
        iPendingcountry.classList.add("fa-pause-circle");
        iRejectedcountry.classList.add("far");
        iRejectedcountry.classList.add("fa-times-circle");
        validColCountry.classList.add("validCol");
        validColCountry.appendChild(iValidcountry);
        validColCountry.appendChild(iPendingcountry);
        validColCountry.appendChild(iRejectedcountry);

        var fieldColCountry = document.createElement("div");
        fieldColCountry.classList.add("fieldCol");
        var pEntity = document.createElement("p");
        pEntity.innerHTML = "Pa\u00EDs"
        fieldColCountry.appendChild(pEntity);

        var infoColCountry = document.createElement("div");
        infoColCountry.classList.add("infoCol");
        var pJobInfo = document.createElement("p");
        if (partner.pepcountryid) {
            pJobInfo.innerHTML = partner.pepcountryid;
        }
        infoColCountry.appendChild(pJobInfo);

        rowCountry.appendChild(validColCountry);
        rowCountry.appendChild(fieldColCountry);
        rowCountry.appendChild(infoColCountry);

        //identification x Exposed
        var rowIdentification = document.createElement("div");
        rowIdentification.classList.add("row-tabCnt");

        var validColIdentification = document.createElement("div");
        var iValidId = document.createElement("i");
        var iPendingId = document.createElement("i");
        var iRejectedId = document.createElement("i");
        iValidId.classList.add("far");
        iValidId.classList.add("fa-check-circle");
        iValidId.style.color = colorValid;
        iPendingId.classList.add("far");
        iPendingId.classList.add("fa-pause-circle");
        iRejectedId.classList.add("far");
        iRejectedId.classList.add("fa-times-circle");
        validColIdentification.classList.add("validCol");
        validColIdentification.appendChild(iValidId);
        validColIdentification.appendChild(iPendingId);
        validColIdentification.appendChild(iRejectedId);

        var fieldColIdentification = document.createElement("div");
        fieldColIdentification.classList.add("fieldCol");
        var pId = document.createElement("p");
        pId.innerHTML = "Identificaci\u00F3n del relacionado"
        fieldColIdentification.appendChild(pId);

        var infoColIdentification = document.createElement("div");
        infoColIdentification.classList.add("infoCol");
        var pIdInfo = document.createElement("p");
        if (partner.peprelatedid) {
            pIdInfo.innerHTML = partner.peprelatedid;
        }
        infoColIdentification.appendChild(pIdInfo);

        rowIdentification.appendChild(validColIdentification);
        rowIdentification.appendChild(fieldColIdentification);
        rowIdentification.appendChild(infoColIdentification);

        rowEntity.dataset.partner = "partnerNoRep";
        rowJob.dataset.partner = "partnerNoRep";
        rowCountry.dataset.partner = "partnerNoRep";
        rowIdentification.dataset.partner = "partnerNoRep";
        tabPartners.appendChild(rowEntity);
        tabPartners.appendChild(rowJob);
        tabPartners.appendChild(rowCountry);
        tabPartners.appendChild(rowIdentification);
    }

}

// Tab 'Direction Company' Modal Legal Person
function paintTabDirectioncompanyLegal(rsp) {
    var bd = document.getElementById("direction-company").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    var dataCompany = rsp.entry.company;

    // Country Residence
    var validcountryResidence = dataCompany.country.valid;
    if (validcountryResidence === 0) {
        document.getElementById("countryResidencePending").classList.remove("far");
        document.getElementById("countryResidencePending").classList.add("fas");
        document.getElementById("countryResidencePending").dataset.updateLbl = dataCompany.country.update + "-pending";
        document.getElementById("countryResidencePending").style.color = colorPending;
    } else if (validcountryResidence === 1) {
        document.getElementById("countryResidenceValid").classList.remove("far");
        document.getElementById("countryResidenceValid").classList.add("fas");
        document.getElementById("countryResidenceValid").dataset.updateLbl = dataCompany.country.update + "-valid";
        document.getElementById("countryResidenceValid").style.color = colorValid;
    } else if (validcountryResidence === -1) {
        document.getElementById("countryResidenceRejected").classList.remove("far");
        document.getElementById("countryResidenceRejected").classList.add("fas");
        document.getElementById("countryResidenceRejected").dataset.updateLbl = dataCompany.country.update + "-invalid";
        document.getElementById("countryResidenceRejected").style.color = colorRejected
    }
    var countryResidence = document.getElementById("countryResidence");
    if (dataCompany.country.dsc) {
        countryResidence.innerHTML = dataCompany.country.dsc;
    }
    countryResidence.parentElement.parentElement.setAttribute("upid", dataCompany.country.update);


    // State Residence
    var validstateResidence = dataCompany.region.valid;
    if (validstateResidence === 0) {
        document.getElementById("stateResidencePending").classList.remove("far");
        document.getElementById("stateResidencePending").classList.add("fas");
        document.getElementById("stateResidencePending").dataset.updateLbl = dataCompany.region.update + "-pending";
        document.getElementById("stateResidencePending").style.color = colorPending;
    } else if (validstateResidence === 1) {
        document.getElementById("stateResidenceValid").classList.remove("far");
        document.getElementById("stateResidenceValid").classList.add("fas");
        document.getElementById("stateResidenceValid").dataset.updateLbl = dataCompany.region.update + "-valid";
        document.getElementById("stateResidenceValid").style.color = colorValid;
    } else if (validstateResidence === -1) {
        document.getElementById("stateResidenceRejected").classList.remove("far");
        document.getElementById("stateResidenceRejected").classList.add("fas");
        document.getElementById("stateResidenceRejected").dataset.updateLbl = dataCompany.region.update + "-invalid";
        document.getElementById("stateResidenceRejected").style.color = colorRejected
    }
    var stateResidence = document.getElementById("stateResidence");
    if (dataCompany.region.dsc) {
        stateResidence.innerHTML = dataCompany.region.dsc;
    }
    stateResidence.parentElement.parentElement.setAttribute("upid", dataCompany.region.update);

    // City Residence
    var validcityResidence = dataCompany.city.valid;
    if (validcityResidence === 0) {
        document.getElementById("cityResidencePending").classList.remove("far");
        document.getElementById("cityResidencePending").classList.add("fas");
        document.getElementById("cityResidencePending").dataset.updateLbl = dataCompany.city.update + "-pending";
        document.getElementById("cityResidencePending").style.color = colorPending;
    } else if (validcityResidence === 1) {
        document.getElementById("cityResidenceValid").classList.remove("far");
        document.getElementById("cityResidenceValid").classList.add("fas");
        document.getElementById("cityResidenceValid").dataset.updateLbl = dataCompany.city.update + "-valid";
        document.getElementById("cityResidenceValid").style.color = colorValid;
    } else if (validcityResidence === -1) {
        document.getElementById("cityResidenceRejected").classList.remove("far");
        document.getElementById("cityResidenceRejected").classList.add("fas");
        document.getElementById("cityResidenceRejected").dataset.updateLbl = dataCompany.city.update + "-invalid";
        document.getElementById("cityResidenceRejected").style.color = colorRejected
    }
    var cityResidence = document.getElementById("cityResidence");
    if (dataCompany.city.dsc) {
        cityResidence.innerHTML = dataCompany.city.dsc;
    }
    cityResidence.parentElement.parentElement.setAttribute("upid", dataCompany.city.update);

    // Street Residence
    var validstreetResidence = dataCompany.street.valid;
    if (validstreetResidence === 0) {
        document.getElementById("streetResidencePending").classList.remove("far");
        document.getElementById("streetResidencePending").classList.add("fas");
        document.getElementById("streetResidencePending").dataset.updateLbl = dataCompany.street.update + "-pending";
        document.getElementById("streetResidencePending").style.color = colorPending;
    } else if (validstreetResidence === 1) {
        document.getElementById("streetResidenceValid").classList.remove("far");
        document.getElementById("streetResidenceValid").classList.add("fas");
        document.getElementById("streetResidenceValid").dataset.updateLbl = dataCompany.street.update + "-valid";
        document.getElementById("streetResidenceValid").style.color = colorValid;
    } else if (validstreetResidence === -1) {
        document.getElementById("streetResidenceRejected").classList.remove("far");
        document.getElementById("streetResidenceRejected").classList.add("fas");
        document.getElementById("streetResidenceRejected").dataset.updateLbl = dataCompany.street.update + "-invalid";
        document.getElementById("streetResidenceRejected").style.color = colorRejected
    }
    var streetResidence = document.getElementById("streetResidence");
    if (dataCompany.street.value) {
        streetResidence.innerHTML = dataCompany.street.value;
    }
    streetResidence.parentElement.parentElement.setAttribute("upid", dataCompany.street.update);

    // House Residence
    var validhouseNumber = dataCompany.home.valid;
    if (validhouseNumber === 0) {
        document.getElementById("houseNumberPending").classList.remove("far");
        document.getElementById("houseNumberPending").classList.add("fas");
        document.getElementById("houseNumberPending").dataset.updateLbl = dataCompany.home.update + "-pending";
        document.getElementById("houseNumberPending").style.color = colorPending;
    } else if (validhouseNumber === 1) {
        document.getElementById("houseNumberValid").classList.remove("far");
        document.getElementById("houseNumberValid").classList.add("fas");
        document.getElementById("houseNumberValid").dataset.updateLbl = dataCompany.home.update + "-valid";
        document.getElementById("houseNumberValid").style.color = colorValid;
    } else if (validhouseNumber === -1) {
        document.getElementById("houseNumberRejected").classList.remove("far");
        document.getElementById("houseNumberRejected").classList.add("fas");
        document.getElementById("houseNumberRejected").dataset.updateLbl = dataCompany.home.update + "-invalid";
        document.getElementById("houseNumberRejected").style.color = colorRejected
    }
    var streetResidence = document.getElementById("houseNumber");
    if (dataCompany.home.value) {
        streetResidence.innerHTML = dataCompany.home.value;
    }
    streetResidence.parentElement.parentElement.setAttribute("upid", dataCompany.home.update);

    // House Residence
    var validbranchOffice = dataCompany.branchoffices.valid;
    if (validbranchOffice === 0) {
        document.getElementById("branchOfficePending").classList.remove("far");
        document.getElementById("branchOfficePending").classList.add("fas");
        document.getElementById("branchOfficePending").dataset.updateLbl = dataCompany.branchoffices.update + "-pending";
        document.getElementById("branchOfficePending").style.color = colorPending;
    } else if (validbranchOffice === 1) {
        document.getElementById("branchOfficeValid").classList.remove("far");
        document.getElementById("branchOfficeValid").classList.add("fas");
        document.getElementById("branchOfficeValid").dataset.updateLbl = dataCompany.branchoffices.update + "-valid";
        document.getElementById("branchOfficeValid").style.color = colorValid;
    } else if (validbranchOffice === -1) {
        document.getElementById("branchOfficeRejected").classList.remove("far");
        document.getElementById("branchOfficeRejected").classList.add("fas");
        document.getElementById("branchOfficeRejected").dataset.updateLbl = dataCompany.branchoffices.update + "-invalid";
        document.getElementById("branchOfficeRejected").style.color = colorRejected
    }
    var streetResidence = document.getElementById("branchOffice");
    if (dataCompany.branchoffices.value != null) {
        streetResidence.innerHTML = dataCompany.branchoffices.value;
    }
    streetResidence.parentElement.parentElement.setAttribute("upid", dataCompany.branchoffices.update);

}

// Tab 'Professional Data' Modal Legal Person
function paintTabProfessionalInfoLegal(rsp) {
    var bd = document.getElementById("professional-info-legal").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    var dataCompany = rsp.entry.company;

    // Economic Activity
    var valideconomicAct = dataCompany.economicalactivity.valid;
    if (valideconomicAct === 0) {
        document.getElementById("economicActPending").classList.remove("far");
        document.getElementById("economicActPending").classList.add("fas");
        document.getElementById("economicActPending").dataset.updateLbl = dataCompany.economicalactivity.update + "-pending";
        document.getElementById("economicActPending").style.color = colorPending;
    } else if (valideconomicAct === 1) {
        document.getElementById("economicActValid").classList.remove("far");
        document.getElementById("economicActValid").classList.add("fas");
        document.getElementById("economicActValid").dataset.updateLbl = dataCompany.economicalactivity.update + "-valid";
        document.getElementById("economicActValid").style.color = colorValid;
    } else if (valideconomicAct === -1) {
        document.getElementById("economicActRejected").classList.remove("far");
        document.getElementById("economicActRejected").classList.add("fas");
        document.getElementById("economicActRejected").dataset.updateLbl = dataCompany.economicalactivity.update + "-invalid";
        document.getElementById("economicActRejected").style.color = colorRejected
    }
    var economicAct = document.getElementById("economicAct");
    var select = economicAct.nextElementSibling;
    var val = dataCompany.economicalactivity.value;
    if (val !== null) {
        select.value = val;
        val = select.options[select.selectedIndex].textContent;
        if (dataCompany.economicalactivity.value) {
            economicAct.innerHTML = val;
        }
        economicAct.parentElement.parentElement.setAttribute("upid", dataCompany.economicalactivity.update);
    } else {
        economicAct.innerHTML = "";
    }



    //Exposed
    update = dataCompany.politicalexposed.update;
    icons = ["personExposedPending", "personExposedValid", "personExposedRejected"];
    valid = dataCompany.politicalexposed.valid;
    val = "";
    if (dataCompany.politicalexposed.value == 1) {
        val = "Sí";
    } else if (dataCompany.politicalexposed.value == 0) {
        val = "No";
    } else {
        val = "";
    }
    drawSolidCols(icons, update, valid, "personExposed", val);

    // Anual Income
    var validanualIncome = dataCompany.anualincome.valid;
    if (validanualIncome === 0) {
        document.getElementById("anualIncomePending").classList.remove("far");
        document.getElementById("anualIncomePending").classList.add("fas");
        document.getElementById("anualIncomePending").dataset.updateLbl = dataCompany.anualincome.update + "-pending";
        document.getElementById("anualIncomePending").style.color = colorPending;
    } else if (validanualIncome === 1) {
        document.getElementById("anualIncomeValid").classList.remove("far");
        document.getElementById("anualIncomeValid").classList.add("fas");
        document.getElementById("anualIncomeValid").dataset.updateLbl = dataCompany.anualincome.update + "-valid";
        document.getElementById("anualIncomeValid").style.color = colorValid;
    } else if (validanualIncome === -1) {
        document.getElementById("anualIncomeRejected").classList.remove("far");
        document.getElementById("anualIncomeRejected").classList.add("fas");
        document.getElementById("anualIncomeRejected").dataset.updateLbl = dataCompany.anualincome.update + "-invalid";
        document.getElementById("anualIncomeRejected").style.color = colorRejected
    }
    var anualIncome = document.getElementById("anualIncome");
    if (dataCompany.anualincome.formatted) {
        anualIncome.innerHTML = dataCompany.anualincome.formatted;
    }
    anualIncome.parentElement.parentElement.setAttribute("upid", dataCompany.anualincome.update);


    // Anual Income
    var validworth = dataCompany.patrimony.valid;
    if (validworth === 0) {
        document.getElementById("worthPending").classList.remove("far");
        document.getElementById("worthPending").classList.add("fas");
        document.getElementById("worthPending").dataset.updateLbl = dataCompany.patrimony.update + "-pending";
        document.getElementById("worthPending").style.color = colorPending;
    } else if (validworth === 1) {
        document.getElementById("worthValid").classList.remove("far");
        document.getElementById("worthValid").classList.add("fas");
        document.getElementById("worthValid").dataset.updateLbl = dataCompany.patrimony.update + "-valid";
        document.getElementById("worthValid").style.color = colorValid;
    } else if (validworth === -1) {
        document.getElementById("worthRejected").classList.remove("far");
        document.getElementById("worthRejected").classList.add("fas");
        document.getElementById("worthRejected").dataset.updateLbl = dataCompany.patrimony.update + "-invalid";
        document.getElementById("worthRejected").style.color = colorRejected
    }
    var worth = document.getElementById("worth");
    if (dataCompany.patrimony.formatted) {
        worth.innerHTML = dataCompany.patrimony.formatted;
    }
    worth.parentElement.parentElement.setAttribute("upid", dataCompany.patrimony.update);

}

// Tab 'Support Image' Modal Legal Person
function paintTabDataImagesLegal(rsp) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var dataCompany = rsp.entry.company.uploads;

    if (dataCompany) {
        for (let i = 0; i < dataCompany.length; i++) {
            // Image i
            var row = document.createElement("div");
            row.classList.add("row-tabCnt");

            var validCol = document.createElement("div");
            validCol.classList.add("validCol");
            var iValid = document.createElement("i");
            var iPending = document.createElement("i");
            var iRejected = document.createElement("i");
            iValid.classList.add("far");
            iValid.classList.add("fa-check-circle");
            iPending.classList.add("far");
            iPending.classList.add("fa-pause-circle");
            iRejected.classList.add("far");
            iRejected.classList.add("fa-times-circle");

            if (dataCompany[i].url !== "") {
                if (dataCompany[i].validated === 0) {
                    iPending.classList.remove("far");
                    iPending.classList.add("fas");
                    iPending.dataset.updateUpload = dataCompany[i].id + "-pending"
                    iPending.style.color = colorPending;
                } else if (dataCompany[i].validated === 1) {
                    iValid.classList.remove("far");
                    iValid.classList.add("fas");
                    iValid.dataset.updateUpload = dataCompany[i].id + "-valid"
                    iValid.style.color = colorValid;
                } else if (dataCompany[i].validated === -1) {
                    iRejected.classList.remove("far");
                    iRejected.classList.add("fas");
                    iRejected.dataset.updateUpload = dataCompany[i].id + "-invalid"
                    iRejected.style.color = colorRejected;
                }
                iValid.addEventListener("click", function () {
                    ActRow(this, 'valid');
                });
                iPending.addEventListener("click", function () {
                    ActRow(this, 'pending');
                });
                iRejected.addEventListener("click", function () {
                    ActRow(this, 'invalid');
                });
            }
            validCol.appendChild(iValid);
            validCol.appendChild(iPending);
            validCol.appendChild(iRejected);

            var fieldCol = document.createElement("div");
            fieldCol.classList.add("fieldCol");
            var p = document.createElement("p");
            if (dataCompany[i].dsc) {
                p.innerHTML = dataCompany[i].dsc;
            } else {
                p.innerHTML = "";
            }
            fieldCol.appendChild(p);
            fieldCol.style.width = "70%";

            var infoCol = document.createElement("div");
            infoCol.classList.add("infoCol");
            var iEye = document.createElement("i");
            iEye.classList.add("fas");
            iEye.classList.add("fa-eye");
            iEye.style.color = "#4287CE";
            iEye.dataset.url = dataCompany[i].url;
            infoCol.style.width = "10%";
            infoCol.style.textAlign = "left";
            if (dataCompany[i].url !== "")
                infoCol.appendChild(iEye);

            if (dataCompany[i].url == "") iEye.style.display = "";
            iEye.addEventListener("click", function () {
                //document.getElementById("modalImage").style.display = "block";
                var url = this.dataset.url;
                window.open(url, '_blank');
                /*
                setTimeout(function(){
                    document.getElementById("imageSupport").style.backgroundImage = 'url('+url+')';
                    document.getElementById("modalImage").style.opacity = "1";
                },300);*/
            });


            if (i % 2 !== 0) {
                row.classList.add("rowImpar");
            }
            row.appendChild(validCol);
            row.appendChild(fieldCol);
            row.appendChild(infoCol);
            row.dataset.idImgLegal = dataCompany[i].id;

            var tabPartners = document.getElementById("images-data-legal");
            row.dataset.image = "imagesLegalRemovible";
            tabPartners.children[1].children[0].children[0].children[0].appendChild(row);
        }
    }
}

// Tab 'Transaction Data' Modal Legal Person
function paintTabDataTransactionLegal(rsp) {
    var bd = document.getElementById("transaction-data-legal").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';

    var dataCompany = rsp.entry.company;

    // Operations Average by month
    var validaverageMonth = dataCompany.qtyoperationsmothly.valid;
    if (validaverageMonth === 0) {
        document.getElementById("averageMonthPending").classList.remove("far");
        document.getElementById("averageMonthPending").classList.add("fas");
        document.getElementById("averageMonthPending").dataset.updateLbl = dataCompany.qtyoperationsmothly.update + "-pending";
        document.getElementById("averageMonthPending").style.color = colorPending;
    } else if (validaverageMonth === 1) {
        document.getElementById("averageMonthValid").classList.remove("far");
        document.getElementById("averageMonthValid").classList.add("fas");
        document.getElementById("averageMonthValid").dataset.updateLbl = dataCompany.qtyoperationsmothly.update + "-valid";
        document.getElementById("averageMonthValid").style.color = colorValid;
    } else if (validaverageMonth === -1) {
        document.getElementById("averageMonthRejected").classList.remove("far");
        document.getElementById("averageMonthRejected").classList.add("fas");
        document.getElementById("averageMonthRejected").dataset.updateLbl = dataCompany.qtyoperationsmothly.update + "-invalid";
        document.getElementById("averageMonthRejected").style.color = colorRejected
    }
    var averageMonth = document.getElementById("averageMonth");
    if (dataCompany.qtyoperationsmothly.value) {
        averageMonth.innerHTML = dataCompany.qtyoperationsmothly.value;
    }
    averageMonth.parentElement.parentElement.setAttribute("upid", dataCompany.qtyoperationsmothly.update);

    // Mount $ of operations 
    var validmountOp = dataCompany.amooperationsmonthly.valid;
    if (validmountOp === 0) {
        document.getElementById("mountOpPending").classList.remove("far");
        document.getElementById("mountOpPending").classList.add("fas");
        document.getElementById("mountOpPending").dataset.updateLbl = dataCompany.amooperationsmonthly.update + "-pending";
        document.getElementById("mountOpPending").style.color = colorPending;
    } else if (validmountOp === 1) {
        document.getElementById("mountOpValid").classList.remove("far");
        document.getElementById("mountOpValid").classList.add("fas");
        document.getElementById("mountOpValid").dataset.updateLbl = dataCompany.amooperationsmonthly.update + "-valid";
        document.getElementById("mountOpValid").style.color = colorValid;
    } else if (validmountOp === -1) {
        document.getElementById("mountOpRejected").classList.remove("far");
        document.getElementById("mountOpRejected").classList.add("fas");
        document.getElementById("mountOpRejected").dataset.updateLbl = dataCompany.amooperationsmonthly.update + "-invalid";
        document.getElementById("mountOpRejected").style.color = colorRejected
    }
    var mountOp = document.getElementById("mountOp");
    if (dataCompany.amooperationsmonthly.number) {
        mountOp.innerHTML = dataCompany.amooperationsmonthly.number;
    }
    mountOp.parentElement.parentElement.setAttribute("upid", dataCompany.amooperationsmonthly.update);

    // type operations
    var validtypeOp = dataCompany.preferoptype.valid;
    if (validtypeOp === 0) {
        document.getElementById("typeOpPending").classList.remove("far");
        document.getElementById("typeOpPending").classList.add("fas");
        document.getElementById("typeOpPending").dataset.updateLbl = dataCompany.preferoptype.update + "-pending";
        document.getElementById("typeOpPending").style.color = colorPending;
    } else if (validtypeOp === 1) {
        document.getElementById("typeOpValid").classList.remove("far");
        document.getElementById("typeOpValid").classList.add("fas");
        document.getElementById("typeOpValid").dataset.updateLbl = dataCompany.preferoptype.update + "-valid";
        document.getElementById("typeOpValid").style.color = colorValid;
    } else if (validtypeOp === -1) {
        document.getElementById("typeOpRejected").classList.remove("far");
        document.getElementById("typeOpRejected").classList.add("fas");
        document.getElementById("typeOpRejected").dataset.updateLbl = dataCompany.preferoptype.update + "-invalid";
        document.getElementById("typeOpRejected").style.color = colorRejected
    }
    var typeOp = document.getElementById("typeOp");
    if (dataCompany.preferoptype.id != null) {
        val = dataCompany.preferoptype.id;
        let vals = dataCompany.preferoptype.id.split("-");
        let res = '';
        for (let i = 0; i < vals.length; i++) {
            switch (parseInt(vals[i])) {
                case 1: res += (i == 0 ? "Cripto - Cripto" : ", Cripto - Cripto"); break;
                case 2: res += (i == 0 ? "Cripto - Dinero Fiat" : ", Cripto - Dinero Fiat"); break;
                case 3: res += (i == 0 ? "Dinero Fiat - Cripto" : ", Dinero Fiat - Cripto"); break;
            }
        }

        typeOp.innerHTML = res;
    }
    typeOp.parentElement.parentElement.setAttribute("upid", dataCompany.preferoptype.update);


    //Relationship with economic group
    var validrelationGruop = dataCompany.economicrelation.valid;
    if (validrelationGruop === 0) {
        document.getElementById("relationGruopPending").classList.remove("far");
        document.getElementById("relationGruopPending").classList.add("fas");
        document.getElementById("relationGruopPending").dataset.updateLbl = dataCompany.economicrelation.update + "-pending";
        document.getElementById("relationGruopPending").style.color = colorPending;
    } else if (validrelationGruop === 1) {
        document.getElementById("relationGruopValid").classList.remove("far");
        document.getElementById("relationGruopValid").classList.add("fas");
        document.getElementById("relationGruopValid").dataset.updateLbl = dataCompany.economicrelation.update + "-valid";
        document.getElementById("relationGruopValid").style.color = colorValid;
    } else if (validrelationGruop === -1) {
        document.getElementById("relationGruopRejected").classList.remove("far");
        document.getElementById("relationGruopRejected").classList.add("fas");
        document.getElementById("relationGruopRejected").dataset.updateLbl = dataCompany.economicrelation.update + "-invalid";
        document.getElementById("relationGruopRejected").style.color = colorRejected;
    }
    var relationGruop = document.getElementById("relationGruop");
    if (dataCompany.economicrelation.value != null) {
        let val = dataCompany.economicrelation.value;
        if (val == 1) val = "Sí";
        else if (val == 0) val = "No";
        else val = '';
        relationGruop.innerHTML = val;//dataCompany.economicrelation.value;
    }
    relationGruop.parentElement.parentElement.setAttribute("upid", dataCompany.economicrelation.update);
}

// Tab 'Retirement Accounts' Modal Legal Person
function paintTabAccountsLegal(rsp) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var dataCompany = rsp.entry.accounts;
    if (dataCompany !== null)
        for (let i = 0; i < dataCompany.length; i++) {
            var lines = 0;
            if (dataCompany[i].paymentmethod.details1 != null) lines = 1;
            if (dataCompany[i].paymentmethod.details2 != null) lines = 2;
            if (dataCompany[i].paymentmethod.details3 != null) lines = 3;
            if (dataCompany[i].paymentmethod.details4 != null) lines = 4;
            for (var x = 0; x < lines; x++) {
                // Account i
                var row = document.createElement("div");
                row.classList.add("row-tabCnt");

                var validCol = document.createElement("div");
                validCol.classList.add("validCol");
                var iValidAccount = document.createElement("i");
                var iPendingAccount = document.createElement("i");
                var iRejectedAccount = document.createElement("i");
                iValidAccount.classList.add("far");
                iValidAccount.classList.add("fa-check-circle");
                iPendingAccount.classList.add("far");
                iPendingAccount.classList.add("fa-pause-circle");
                iRejectedAccount.classList.add("far");
                iRejectedAccount.classList.add("fa-times-circle");
                if (dataCompany[i]['details' + (x + 1)].valid === 0) {
                    iPendingAccount.classList.remove("far");
                    iPendingAccount.classList.add("fas");
                    iPendingAccount.style.color = colorPending;
                    iPendingAccount.dataset.updateAcc = 'details' + (x + 1) + "-pending";
                } else if (dataCompany[i]['details' + (x + 1)].valid === 1) {
                    iValidAccount.classList.remove("far");
                    iValidAccount.classList.add("fas");
                    iValidAccount.style.color = colorValid;
                    iValidAccount.dataset.updateAcc = 'details' + (x + 1) + "-valid";
                } else if (dataCompany[i]['details' + (x + 1)].valid === -1) {
                    iRejectedAccount.classList.remove("far");
                    iRejectedAccount.classList.add("fas");
                    iRejectedAccount.style.color = colorRejected;
                    iRejectedAccount.dataset.updateAcc = 'details' + (x + 1) + "-invalid";
                }
                iValidAccount.addEventListener("click", function () {
                    ActRow(this, 'valid');
                });
                iPendingAccount.addEventListener("click", function () {
                    ActRow(this, 'pending');
                });
                iRejectedAccount.addEventListener("click", function () {
                    ActRow(this, 'invalid');
                });
                validCol.appendChild(iValidAccount);
                validCol.appendChild(iPendingAccount);
                validCol.appendChild(iRejectedAccount);

                var fieldName = document.createElement("div");
                fieldName.classList.add("fieldCol");
                var p = document.createElement("p");
                if (x == 0) {
                    p.innerHTML = dataCompany[i].paymentmethod.name + "(" + dataCompany[i].currency.symbol + ")";
                } else {
                    p.innerHTML = "";
                }
                fieldName.appendChild(p);
                fieldName.style.width = '30%';


                var fieldCol = document.createElement("div");
                fieldCol.classList.add("fieldCol");
                var p = document.createElement("p");
                p.innerHTML = dataCompany[i].paymentmethod["details" + (x + 1)];
                fieldCol.appendChild(p);
                fieldCol.style.width = '20%';

                var infoCol = document.createElement("div");
                infoCol.classList.add("infoCol");
                var infcnt = document.createElement("p");
                infcnt.innerHTML = dataCompany[i]["details" + (x + 1)].value;
                infoCol.appendChild(infcnt);
                infoCol.style.width = '30%';


                if (x % 2 !== 0) {
                    row.classList.add("rowImpar");
                }
                row.appendChild(validCol);
                row.appendChild(fieldName);
                row.appendChild(fieldCol);
                row.appendChild(infoCol);

                var tabPartners = document.getElementById("accounts-legal");
                row.dataset.account = "accountsLegalRemovible";
                row.dataset.accountid = dataCompany[i].id;
                tabPartners.children[0].lastElementChild.appendChild(row);
            }
        }
}

function AddTagPersonLegal(ele, className) {
    var groupTag = ele.parentNode;
    var span = document.createElement("span");
    var spanX = document.createElement("span");
    spanX.innerHTML = "&times;"
    const id = ele.value;
    span.setAttribute("id", id);
    span.classList.add(className);
    spanX.style.cursor = "pointer";
    spanX.addEventListener("click", function () {
        RemoveTagLegal(id);
    });
    span.innerHTML = "#" + ele.value;
    span.appendChild(spanX);
    var lastChild = groupTag.lastElementChild;
    groupTag.insertBefore(span, lastChild);
    ele.value = "";
}

function RemoveTagLegal(id) {
    console.log("id que llega ", id)
    var groupTagLegal = document.getElementById("groupTagLegal");
    var span = document.getElementById(id);
    groupTagLegal.removeChild(span)
}

function updateSessionLegal(id, type) {
    var sessionId = sessionStorage.getItem("sessionId");
    var status = -1;
    if (type === 2) {
        if (document.getElementById("swichtStatusLegal").classList.contains("active")) {
            status = 1;
        } else {
            status = 0;
        }

        var level = document.getElementById("levelLegal").value;
        var risklevel = document.getElementById("riskLevelLegal").value;
        var tagBar = document.getElementsByClassName("groupTagLegal");
        var parmTag = "";
        if (tagBar.length > 0) {
            var tags = tagBar[0].getElementsByClassName("tag");
            for (var i = 0; i < tags.length; i++) {
                parmTag += tags[i].getAttribute("data-tag") + " ";
            }
            parmTag = parmTag.substr(0, parmTag.length - 1);
        }

    } else if (type === 1) {
        if (document.getElementById("swichtStatusNatural").classList.contains("active")) {
            status = 1;
        } else {
            status = 0;
        }

        var level = document.getElementById("levelNatural").value;
        var risklevel = document.getElementById("riskLevelNatural").value;
        var tagBar = document.getElementsByClassName("groupTagNatural");
        var parmTag = "";
        if (tagBar.length > 0) {
            var tags = tagBar[0].getElementsByClassName("tag");
            for (var i = 0; i < tags.length; i++) {
                parmTag += tags[i].getAttribute("data-tag") + " ";
            }
            parmTag = parmTag.substr(0, parmTag.length - 1);
        }
    }

    var req = {};
    req.sessionid = sessionId;
    req.id = id;
    req.status = status;
    if (level != "") req.level = level;
    else req.level = 0;
    req.risklevel = risklevel;

    if (parmTag !== "") req.tags = parmTag;
    else req.tags = "";
    console.log("request ", req);
    callWS("GET", "appusers/update", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp) {
            let resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n actualizada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);

                break;

            case 204:
            case 400:
                msg.classList.add("msgError");
                msg.innerHTML = "Error"
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 401:
                myLogout();
                break;

            case 403:
                msg.classList.add("msgError");
                msg.innerHTML = "No posee privilegios para actualizar la sesi\u00F3n";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 409:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, sesi\u00F3n duplicada";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.innerHTML = "";
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                msg.classList.add("msgError");
                msg.innerHTML = "Error al actualizar, intente nuevamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
                break;
        }

        var modal = document.getElementById("modalDetailNatural");
        modal.style.display = "none";
        blankForm(modal);

        var modal = document.getElementById("modalDetailLegal");
        modal.style.display = "none";
        blankForm(modal);
    }
}

function validateSession(usrid) {
    var sessionId = sessionStorage.getItem("sessionId");
    var approved = "";
    var rejected = "";
    var rejecteduploadids = "";
    var approveduploadids = "";
    var partnersids = "";
    var accountids = "";
    var approvedprtnr = "";
    var rejectedprtnr = "";
    var approvedacc = "";
    var rejectedacc = "";
    var tblCnt = document.getElementById("entryUserTbl");
    var updates = tblCnt.getElementsByClassName('rowLvlInf');
    var req = {};
    var prtnrsload = 1;
    var accload = 1;


    var approvedprtnr = "";
    var rejectedprtnr = "";
    var approvedacc = "";
    var rejectedacc = "";
    for (let i = 0; i < updates.length; i++) {
        var isUpload = updates[i].getElementsByClassName("cellInfTbl")[2].classList.contains("upvalue");
        var isPrtnr = updates[i].classList.contains("prnrval");
        var isAcc = updates[i].classList.contains("accVal");
        var upd = updates[i].getElementsByClassName("cellInfTbl")[0];
        var upid = upd.getAttribute("upid");
        var status = "";
        if (upd.getElementsByClassName("lvlCellActv").length > 0)
            status = upd.getElementsByClassName("lvlCellActv")[0].getAttribute("label");

        if (status == 1 || status == -1 || status == 0) {
            if (partnersids.indexOf(updates[i].getAttribute("prtnrid")) == -1 && updates[i].getAttribute("prtnrid") != null) {
                partnersids += updates[i].getAttribute("prtnrid") + "-";
            }
            if (accountids.indexOf(updates[i].getAttribute("accid")) == -1 && updates[i].getAttribute("accid") != null) {
                accountids += updates[i].getAttribute("accid") + "-";
            }
        }
        switch (status) {
            case '1':
                if (isUpload) {
                    approveduploadids += upid + '-';
                } else if (isPrtnr) {
                    if ((prtnrsload + 2) == (partnersids.split("-").length) && (partnersids.split("-").length > 0)) {
                        if (approvedprtnr != "" || rejectedprtnr != "") {
                            approvedprtnr = approvedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedprtnr = rejectedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['partner' + (prtnrsload)] = approvedprtnr + "|" + rejectedprtnr;
                        approvedprtnr = "";
                        rejectedprtnr = "";
                        prtnrsload = prtnrsload + 1;
                    }
                    approvedprtnr += upid + ',';
                } else if (isAcc) {
                    if ((accload + 2) == (accountids.split("-").length) && (accountids.split("-").length > 0)) {
                        if (approvedacc != "" || rejectedacc != "") {
                            approvedacc = approvedacc.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedacc = rejectedacc.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['account' + (accload)] = approvedacc + "|" + rejectedacc;
                        approvedacc = "";
                        rejectedacc = "";
                        accload = accload + 1;
                    }
                    approvedacc += upid + ',';
                } else {
                    approved += upid + ',';
                }
                break;
            case '-1':
                if (isUpload) {
                    rejecteduploadids += upid + '-';
                } else if (isPrtnr) {
                    if ((prtnrsload + 2) == (partnersids.split("-").length) && (partnersids.split("-").length > 0)) {
                        if (approvedprtnr != "" || rejectedprtnr != "") {
                            approvedprtnr = approvedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedprtnr = rejectedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['partner' + (prtnrsload)] = approvedprtnr + "|" + rejectedprtnr;
                        approvedprtnr = "";
                        rejectedprtnr = "";
                        prtnrsload = prtnrsload + 1;
                    }

                    rejectedprtnr += upid + ',';
                } else if (isAcc) {
                    if ((accload + 2) == (accountids.split("-").length) && (accountids.split("-").length > 0)) {
                        if (approvedacc != "" || rejectedacc != "") {
                            approvedacc = approvedacc.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedacc = rejectedacc.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['account' + (accload)] = approvedacc + "|" + rejectedacc;
                        approvedacc = "";
                        rejectedacc = "";
                        accload = accload + 1;
                    }
                    rejectedacc += upid + ',';
                } else {
                    rejected += upid + ',';
                }
                break;
            case '0':
                if (isPrtnr) {
                    if ((prtnrsload + 2) == (partnersids.split("-").length) && (partnersids.split("-").length > 0)) {
                        if (approvedprtnr != "" || rejectedprtnr != "") {
                            approvedprtnr = approvedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedprtnr = rejectedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['partner' + (prtnrsload)] = approvedprtnr + "|" + rejectedprtnr;
                        approvedprtnr = "";
                        rejectedprtnr = "";
                        prtnrsload = prtnrsload + 1;
                    }
                } else if (isAcc) {
                    if ((accload + 2) == (accountids.split("-").length) && (accountids.split("-").length > 0)) {
                        if (approvedacc != "" || rejectedacc != "") {
                            approvedacc = approvedacc.slice(0, -1); //Se elimina el ultimo "-" 
                            rejectedacc = rejectedacc.slice(0, -1); //Se elimina el ultimo "-" 
                        }
                        req['account' + (accload)] = approvedacc + "|" + rejectedacc;
                        approvedacc = "";
                        rejectedacc = "";
                        accload = accload + 1;
                    }
                }
                break;
        }
    }
    req.id = usrid;
    req.sessionid = sessionId;
    if (approveduploadids != "" || rejecteduploadids != "") {
        approveduploadids = approveduploadids.slice(0, -1); //Se elimina el ultimo "-" 
        rejecteduploadids = rejecteduploadids.slice(0, -1); //Se elimina el ultimo "-" 
        req.approveduploadids = approveduploadids;
        req.rejecteduploadids = rejecteduploadids;
    }
    if (approved != "" || rejected != "") {
        approved = approved.slice(0, -1); //Se elimina el ultimo "-" 
        rejected = rejected.slice(0, -1); //Se elimina el ultimo "-" 
        req.approved = approved;
        req.rejected = rejected;
    }
    if ((prtnrsload + 1) == (partnersids.split("-").length) && (partnersids.split("-").length > 0)) {
        if (approvedprtnr != "" || rejectedprtnr != "") {
            approvedprtnr = approvedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
            rejectedprtnr = rejectedprtnr.slice(0, -1); //Se elimina el ultimo "-" 
        }
        req['partner' + (prtnrsload)] = approvedprtnr + "|" + rejectedprtnr;
        approvedprtnr = "";
        rejectedprtnr = "";
        prtnrsload = prtnrsload + 1;
    }
    if (partnersids != "") {
        partnersids = partnersids.slice(0, -1);//Se elimina el ultimo "-"    
        req.partnerids = partnersids;
    }
    if ((accload + 1) == (accountids.split("-").length) && (accountids.split("-").length > 0)) {
        if (approvedacc != "" || rejectedacc != "") {
            approvedacc = approvedacc.slice(0, -1); //Se elimina el ultimo "-" 
            rejectedacc = rejectedacc.slice(0, -1); //Se elimina el ultimo "-" 
        }
        req['account' + (accload)] = approvedacc + "|" + rejectedacc;
        approvedacc = "";
        rejectedacc = "";
        accload = accload + 1;
    }
    if (accountids != "") {
        accountids = accountids.slice(0, -1);//Se elimina el ultimo "-"            
        req.accountids = accountids;
    }
    var respuesta = function (status, rsp) {
        if (rsp) {
            var resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("errorEntryCnt");
        switch (status) {
            case 200:
                loadvalid = true;
                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n validada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);
                loadLevels(resp.id, document.getElementById("levelsList").value);

            case 400:
                break;

            case 401:
                myLogout();
                break;

            case 409:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Documento de identificacion duplicado";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);
                break;

            case 500:
                break;
        }
    }
    callWS("GET", "appusers/validate", req, respuesta);
}

function validateSessionNatural(id) {
    var sessionId = sessionStorage.getItem("sessionId");
    var approved = "";
    var rejected = "";
    var rejecteduploadids = "";
    var approveduploadids = "";
    var tblCnt = document.getElementById("modalDetailNatural");
    var updates = tblCnt.querySelectorAll('[data-update-lbl]');
    for (let i = 0; i < updates.length; i++) {
        var upd = updates[i].dataset.updateLbl
        if (upd.includes('-valid')) {
            if (approved === "") {
                approved = upd.split("-")[0];
            } else {
                approved = approved + ',' + upd.split("-")[0];
            }
        } else if (upd.includes('-invalid')) {
            if (rejected === "") {
                rejected = upd.split("-")[0];
            } else {
                rejected = rejected + ',' + upd.split("-")[0];
            }
        }
    }

    var imagesUpdate = tblCnt.querySelectorAll('[data-update-upload]');
    for (let j = 0; j < imagesUpdate.length; j++) {
        var img = imagesUpdate[j].dataset.updateUpload;
        if (img.includes('-valid')) {
            if (approveduploadids === "") {
                approveduploadids = img.split("-")[0];
            } else {
                approveduploadids = approveduploadids + '-' + img.split("-")[0];
            }
        } else if (img.includes('-invalid')) {
            if (rejecteduploadids === "") {
                rejecteduploadids = img.split("-")[0];
            } else {
                rejecteduploadids = rejecteduploadids + '-' + img.split("-")[0];
            }
        }
    }



    req = {};
    var approvedacc = ""; var rejectedacc = "";
    var accountsId = document.querySelectorAll('[data-account="accountsNaturalRemovible"]');
    var ids = "";
    var cntid = 0;
    var last = 0;
    for (let i = 0; i < accountsId.length; i++) {
        var upd = accountsId[i].querySelectorAll('[data-update-acc]');
        upd = upd[0].dataset.updateAcc;
        if ((ids.toString()).indexOf(accountsId[i].dataset.accountid.toString()) < 0) {
            if (ids === "") {
                if (i == (accountsId.length - 1))
                    ids = accountsId[i].dataset.accountid;
                else
                    ids = accountsId[i].dataset.accountid;
            } else {
                if (i == (accountsId.length - 1))
                    ids = ids + "-" + accountsId[i].dataset.accountid;
                else
                    ids = ids + "-" + accountsId[i].dataset.accountid;
            }
            cntid = cntid + 1;
            rejectedacc = ""; approvedacc = "";
        }
        if (upd.includes('-valid')) {
            if (approvedacc === "") {
                approvedacc = upd.split("-")[0];
            } else {
                approvedacc = approvedacc + ',' + upd.split("-")[0];
            }
        } else if (upd.includes('-invalid')) {
            if (rejectedacc === "") {
                rejectedacc = upd.split("-")[0];
            } else {
                rejectedacc = rejectedacc + ',' + upd.split("-")[0];
            }
        }
        req["account" + cntid] = approvedacc + "|" + rejectedacc;
    }

    req.accountids = ids;
    req.id = id;
    req.sessionid = sessionId;
    if (approveduploadids != "" || rejecteduploadids != "") {
        req.approveduploadids = approveduploadids;
        req.rejecteduploadids = rejecteduploadids;
    }
    if (approved != "" || rejected != "") {
        req.approved = approved;
        req.rejected = rejected;
    }

    callWS("GET", "appusers/validate", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp) {
            let resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                //Una vez que se validan los datos se cargan los niveles y se evalúa si existe el que se encuentra marcado previamente.
                //Si no existe se escoge la primera opción
                LoadLevelsList(1, id, document.getElementById("levelNatural").value, function () {
                    updateSessionLegal(id, 1);

                    var filter = document.getElementById("search").value;
                    if (filter == null || filter == undefined) filter = '';
                    LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);

                });

                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n validada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);

                var modal = document.getElementById("modalDetailNatural");
                modal.style.display = "none";





            case 400:
                break;

            case 401:
                myLogout();
                break;

            case 409:
                msg.classList.add("msgSucess");
                msg.innerHTML = "Documento de identificacion duplicado";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);

                var modal = document.getElementById("modalDetailNatural");
                modal.style.display = "none";

                blankForm(document.getElementById("modalDetailNatural"));

                var filter = document.getElementById("search").value;
                if (filter == null || filter == undefined) {
                    filter = '';
                }
                LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
                break;

            case 500:
                break;
        }
    }
}

function blankForm(tbl) {
    var cols = tbl.getElementsByClassName("infoCol");
    for (var i = 0; i < cols.length; i++) {
        if (cols[i].firstElementChild !== null)
            cols[i].firstElementChild.innerHTML = "";
    }
    var updates = tbl.querySelectorAll('[data-image]');
    /*Juridico*/
    var levelLegal = document.getElementById("levelLegal");
    var levelLegalOp = levelLegal.getElementsByClassName("levelLegalOp");
    for (let i = 0; i < levelLegalOp.length; i++) {
        levelLegal.removeChild(levelLegalOp[i]);
    }

    var tabImagesLegal = document.getElementById("images-data-legal");
    var image = document.querySelectorAll('[data-image="imagesLegalRemovible"]');
    for (let i = 0; i < image.length; i++) {
        tabImagesLegal.children[1].children[0].children[0].children[0].removeChild(image[i]);
    }
    var tabAccounts = document.getElementById("accounts-legal");
    var account = tabAccounts.querySelectorAll('[data-account="accountsLegalRemovible"]');
    for (let i = 0; i < account.length; i++) {
        tabAccounts.children[0].lastElementChild.removeChild(account[i]);
    }

    var tabPartner = document.getElementById("partner-data");
    var elements = document.querySelectorAll('[data-account="parnersLegalRemovible"]');
    for (let i = 0; i < elements.length; i++) {
        tabPartner.children[1].children[0].children[0].children[0].removeChild(elements[i]);
    }
    /*Natural*/
    var levelNatural = document.getElementById("levelNatural");
    var levelNaturalOp = levelNatural.getElementsByClassName("levelNaturalOp");
    for (let i = 0; i < levelNaturalOp.length; i++) {
        levelNatural.removeChild(levelNaturalOp[i]);
    }

    var tabAccounts = document.getElementById("retirement-accounts");
    var account = tabAccounts.querySelectorAll('[data-account="accountsNaturalRemovible"]');
    for (let i = 0; i < account.length; i++) {
        tabAccounts.children[0].lastElementChild.removeChild(account[i]);
    }
    var tabImageNatural = document.getElementById("support-images");
    var image = document.querySelectorAll('[data-image="imagesNautralRemovible"]');
    for (let i = 0; i < image.length; i++) {
        tabImageNatural.children[1].children[0].children[0].children[0].removeChild(image[i]);
    }
    //Etiquetas
    var tags = tbl.getElementsByClassName("tag");
    for (var i = 0; i < tags.length; i++) {
        tags[i].parentElement.removeChild(tags[i]);
    }

    var validCol = document.getElementsByClassName("validCol");
    for (var i = 0; i < validCol.length; i++) {
        var xIc = validCol[i].getElementsByTagName("i");
        for (var x = 0; x < xIc.length; x++) {
            xIc[x].style.color = "";
            xIc[x].classList.add("far");
            xIc[x].classList.remove("fas");
        }
    }

    var tblCnt = document.getElementById("modalDetailLegal");
    var updates = tblCnt.querySelectorAll('[data-update-lbl]');
    for (var i = 0; i < updates.length; i++) {
        updates[i].removeAttribute('data-update-lbl');
    }
    var tblCnt = document.getElementById("modalDetailNatural");
    var updates = tblCnt.querySelectorAll('[data-update-lbl]');
    for (var i = 0; i < updates.length; i++) {
        updates[i].removeAttribute('data-update-lbl');
    }
    document.getElementById("declaration-natural").getElementsByClassName("infoCol")[0].children[0].innerHTML = "Si";
    document.getElementById("declaration").getElementsByClassName("infoCol")[0].children[0].innerHTML = "Si";
}

function validateSessionLegal(id) {
    var sessionId = sessionStorage.getItem("sessionId");
    var approved = "";
    var rejected = "";
    var rejecteduploadids = "";
    var approveduploadids = "";
    var tblCnt = document.getElementById("modalDetailLegal");
    var updates = tblCnt.querySelectorAll('[data-update-lbl]');
    for (let i = 0; i < updates.length; i++) {
        var upd = updates[i].dataset.updateLbl
        if (upd.includes('-valid')) {
            if (approved === "") {
                approved = upd.split("-")[0];
            } else {
                approved = approved + ',' + upd.split("-")[0];
            }
        } else if (upd.includes('-invalid')) {
            if (rejected === "") {
                rejected = upd.split("-")[0];
            } else {
                rejected = rejected + ',' + upd.split("-")[0];
            }
        }
    }

    var imagesUpdate = tblCnt.querySelectorAll('[data-update-upload]');
    for (let j = 0; j < imagesUpdate.length; j++) {
        var img = imagesUpdate[j].dataset.updateUpload;
        if (img.includes('-valid')) {
            if (approveduploadids === "") {
                approveduploadids = img.split("-")[0];
            } else {
                approveduploadids = approveduploadids + '-' + img.split("-")[0];
            }
        } else if (img.includes('-invalid')) {
            if (rejecteduploadids === "") {
                rejecteduploadids = img.split("-")[0];
            } else {
                rejecteduploadids = rejecteduploadids + '-' + img.split("-")[0];
            }
        }
    }

    req = {};

    var approvedprtnr = ""; var rejectedprtnr = "";
    var partnersId = document.querySelectorAll('[data-account="parnersLegalRemovible"]');
    var ids = "";
    var cntid = 0;
    var last = 0;
    for (let i = 0; i < partnersId.length; i++) {
        var upd = partnersId[i].querySelectorAll('[data-prtnr-upload]');
        if (upd[0] !== undefined) {
            upd = upd[0].dataset.prtnrUpload;
            if ((ids.toString()).indexOf(partnersId[i].dataset.partnerid.toString()) < 0) {
                if (ids === "") {
                    if (i == (partnersId.length - 1))
                        ids = partnersId[i].dataset.partnerid;
                    else
                        ids = partnersId[i].dataset.partnerid;
                } else {
                    if (i == (partnersId.length - 1))
                        ids = ids + "-" + partnersId[i].dataset.partnerid;
                    else
                        ids = ids + "-" + partnersId[i].dataset.partnerid;
                }
                cntid = cntid + 1;
                rejectedprtnr = ""; approvedprtnr = "";
            }
            if (upd.includes('-valid')) {
                if (approvedprtnr === "") {
                    approvedprtnr = upd.split("-")[0];
                } else {
                    approvedprtnr = approvedprtnr + ',' + upd.split("-")[0];
                }
            } else if (upd.includes('-invalid')) {
                if (rejectedprtnr === "") {
                    rejectedprtnr = upd.split("-")[0];
                } else {
                    rejectedprtnr = rejectedprtnr + ',' + upd.split("-")[0];
                }
            }
            req["partner" + cntid] = approvedprtnr + "|" + rejectedprtnr;
        }
    }
    req.partnerids = ids;

    var approvedacc = ""; var rejectedacc = "";
    var accountsId = document.querySelectorAll('[data-account="accountsLegalRemovible"]');
    var ids = "";
    var cntid = 0;
    var last = 0;

    for (let i = 0; i < accountsId.length; i++) {
        var upd = accountsId[i].querySelectorAll('[data-update-acc]');
        upd = upd[0].dataset.updateAcc;
        if ((ids.toString()).indexOf(accountsId[i].dataset.accountid.toString()) < 0) {
            if (ids === "") {
                if (i == (accountsId.length - 1))
                    ids = accountsId[i].dataset.accountid;
                else
                    ids = accountsId[i].dataset.accountid;
            } else {
                if (i == (accountsId.length - 1))
                    ids = ids + "-" + accountsId[i].dataset.accountid;
                else
                    ids = ids + "-" + accountsId[i].dataset.accountid;
            }
            cntid = cntid + 1;
            rejectedacc = ""; approvedacc = "";
        }
        if (upd.includes('-valid')) {
            if (approvedacc === "") {
                approvedacc = upd.split("-")[0];
            } else {
                approvedacc = approvedacc + ',' + upd.split("-")[0];
            }
        } else if (upd.includes('-invalid')) {
            if (rejectedacc === "") {
                rejectedacc = upd.split("-")[0];
            } else {
                rejectedacc = rejectedacc + ',' + upd.split("-")[0];
            }
        }
        req["account" + cntid] = approvedacc + "|" + rejectedacc;
    }

    req.accountids = ids;
    req.id = id;
    req.sessionid = sessionId;
    req.approveduploadids = approveduploadids;
    req.rejecteduploadids = rejecteduploadids;
    req.approved = approved;
    req.rejected = rejected

    callWS("GET", "appusers/validate", req, respuesta);
    function respuesta(status, rsp) {
        if (rsp) {
            let resp = JSON.parse(rsp);
        }
        var msg = document.getElementById("messageApi");
        switch (status) {
            case 200:
                LoadLevelsList(2, id, document.getElementById("levelLegal").value, function () {
                    updateSessionLegal(id, 2);

                    var filter = document.getElementById("search").value;
                    if (filter == null || filter == undefined) {
                        filter = '';
                    }
                    LoadSessions(filter, document.getElementById("rangeFilter").value, document.getElementById("statusFilter").value, document.getElementById("levelFilter").value, 0, document.getElementById("orderBy").value, document.getElementById("registerFilter").value, sessionId);
                });

                msg.classList.add("msgSucess");
                msg.innerHTML = "Sesi\u00F3n validada correctamente";
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgSucess");
                    msg.innerHTML = "";
                    msg.style.display = "none";
                }, 3000);
                break;



            case 400:
                break;

            case 401:
                myLogout();
                break;

            case 409:
                break;

            case 500:
                break;
        }
    }
}

function ActRow(ele, icon) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var noColor = "#D5DCE5";
    var posval = 2;
    var edit = false;
    var win = ele.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.id;
    if (win == 'retirement-accounts' || win == 'accounts-legal') {
        posval = 3;
    } else if (win == 'support-images' || win == 'images-data-legal' || win == "") {
        edit = true;
    }
    if (ele.parentElement.parentElement.children[posval].children[0].textContent.trim() !== "" || edit) {
        if (icon === 'valid') {
            ele.classList.remove("far");
            ele.classList.add("fas");
            ele.style.color = colorValid;
            var next = ele.nextElementSibling;
            next.style.color = noColor;
            next.classList.remove("fas");
            next.classList.add("far");
            var nextNext = next.nextElementSibling;
            nextNext.style.color = noColor;
            nextNext.classList.remove("fas");
            nextNext.classList.add("far");


            if (next.dataset.updateLbl)
                ele.dataset.updateLbl = next.dataset.updateLbl.split("-")[0] + "-valid";
            if (nextNext.dataset.updateLbl)
                ele.dataset.updateLbl = nextNext.dataset.updateLbl.split("-")[0] + "-valid";


            if (next.dataset.updateUpload)
                ele.dataset.updateUpload = next.dataset.updateUpload.split("-")[0] + "-valid";
            if (nextNext.dataset.updateUpload)
                ele.dataset.updateUpload = nextNext.dataset.updateUpload.split("-")[0] + "-valid";

            if (next.dataset.updateAcc)
                ele.dataset.updateAcc = next.dataset.updateAcc.split("-")[0] + "-valid";
            if (nextNext.dataset.updateAcc)
                ele.dataset.updateAcc = nextNext.dataset.updateAcc.split("-")[0] + "-valid";

            if (next.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = next.dataset.prtnrUpload.split("-")[0] + "-valid";
            if (nextNext.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = nextNext.dataset.prtnrUpload.split("-")[0] + "-valid";



            next.removeAttribute("data-update-upload");
            nextNext.removeAttribute("data-update-upload");
            next.removeAttribute("data-update-lbl");
            nextNext.removeAttribute("data-update-lbl");
            next.removeAttribute("data-update-acc");
            nextNext.removeAttribute("data-update-acc");
            next.removeAttribute("data-prtnr-upload");
            nextNext.removeAttribute("data-prtnr-upload");


        } else if (icon === 'invalid') {
            ele.classList.remove("far");
            ele.classList.add("fas");
            ele.style.color = colorRejected;
            var prev = ele.previousElementSibling;
            prev.style.color = noColor;
            prev.classList.remove("fas");
            prev.classList.add("far");
            var prevPrev = prev.previousElementSibling;
            prevPrev.style.color = noColor;
            prevPrev.classList.remove("fas");
            prevPrev.classList.add("far");

            if (prev.dataset.updateLbl)
                ele.dataset.updateLbl = prev.dataset.updateLbl.split("-")[0] + "-invalid";
            if (prevPrev.dataset.updateLbl)
                ele.dataset.updateLbl = prevPrev.dataset.updateLbl.split("-")[0] + "-invalid";


            if (prev.dataset.updateUpload)
                ele.dataset.updateUpload = prev.dataset.updateUpload.split("-")[0] + "-invalid";
            if (prevPrev.dataset.updateUpload)
                ele.dataset.updateUpload = prevPrev.dataset.updateUpload.split("-")[0] + "-invalid";

            if (prev.dataset.updateAcc)
                ele.dataset.updateAcc = prev.dataset.updateAcc.split("-")[0] + "-invalid";
            if (prevPrev.dataset.updateAcc)
                ele.dataset.updateAcc = prevPrev.dataset.updateAcc.split("-")[0] + "-invalid";

            if (prev.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = prev.dataset.prtnrUpload.split("-")[0] + "-invalid";
            if (prevPrev.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = prevPrev.dataset.prtnrUpload.split("-")[0] + "-invalid";

            prev.removeAttribute("data-update-upload");
            prevPrev.removeAttribute("data-update-upload");
            prev.removeAttribute("data-update-lbl");
            prevPrev.removeAttribute("data-update-lbl");
            prev.removeAttribute("data-update-acc");
            prevPrev.removeAttribute("data-update-acc");
            prev.removeAttribute("data-prtnr-upload");
            prevPrev.removeAttribute("data-prtnr-upload");



        } else if (icon === 'pending') {
            ele.classList.remove("far");
            ele.classList.add("fas");
            ele.style.color = colorPending;

            var previ = ele.previousElementSibling
            previ.style.color = noColor;
            previ.classList.remove("fas");
            previ.classList.add("far");
            var nextS = ele.nextElementSibling;
            nextS.style.color = noColor;
            nextS.classList.remove("fas");
            nextS.classList.add("far");

            if (previ.dataset.updateLbl)
                ele.dataset.updateLbl = previ.dataset.updateLbl.split("-")[0] + "-pending";
            //previ.removeAttribute("data-update-upload"); 
            if (nextS.dataset.updateLbl)
                ele.dataset.updateLbl = nextS.dataset.updateLbl.split("-")[0] + "-pending";
            //nextS.removeAttribute("data-update-upload"); 


            if (previ.dataset.updateUpload)
                ele.dataset.updateUpload = previ.dataset.updateUpload.split("-")[0] + "-pending";
            //previ.removeAttribute("data-update-upload"); 
            if (nextS.dataset.updateUpload)
                ele.dataset.updateUpload = nextS.dataset.updateUpload.split("-")[0] + "-pending";
            //nextS.removeAttribute("data-update-upload"); 

            if (previ.dataset.updateAcc)
                ele.dataset.updateAcc = previ.dataset.updateAcc.split("-")[0] + "-pending";
            if (nextS.dataset.updateAcc)
                ele.dataset.updateAcc = nextS.dataset.updateAcc.split("-")[0] + "-pending";

            if (previ.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = previ.dataset.prtnrUpload.split("-")[0] + "-pending";
            if (nextS.dataset.prtnrUpload)
                ele.dataset.prtnrUpload = nextS.dataset.prtnrUpload.split("-")[0] + "-pending";



            previ.removeAttribute("data-update-upload");
            nextS.removeAttribute("data-update-upload");
            previ.removeAttribute("data-update-lbl");
            nextS.removeAttribute("data-update-lbl");
            previ.removeAttribute("data-update-acc");
            nextS.removeAttribute("data-update-acc");
            previ.removeAttribute("data-prtnr-upload");
            nextS.removeAttribute("data-prtnr-upload");
        }
    }
};

function paintTermsNatural(rsp) {
    var bd = document.getElementById("declaration-natural").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var dataPerson = rsp.entry;
    //Declaración
    update = "declaration";
    icons = ["declarationNatPending", "declarationNatValid", "declarationNatRejected"];
    valid = dataPerson.declaration.valid;
    val = dataPerson.declaration.value;
    drawSolidCols(icons, update, valid, "declarationNat", val);
    var declaration = document.getElementById("declarationNat");
    if (val !== null) {
        declaration.innerHTML = "Sí";
    } else {
        declaration.innerHTML = "No";
    }
    update = "terms";
    icons = ["termsNatPending", "termsNatValid", "termsNatRejected"];
    valid = dataPerson.terms.valid;
    val = dataPerson.terms.value;
    drawSolidCols(icons, update, valid, "termsNat", val);
    var terms = document.getElementById("termsNat");
    if (val !== null) {
        terms.innerHTML = "Sí";
    } else {
        terms.innerHTML = "No";
    }
}
function paintTermsLegal(rsp) {
    var bd = document.getElementById("declaration").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var dataCompany = rsp.entry;
    //Declaración
    update = "declaration";
    icons = ["declarationLegalPending", "declarationLegalValid", "declarationLegalRejected"];
    valid = dataCompany.declaration.valid;
    val = dataCompany.declaration.value;
    drawSolidCols(icons, update, valid, "declarationLegal", val);
    var declaration = document.getElementById("declarationLegal");
    if (val !== null) {
        declaration.innerHTML = "Sí";
    } else {
        declaration.innerHTML = "No";
    }
    update = "terms";
    icons = ["termsLegalPending", "termsLegalValid", "termsLegalRejected"];
    valid = dataCompany.terms.valid;
    val = dataCompany.terms.value;
    drawSolidCols(icons, update, valid, "termsLegal", val);
    var terms = document.getElementById("termsLegal");
    if (val !== null) {
        terms.innerHTML = "Sí";
    } else {
        terms.innerHTML = "No";
    }
}

// Tab status Natural
function paintTabStatusNatural(rsp) {
    var dataPerson = rsp.entry;
    var status = dataPerson.status.id;
    var level = dataPerson.level.id;

    if (status === 1) {
        if (!document.getElementById("swichtStatusNatural").classList.contains("active")) {
            document.getElementById("swichtStatusNatural").classList.add("active");
            document.getElementById("swichtStatusLegal").firstElementChild.classList.add("balActive");
        }
    } else {
        if (document.getElementById("swichtStatusNatural").classList.contains("active")) {
            document.getElementById("swichtStatusNatural").classList.remove("active");
            document.getElementById("swichtStatusLegal").firstElementChild.classList.remove("balActive");

        }
    }

    var levelNatural = document.getElementById("levelNatural");
    levelNatural.value = level;
}

// tab basic data natural
function paintTabDataBasicNatural(rsp) {
    var bd = document.getElementById("basic-data").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }

    var icons = []; var valid = ""; var val = ""; var update = "";
    var dataPerson = rsp.entry.person;

    //Venezolano
    update = dataPerson.venezuelan.update;
    icons = ["venezuelanNatPending", "venezuelanNatValid", "venezuelanNatRejected"];
    valid = dataPerson.venezuelan.valid;
    val = dataPerson.venezuelan.value;
    drawSolidCols(icons, update, valid, "venezuelanNat", val);
    var venezuelanLegal = document.getElementById("venezuelanNat");
    if (val === 1) {
        venezuelanLegal.innerHTML = "Sí";
    } else if (val === 0) {
        venezuelanLegal.innerHTML = "No";
    }
    //Americano
    update = dataPerson.american.update;
    icons = ["americanNatPending", "americanNatValid", "americanNatRejected"];
    valid = dataPerson.american.valid;
    val = dataPerson.american.value;
    drawSolidCols(icons, update, valid, "americanNat", val);
    var americanLegal = document.getElementById("americanNat");
    if (val === 1) {
        americanLegal.innerHTML = "Sí";
    } else if (val === 0) {
        americanLegal.innerHTML = "No";
    }

    // firstName
    update = dataPerson.firstname.update;
    icons = ["firstNamePending", "firstNameValid", "firstNameRejected"];
    valid = dataPerson.firstname.valid;
    val = dataPerson.firstname.value;
    drawSolidCols(icons, update, valid, "firstName", val);

    // secondName
    update = dataPerson.secondname.update;
    icons = ["secondNamePending", "secondNameValid", "secondNameRejected"];
    valid = dataPerson.secondname.valid;
    val = dataPerson.secondname.value;
    drawSolidCols(icons, update, valid, "secondName", val);

    // firstLastName
    update = dataPerson.firstlastname.update;
    icons = ["firstLastNamePending", "firstLastNameValid", "firstLastNameRejected"];
    valid = dataPerson.firstlastname.valid;
    val = dataPerson.firstlastname.value;
    drawSolidCols(icons, update, valid, "firstLastName", val);

    // secondLastName
    update = dataPerson.secondlastname.update;
    icons = ["secondLastNamePending", "secondLastNameValid", "secondLastNameRejected"];
    valid = dataPerson.secondlastname.valid;
    val = dataPerson.secondlastname.value;
    drawSolidCols(icons, update, valid, "secondLastName", val);

    // identificationNat
    update = dataPerson.document.type.update;
    icons = ["identificationNatPending", "identificationNatValid", "identificationNatRejected"];
    valid = dataPerson.document.type.valid;
    val = dataPerson.document.type.dsc;
    drawSolidCols(icons, update, valid, "identificationNat", val);

    // number identification numberNat
    update = dataPerson.document.dsc.update;
    icons = ["numberNatPending", "numberNatValid", "numberNatRejected"];
    valid = dataPerson.document.dsc.valid;
    val = dataPerson.document.dsc.value;
    drawSolidCols(icons, update, valid, "numberNat", val);


    // countryEmitionDoc
    update = dataPerson.document.country.update;
    icons = ["countryEmitionDocPending", "countryEmitionDocValid", "countryEmitionDocRejected"];
    valid = dataPerson.document.country.valid;
    val = dataPerson.document.country.dsc;
    drawSolidCols(icons, update, valid, "countryEmitionDoc", val);

    // dateEmition
    update = dataPerson.document.datecreated.update;
    icons = ["dateEmitionPending", "dateEmitionValid", "dateEmitionRejected"];
    valid = dataPerson.document.datecreated.valid;
    val = dataPerson.document.datecreated.formatted;
    drawSolidCols(icons, update, valid, "dateEmition", val);

    // dateExp
    update = dataPerson.document.dateexpiration.update;
    icons = ["dateExpPending", "dateExpValid", "dateExpRejected"];
    valid = dataPerson.document.dateexpiration.valid;
    val = dataPerson.document.dateexpiration.formatted;
    drawSolidCols(icons, update, valid, "dateExp", val);

    // sex 
    update = dataPerson.gender.update;
    icons = ["sexPending", "sexValid", "sexRejected"];
    valid = dataPerson.gender.valid;
    val = dataPerson.gender.value;
    drawSolidCols(icons, update, valid, "sex", val);


    // dateBorn
    update = dataPerson.birthdate.update;
    icons = ["dateBornPending", "dateBornValid", "dateBornRejected"];
    valid = dataPerson.birthdate.valid;
    val = dataPerson.birthdate.formatted;
    drawSolidCols(icons, update, valid, "dateBorn", val);

    // stateCivil
    update = dataPerson.maritalstatus.update;
    icons = ["stateCivilPending", "stateCivilValid", "stateCivilRejected"];
    valid = dataPerson.maritalstatus.valid;
    val = dataPerson.maritalstatus.dsc;
    drawSolidCols(icons, update, valid, "stateCivil", val);


    // phoneNat
    update = dataPerson.phone.update;
    icons = ["phoneNatPending", "phoneNatValid", "phoneNatRejected"];
    valid = dataPerson.phone.valid;
    val = dataPerson.phone.value;
    drawSolidCols(icons, update, valid, "phoneNat", val);


    // countryBorn
    update = dataPerson.birthcountry.update;
    icons = ["countryBornPending", "countryBornValid", "countryBornRejected"];
    valid = dataPerson.birthcountry.valid;
    val = dataPerson.birthcountry.dsc;
    drawSolidCols(icons, update, valid, "countryBorn", val);

}

function drawSolidCols(icons, update, valid, idval, value) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var noColor = "#D5DCE5";
    var parent = document.getElementById(icons[0]).parentElement.parentElement;
    parent.setAttribute("upid", update);
    if (valid === 0) {
        document.getElementById(icons[0]).classList.remove("far");
        document.getElementById(icons[0]).classList.add("fas");
        document.getElementById(icons[0]).dataset.updateLbl = update + "-pending";
        document.getElementById(icons[0]).style.color = colorPending;

        if (document.getElementById(icons[1]).classList.contains("fas")) {
            document.getElementById(icons[1]).classList.remove("fas");
            document.getElementById(icons[1]).classList.add("far");
        }
        document.getElementById(icons[1]).style.color = "";

        if (document.getElementById(icons[2]).classList.contains("fas")) {
            document.getElementById(icons[2]).classList.remove("fas");
            document.getElementById(icons[2]).classList.add("far");
        }
        document.getElementById(icons[2]).style.color = "";
    } else if (valid === 1) {
        document.getElementById(icons[1]).classList.remove("far");
        document.getElementById(icons[1]).classList.add("fas");
        document.getElementById(icons[1]).dataset.updateLbl = update + "-valid";
        document.getElementById(icons[1]).style.color = colorValid;

        if (document.getElementById(icons[0]).classList.contains("fas")) {
            document.getElementById(icons[0]).classList.remove("fas");
            document.getElementById(icons[0]).classList.add("far");
        }
        document.getElementById(icons[0]).style.color = "";

        if (document.getElementById(icons[2]).classList.contains("fas")) {
            document.getElementById(icons[2]).classList.remove("fas");
            document.getElementById(icons[2]).classList.add("far");
        }
        document.getElementById(icons[2]).style.color = "";
    } else if (valid === -1) {
        document.getElementById(icons[2]).classList.remove("far");
        document.getElementById(icons[2]).classList.add("fas");
        document.getElementById(icons[2]).dataset.updateLbl = update + "-invalid";
        document.getElementById(icons[2]).style.color = colorRejected;
        if (document.getElementById(icons[0]).classList.contains("fas")) {
            document.getElementById(icons[0]).classList.remove("fas");
            document.getElementById(icons[0]).classList.add("far");
        }
        document.getElementById(icons[0]).style.color = "";

        if (document.getElementById(icons[1]).classList.contains("fas")) {
            document.getElementById(icons[1]).classList.remove("fas");
            document.getElementById(icons[1]).classList.add("far");
        }
        document.getElementById(icons[1]).style.color = "";
    }
    var ele = document.getElementById(idval);
    ele.innerHTML = value;
}

//tab Data residence Natural
function paintTabDataResidenceNatural(rsp) {
    var bd = document.getElementById("residence-data").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }

    var icons = []; var valid = ""; var val = ""; var update = "";
    var dataPerson = rsp.entry.person;

    //Pais
    update = dataPerson.country.update;
    icons = ["countryResidenceNatPending", "countryResidenceNatValid", "countryResidenceNatRejected"];
    valid = dataPerson.country.valid;
    val = dataPerson.country.dsc;
    drawSolidCols(icons, update, valid, "countryResidenceNat", val);

    //Estado
    update = dataPerson.region.update;
    icons = ["stateResidenceNatPending", "stateResidenceNatValid", "stateResidenceNatRejected"];
    valid = dataPerson.region.valid;
    val = dataPerson.region.dsc;
    drawSolidCols(icons, update, valid, "stateResidenceNat", val);

    //Ciudad
    update = dataPerson.city.update;
    icons = ["cityResidenceNatPending", "cityResidenceNatValid", "cityResidenceNatRejected"];
    valid = dataPerson.city.valid;
    val = dataPerson.city.dsc;
    drawSolidCols(icons, update, valid, "cityResidenceNat", val);

    //Calle
    update = dataPerson.street.update;
    icons = ["directionResidencePending", "directionResidenceValid", "directionResidenceRejected"];
    valid = dataPerson.street.valid;
    val = dataPerson.street.value;
    drawSolidCols(icons, update, valid, "directionResidence", val);

    //Apartamento
    update = dataPerson.home.update;
    icons = ["houseNumberNatPending", "houseNumberNatValid", "houseNumberNatRejected"];
    valid = dataPerson.home.valid;
    val = dataPerson.home.value;
    drawSolidCols(icons, update, valid, "houseNumberNat", val);

    //Codigo postal
    update = dataPerson.postalcode.update;
    icons = ["codePostalNatPending", "codePostalNatValid", "codePostalNatRejected"];
    valid = dataPerson.postalcode.valid;
    val = dataPerson.postalcode.value;
    drawSolidCols(icons, update, valid, "codePostalNat", val);

}

//tab Professional info Natural
function paintTabProfessionalInfoNatural(rsp) {
    var bd = document.getElementById("professional-info").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }
    var icons = []; var valid = ""; var val = ""; var update = "";
    var dataPerson = rsp.entry.person;

    //Profesión
    update = dataPerson.profession.update;
    icons = ["professionPending", "professionValid", "professionRejected"];
    valid = dataPerson.profession.valid;
    val = dataPerson.profession.value;
    drawSolidCols(icons, update, valid, "profession", val);

    //Actividad económica
    update = dataPerson.economicalactivity.update;
    icons = ["economicActNatPending", "economicActNatValid", "economicActNatRejected"];

    valid = dataPerson.economicalactivity.valid;
    val = dataPerson.economicalactivity.value;
    if (val !== null) {
        var select = document.getElementById("economicActNat").nextElementSibling;
        select.value = val;
        val = select.selectedIndex == -1 ? '' : select.options[select.selectedIndex].textContent;
        drawSolidCols(icons, update, valid, "economicActNat", val);
    }
    //Comerciante independiente
    update = dataPerson.independentdealer.update;
    icons = ["dealerIndPending", "dealerIndValid", "dealerIndRejected"];
    valid = dataPerson.independentdealer.valid;
    val = dataPerson.independentdealer.value;
    if (val == 1) val = "Sí";
    else if (val == 0) val = "No";
    else val = "";
    drawSolidCols(icons, update, valid, "dealerInd", val);

    //Comapñia
    update = dataPerson.company.update;
    icons = ["companyNatPending", "companyNatValid", "companyNatRejected"];
    valid = dataPerson.company.valid;
    val = dataPerson.company.value;
    drawSolidCols(icons, update, valid, "companyNat", val);

    //Ocupación
    update = dataPerson.ocupation.update;
    icons = ["ocupationNatPending", "ocupationNatValid", "ocupationNatRejected"];
    valid = dataPerson.ocupation.valid;
    val = dataPerson.ocupation.value.dsc;
    if (val == "null") val = "";
    drawSolidCols(icons, update, valid, "ocupationNat", val);

    //Ingreso anual
    update = dataPerson.anualincome.update;
    icons = ["anualIncomeNatPending", "anualIncomeNatValid", "anualIncomeNatRejected"];
    valid = dataPerson.anualincome.valid;
    val = dataPerson.anualincome.formatted;
    drawSolidCols(icons, update, valid, "anualIncomeNat", val);

    //Patrimonio
    update = dataPerson.patrimony.update;
    icons = ["worthNatPending", "worthNatValid", "worthNatRejected"];
    valid = dataPerson.patrimony.valid;
    val = dataPerson.patrimony.formatted;
    drawSolidCols(icons, update, valid, "worthNat", val);

    //Exposed
    update = dataPerson.politicalexposed.update;
    icons = ["personExposedNatPending", "personExposedNatValid", "personExposedNatRejected"];
    valid = dataPerson.politicalexposed.valid;
    val = dataPerson.politicalexposed.value;
    if (val == 1) {
        val = "Sí"
        var pesronExpClass = document.getElementsByClassName("personExposedNat");
        for (let o = 0; o < pesronExpClass.length; o++) {
            pesronExpClass[o].style.display = "table";
            pesronExpClass[o].classList.add("row-tabCnt");
            pesronExpClass[o].classList.remove("row-tabCntX");

        }
    } else if (val == 0) {
        val = "No";
        var pesronExpClass = document.getElementsByClassName("personExposedNat");
        for (let o = 0; o < pesronExpClass.length; o++) {
            pesronExpClass[o].style.display = "none";
            pesronExpClass[o].classList.add("row-tabCntX");
            pesronExpClass[o].classList.remove("row-tabCnt");
        }
    } else {
        val = "";
        var pesronExpClass = document.getElementsByClassName("personExposedNat");
        for (let o = 0; o < pesronExpClass.length; o++) {
            pesronExpClass[o].style.display = "none";
            pesronExpClass[o].classList.add("row-tabCntX");
            pesronExpClass[o].classList.remove("row-tabCnt");
        }
    }
    drawSolidCols(icons, update, valid, "personExposedNat", val);

    //Name entity
    update = dataPerson.affiliationbody.update;
    icons = ["nameEntityNatPending", "nameEntityNatValid", "nameEntityNatRejected"];
    valid = dataPerson.affiliationbody.valid;
    val = dataPerson.affiliationbody.value;
    drawSolidCols(icons, update, valid, "nameEntityNat", val);

    //Cargo
    update = dataPerson.positionheld.update;
    icons = ["jobPerformsNatPending", "jobPerformsNatValid", "jobPerformsNatRejected"];
    valid = dataPerson.positionheld.valid;
    val = dataPerson.positionheld.value;
    drawSolidCols(icons, update, valid, "jobPerformsNat", val);

    //Position
    update = dataPerson.pepcountryid.update;
    icons = ["countryPersonExposedNatPending", "countryPersonExposedNatValid", "countryPersonExposedNatRejected"];
    valid = dataPerson.pepcountryid.valid;
    val = dataPerson.pepcountryid.dsc;
    drawSolidCols(icons, update, valid, "countryPersonExposedNat", val);

    //ID pep
    update = dataPerson.peprelatedid.update;
    icons = ["identificationPersonExposedNatPending", "identificationPersonExposedNatValid", "identificationPersonExposedNatRejected"];
    valid = dataPerson.peprelatedid.valid;
    val = dataPerson.peprelatedid.value;
    drawSolidCols(icons, update, valid, "identificationPersonExposedNat", val);
}

//tab data Image Natural
function paintTabDataImagesNatural(rsp) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var dataPerson = rsp.entry.person.uploads;
    if (dataPerson != null) {
        for (let i = 0; i < dataPerson.length; i++) {
            // Image i
            var row = document.createElement("div");
            row.classList.add("row-tabCnt");

            var validCol = document.createElement("div");
            validCol.classList.add("validCol");
            var iValid = document.createElement("i");
            var iPending = document.createElement("i");
            var iRejected = document.createElement("i");
            iValid.classList.add("far");
            iValid.classList.add("fa-check-circle");
            iPending.classList.add("far");
            iPending.classList.add("fa-pause-circle");
            iRejected.classList.add("far");
            iRejected.classList.add("fa-times-circle");
            if (dataPerson[i].url !== "") {
                if (dataPerson[i].validated === 0) {
                    iPending.classList.remove("far");
                    iPending.classList.add("fas");
                    iPending.dataset.updateUpload = dataPerson[i].id + "-pending"
                    iPending.style.color = colorPending;
                } else if (dataPerson[i].validated === 1) {
                    iValid.classList.remove("far");
                    iValid.classList.add("fas");
                    iValid.dataset.updateUpload = dataPerson[i].id + "-valid"
                    iValid.style.color = colorValid;
                } else if (dataPerson[i].validated === -1) {
                    iRejected.classList.remove("far");
                    iRejected.classList.add("fas");
                    iRejected.dataset.updateUpload = dataPerson[i].id + "-invalid"
                    iRejected.style.color = colorRejected;
                }
                iValid.addEventListener("click", function () {
                    ActRow(this, 'valid');
                });
                iPending.addEventListener("click", function () {
                    ActRow(this, 'pending');
                });
                iRejected.addEventListener("click", function () {
                    ActRow(this, 'invalid');
                });
            }
            validCol.appendChild(iValid);
            validCol.appendChild(iPending);
            validCol.appendChild(iRejected);

            var fieldCol = document.createElement("div");
            fieldCol.classList.add("fieldCol");
            var p = document.createElement("p");
            if (dataPerson[i].dsc) {
                p.innerHTML = dataPerson[i].dsc;
            } else {
                p.innerHTML = "";
            }
            fieldCol.appendChild(p);
            fieldCol.style.width = "70%";

            var infoCol = document.createElement("div");
            infoCol.classList.add("infoCol");
            var iEye = document.createElement("i");
            iEye.classList.add("fas");
            iEye.classList.add("fa-eye");
            iEye.style.color = "#4287CE";
            iEye.dataset.url = dataPerson[i].url;
            if (dataPerson[i].url == "") iEye.style.display = "none";
            else iEye.style.display = "";
            infoCol.style.width = "10%";
            infoCol.style.textAlign = "left";
            infoCol.appendChild(iEye);
            iEye.addEventListener("click", function () {
                //document.getElementById("modalImage").style.display = "block";
                var url = this.dataset.url;
                window.open(url, '_blank');
                /*
                setTimeout(function(){
                    document.getElementById("imageSupport").style.backgroundImage = 'url('+url+')';
                    document.getElementById("modalImage").style.opacity = "1";
                },300);*/
            });
            /*
            iEye.addEventListener("click", function(){
                document.getElementById("modalImage").style.display = "block";
                var url = this.dataset.url;
                setTimeout(function(){
                    document.getElementById("imageSupport").style.backgroundImage = 'url('+url+')';
                    document.getElementById("modalImage").style.opacity = "1";
                },300);
            });*/
            /*if(dataPerson[i].url=="")iEye.style.display = "none";
            iEye.addEventListener("click", function(){
                document.getElementById("modalImage").style.display = "block";
                document.getElementById("imageSupport").src = this.dataset.url;
            });*/

            if (i % 2 !== 0) {
                row.classList.add("rowImpar");
            }
            row.appendChild(validCol);
            row.appendChild(fieldCol);
            row.appendChild(infoCol);
            row.dataset.idImgLegal = dataPerson[i].id;

            var tabPartners = document.getElementById("support-images");
            row.dataset.image = "imagesNautralRemovible";
            tabPartners.children[1].children[0].children[0].children[0].appendChild(row);
        }
    }
}

//tab data transaction natural
function paintTabDataTransactionNatural(rsp) {
    var bd = document.getElementById("transaction-data").getElementsByClassName("row-tabCnt");
    //i = 1 Ignora la primera linea 
    for (var i = 1; i < bd.length; i++) {
        bd[i].classList.remove("rowImpar");
        if (i % 2 == 0)
            bd[i].classList.add("rowImpar");
    }

    var icons = []; var valid = ""; var val = ""; var update = "";
    var dataPerson = rsp.entry.person;

    //Cantidad operaciones
    update = dataPerson.qtyoperationsmothly.update;
    icons = ["averageMonthActNatPending", "averageMonthActNatValid", "averageMonthActNatRejected"];
    valid = dataPerson.qtyoperationsmothly.valid;
    val = dataPerson.qtyoperationsmothly.value;
    drawSolidCols(icons, update, valid, "averageMonthActNat", val);

    //Monto de operaciones
    update = dataPerson.amooperationsmonthly.update;
    icons = ["mountOpNatPending", "mountOpNatValid", "mountOpNatRejected"];
    valid = dataPerson.amooperationsmonthly.valid;
    val = dataPerson.amooperationsmonthly.number;
    drawSolidCols(icons, update, valid, "mountOpNat", val);

    //Tipo de operacion
    update = dataPerson.preferoptype.update;
    icons = ["typeOpNatPending", "typeOpNatValid", "typeOpNatRejected"];
    valid = dataPerson.preferoptype.valid;
    val = '';

    if (dataPerson.preferoptype.id != null) {
        let vals = dataPerson.preferoptype.id.split("-");
        for (let i = 0; i < vals.length; i++) {
            switch (parseInt(vals[i])) {
                case 1: val += (i == 0 ? "Cripto - Cripto" : ", Cripto - Cripto"); break;
                case 2: val += (i == 0 ? "Cripto - Dinero Fiat" : ", Cripto - Dinero Fiat"); break;
                case 3: val += (i == 0 ? "Dinero Fiat - Cripto" : ", Dinero Fiat - Cripto"); break;
            }
        }
    }

    drawSolidCols(icons, update, valid, "typeOpNat", val);

    //Relación económica
    update = dataPerson.economicrelation.update;
    icons = ["relationGruopNatPending", "relationGruopNatValid", "relationGruopNatRejected"];
    valid = dataPerson.economicrelation.valid;
    val = dataPerson.economicrelation.value;
    if (val == 1) val = "Sí";
    else if (val == 0) val = "No";
    else val = '';
    drawSolidCols(icons, update, valid, "relationGruopNat", val);
}

// tab accounts natural
function paintTabAccountsNatural(rsp) {
    var colorPending = '#f5ac3e';
    var colorRejected = '#c25462';
    var colorValid = '#85bb50';
    var dataPerson = rsp.entry.accounts;
    if (dataPerson) {
        for (let i = 0; i < dataPerson.length; i++) {
            var lines = 0;
            if (dataPerson[i].paymentmethod.details1 != null) lines = 1;
            if (dataPerson[i].paymentmethod.details2 != null) lines = 2;
            if (dataPerson[i].paymentmethod.details3 != null) lines = 3;
            if (dataPerson[i].paymentmethod.details4 != null) lines = 4;
            for (var x = 0; x < lines; x++) {
                // Account i
                var row = document.createElement("div");
                row.classList.add("row-tabCnt");

                var validCol = document.createElement("div");
                validCol.classList.add("validCol");
                var iValidAccount = document.createElement("i");
                var iPendingAccount = document.createElement("i");
                var iRejectedAccount = document.createElement("i");
                iValidAccount.classList.add("far");
                iValidAccount.classList.add("fa-check-circle");
                iPendingAccount.classList.add("far");
                iPendingAccount.classList.add("fa-pause-circle");
                iRejectedAccount.classList.add("far");
                iRejectedAccount.classList.add("fa-times-circle");
                if (dataPerson[i]['details' + (x + 1)].valid === 0) {
                    iPendingAccount.classList.remove("far");
                    iPendingAccount.classList.add("fas");
                    iPendingAccount.dataset.updateAcc = 'details' + (x + 1) + "-pending";
                    iPendingAccount.style.color = colorPending;
                } else if (dataPerson[i]['details' + (x + 1)].valid === 1) {
                    iValidAccount.classList.remove("far");
                    iValidAccount.classList.add("fas");
                    iValidAccount.dataset.updateAcc = 'details' + (x + 1) + "-valid";
                    iValidAccount.style.color = colorValid;
                } else if (dataPerson[i]['details' + (x + 1)].valid === -1) {
                    iRejectedAccount.classList.remove("far");
                    iRejectedAccount.classList.add("fas");
                    iRejectedAccount.style.color = colorRejected;
                    iRejectedAccount.dataset.updateAcc = 'details' + (x + 1) + "-invalid";

                }
                iValidAccount.addEventListener("click", function () {
                    ActRow(this, 'valid');
                });
                iPendingAccount.addEventListener("click", function () {
                    ActRow(this, 'pending');
                });
                iRejectedAccount.addEventListener("click", function () {
                    ActRow(this, 'invalid');
                });
                validCol.appendChild(iValidAccount);
                validCol.appendChild(iPendingAccount);
                validCol.appendChild(iRejectedAccount);

                var fieldName = document.createElement("div");
                fieldName.classList.add("fieldCol");
                var p = document.createElement("p");
                if (x == 0) {
                    p.innerHTML = dataPerson[i].paymentmethod.name + "(" + dataPerson[i].currency.symbol + ")";
                } else {
                    p.innerHTML = "";
                }
                fieldName.appendChild(p);
                fieldName.style.width = "30%";

                var fieldCol = document.createElement("div");
                fieldCol.classList.add("fieldCol");
                var p = document.createElement("p");
                p.innerHTML = dataPerson[i].paymentmethod["details" + (x + 1)];
                fieldCol.style.width = "20%";
                fieldCol.appendChild(p);

                var infoCol = document.createElement("div");
                infoCol.classList.add("infoCol");
                var infcnt = document.createElement("p");
                infcnt.innerHTML = dataPerson[i]["details" + (x + 1)].value;
                infoCol.style.width = "30%";
                infoCol.appendChild(infcnt);

                if (x % 2 !== 0) {
                    row.classList.add("rowImpar");
                }
                row.appendChild(validCol);
                row.appendChild(fieldName);
                row.appendChild(fieldCol);
                row.appendChild(infoCol);

                var tabPartners = document.getElementById("retirement-accounts");
                row.dataset.account = "accountsNaturalRemovible";
                row.dataset.accountid = dataPerson[i].id;
                tabPartners.children[0].lastElementChild.appendChild(row);
            }
        }
    }

}

//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];
                tagsInpt.addEventListener("keyup", function (e) {
                    if (this.value.length > 0) {
                        if (this.value[0] !== "#") this.value = "#" + this.value;
                    }
                });
            }

        }
    }, 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);
        }
    }
}
var levelreqList = [];
function drawLevelMarks(tbl) {
    var modal = document.getElementById(tbl);
    var levelList = modal.getElementsByClassName("drawLevelLines");
    var ptype = 1;
    //|| levelreqList[y].partnerfields.indexOf("upid",0)>0
    //Recorre todas las listas que requieren verificación para nivel
    for (var i = 0; i < levelList.length; i++) {
        var linescnt = levelList[i].parentElement.previousElementSibling;
        levelList[i].innerHTML = "";
        if (linescnt) {
            var lines = linescnt.getElementsByClassName("row-tabCnt");
            for (var x = 0; x < lines.length; x++) {
                var row = document.createElement("div");
                row.classList.add("row-tabCnt");
                var lvl05 = document.createElement("div");
                lvl05.classList.add("checklvlCell");
                var lvl1 = document.createElement("div");
                lvl1.classList.add("checklvlCell");
                var lvl2 = document.createElement("div");
                lvl2.classList.add("checklvlCell");
                var lvl3 = document.createElement("div");
                lvl3.classList.add("checklvlCell");
                var iPay = document.createElement("i");
                var iValid = document.createElement("i");
                var iPending = document.createElement("i");
                var iRejected = document.createElement("i");

                var color = "#D5DCE5";
                var classIc = "far";
                var upid = lines[x].getAttribute("upid");
                if (upid == undefined) {
                    upid = parseFloat(lines[x].getAttribute("data-id-img-legal"));
                }
                var lvlpos = -1;
                if (upid !== "") {
                    for (var y = 0; y < levelreqList.length; y++) {
                        if (levelreqList[y].typefields.indexOf(upid, 0) >= 0 || levelreqList[y].partnerfields.indexOf(upid, 0) >= 0 || levelreqList[y].uploadsId.indexOf(upid, 0) >= 0) {
                            lvlpos = levelreqList[y].level;
                            classIc = "fas";
                            color = "#C04F5D";
                        }
                    }
                } else {
                    classIc = "fas";
                    color = "#C04F5D";
                }

                var type = "times";
                if (upid == "terms" || lvlpos == 0.5) {
                    color = "#4287CE";
                    classIc = "fas";
                    type = "check";
                }
                iPay.classList.add(classIc);
                iPay.classList.add("fa-" + type + "-circle");
                iPay.style.color = color;

                iValid.classList.add(classIc);
                if (lvlpos <= 1 && classIc == "fas") {
                    type = "check";
                    color = "#4287CE";
                }
                iValid.classList.add("fa-" + type + "-circle");
                iValid.style.color = color;
                iPending.classList.add(classIc);
                if (lvlpos <= 2 && classIc == "fas") {
                    type = "check";
                    color = "#4287CE";
                }
                iPending.classList.add("fa-" + type + "-circle");
                iPending.style.color = color;

                iRejected.classList.add(classIc);
                if (lvlpos <= 3 && classIc == "fas") {
                    type = "check";
                    color = "#4287CE";
                }
                iRejected.classList.add("fa-" + type + "-circle");
                iRejected.style.color = color;
                lvl05.appendChild(iPay);
                lvl1.appendChild(iValid);
                lvl2.appendChild(iPending);
                lvl3.appendChild(iRejected);
                row.style.height = lines[x].offsetHeight + "px";
                row.appendChild(lvl05);
                row.appendChild(lvl1);
                row.appendChild(lvl2);
                row.appendChild(lvl3);
                if (x % 2 !== 0 && x > 0) {
                    row.classList.add("rowImpar");
                }

                levelList[i].appendChild(row);
            }
        }
    }
}

//Función para cargar listado
function loadActs() {
    var par = {};
    par.filter = "";
    par.order = "1";
    par.offset = 0;
    par.numofrec = 9999;
    par.sessionid = sessionStorage.getItem("sessionId");
    //Especifico el servicio, los parametros y la funcion de retorno del listado listado
    callWS("GET", "economicact/list", par, respList);
    return 0;
}
function respList(status, rsp) {
    var resp = JSON.parse(rsp);
    var msg = document.getElementById("messageApi");
    switch (status) {
        case 200:
            if (resp.records.length) {
                var select = document.getElementById("economicAct").nextElementSibling;
                var select1 = document.getElementById("economic");
                select.innertHTML = "";
                select1.innerHTML = "";
                for (let i = 0; i < resp.records.length; i++) {
                    var option = document.createElement("option");
                    option.innerHTML = resp.records[i].dsc == "" ? resp.records[i].dsc_eng : resp.records[i].dsc;
                    option.value = resp.records[i].id;
                    select.appendChild(option);

                    var opt2 = option.cloneNode(true);
                    select1.appendChild(opt2);
                }
            }
            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;
            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 actividades económicas";
            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);
    }
}


/*
var listDelayed=0;
var listField;
function searchTags(){
    listField = this;
    if (listDelayed) {
        clearTimeout(listDelayed);
        listDelayed = 0;
    }
    if(this.value == undefined){
        if(document.getElementsByClassName("tagInptEle").length>0){
            var tagCnt = document.getElementsByClassName("tagInptEle")[0]
            listField = tagCnt.getElementsByTagName("input")[0];
        }
    }
    listDelayed = setTimeout(function(){
        if (listField.value.length <= 2) return;
        var url = "sites/tagslist";
        var parms = {};
        parms.sessionid = getParameterByName('sessionid');
        /*
        if (listField.id == "benefidInpt")
            params.benefid = listField.value;
        else
            params.benefname = listField.value;
        parms.filter = listField.value;
        var eventid = getParameterByName('hdeventid');
        if(eventid === "")eventid = document.getElementById("cngrsSel").value;
        parms.eventid = eventid;
        var onsucces = function(rsp,status){
            switch (status){
                case 200:
                    console.log(rsp);
                    drawTagsList("tagsList", rsp);
                    listDelayed = 0;
                    break;
                default:
                    console.log(rso);
                    console.log(respText);
                break;
            }
        };
        callWS("GET", url, parms, onsucces);
    }, 500);
}
function drawTagsList(id, rsp){
    var list = document.getElementById(id);
    if (list === null)
        list = document.createElement("DIV");
    else
        list.innerHTML = "";
    list.classList.add("stdList", "benefList");
    list.id = "tagsList";
    var width = document.getElementsByClassName("tagInptEle")[0].offsetWidth;
    list.setAttribute("style", "width:"+width+"px");
    
    var cont = document.createElement("DIV");
    cont.classList.add("listTbl");
    var fila, cell;
    for (var i=0; i<rsp.records.length; i++){
        fila = document.createElement("DIV");
        fila.classList.add("listRow");
        cell = document.createElement("DIV");
        /*cell.setAttribute("data-id", rsp.records[i].id);
        cell.setAttribute("data-benefid", rsp.records[i].benefid);
        cell.setAttribute("data-benefdsc", rsp.records[i].benefdsc);
        cell.addEventListener("mousedown", selTag);
        cell.classList.add("listCell");
        cell.innerHTML = rsp.records[i];
        fila.appendChild(cell);
        cont.appendChild(fila);
    }
    if (rsp.more){
        fila = document.createElement("DIV");
        fila.classList.add("listRow");
        cell = document.createElement("DIV");
        cell.classList.add("listCell", "listCellLastLine");
        cell.innerHTML = 'Hay demasiados registros, mejore la búsqueda';
        fila.appendChild(cell);
        cont.appendChild(fila);
    }
    list.appendChild(cont);
    listField.parentNode.parentNode.appendChild(list);
}
function selTag(){
    var tagsInpt = document.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0];
    tagsInpt.value = this.innerHTML;
    tagsInpt.dispatchEvent(new Event('paste'));
}
function destroyList(listName){
    var list = document.getElementById(listName);
    if (list !== null)list.parentNode.removeChild(list);
}*/