//Variables globales
var cleared = null;
var sessionId = sessionStorage.getItem("sessionId");
var dataC = false;

window.onload = function () {
    initApp();
    tagLoad()

    document.getElementById('informsList').addEventListener('change', function () {
        console.log(this.value);
        if (this.value != 0) {
            let parameterUserName = getParameterByName("userName");
            gotoPage("menu", this.value, { "userName": parameterUserName });
        }
    });

    document.getElementById("search").addEventListener("change", function () {
        loadList();
    });

    document.getElementById("feeInput").addEventListener("change", function () {
        loadList();
    });

    document.getElementById("feeTag").addEventListener("focusout", function () {
        loadList();
    });

    document.getElementById("addDate").addEventListener("focusout", function () {
        // Fecha desde
        // Validamos que sea menor o igual a la fecha final

        if (document.getElementById('addDate1').value == '') {
            loadList();
        } else {
            if (this.value <= document.getElementById('addDate1').value) {
                loadList();
            } else {
                let msg = document.getElementById('msgInTable');

                msg.innerHTML = "Fecha inicial debe ser menor o igual a la fecha final";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
            }
        }
    });

    document.getElementById("addDate1").addEventListener("focusout", function () {
        // Fecha hasta
        // Validamos que sea mayor o igual a la otra fecha inicial

        if (document.getElementById("addDate").value == '') {
            loadList();
        } else {
            if (this.value >= document.getElementById("addDate").value) {
                loadList();
            } else {
                let msg = document.getElementById('msgInTable');

                console.log(msg);
                msg.innerHTML = "Fecha final debe ser mayor o igual a la fecha inicial";
                msg.classList.add("msgError");
                msg.style.display = "block";
                setTimeout(function () {
                    msg.classList.remove("msgError");
                    msg.style.display = "none";
                }, 3000);
            }
        }
    });

    document.getElementById("cmsFilter").addEventListener("change", function () {
        loadList();
    });

    document.getElementById("groupTagNatural").addEventListener("click", function () {
        document.getElementById("feeTag").focus();
    });
    window.addEventListener("click", function () {
        var div = document.getElementById("searchResult");
        div.classList.add("noShow");
    });
}

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;
                    }
                    //SECCION DE BUSQUEDA DE TAGS
                    if (this.value.length >= 2) {
                        if (cleared !== null) {
                            clearTimeout(cleared);
                        }
                        cleared = setTimeout(function () {
                            myTags(document.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0].value.replace("#", ""));
                        }, 1000);
                    }
                });
            }

        }
    }, 100);
    document.getElementById('principalDiv').style.visibility = "initial"
}
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);
        }
    }
}
function myTags(value) {
    var par = {};
    par.filter = value;
    par.sessionid = sessionId;
    callWS("GET", "tags/list", par, rspTags);
    return 0;
}
function rspTags(status, rsp) {
    switch (status) {
        case 200:
            // console.log(JSON.parse(rsp));
            var resp = JSON.parse(rsp);
            var lista = document.getElementById("resultsC");
            var div = document.getElementById("searchResult");
            div.classList.remove("noShow");
            mySearchAdd(lista, resp.records, resp.numofrecords);
            break;
        case 400:
            console.log(JSON.parse(rsp));
            break;
        case 401:
            msg.innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            msg.classList.add("msgError");
            msg.style.display = "block";
            setTimeout(function () {
                msg.classList.remove("msgError");
                myLogout()
                msg.style.display = "none";
            }, 3000);
            break;
        case 403:
            console.log(JSON.parse(rsp));
            break;
        case 500:
            var resSeller = JSON.parse(rsp);
            alert("Error 500 " + resSeller.msg);
            console.log(JSON.parse(rsp));
            break;
        default:
        //console.log(rsp);
    }
}
function mySearchAdd(lista, data, num) {
    lista.innerHTML = "";
    if (num === 0) {
        var line = document.createElement("li");
        line.innerHTML = '<span class="smallRsp">No tenemos registros que coincidan con su busqueda.</span>';
        lista.appendChild(line);
    } else {
        for (navLink of data) {
            var line = document.createElement("li");
            line.classList.add("myNewLineUser");
            line.innerHTML = '<p class="nameResult"> ' + navLink + '</p>';
            lista.appendChild(line);
        }
    }
    document.querySelectorAll('[class="myNewLineUser"]').forEach(function (element) {
        element.addEventListener('mousedown', function (event) {
            var inpt = document.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0];
            inpt.value = this.children[0].innerText;
        });
        element.addEventListener('click', function (event) {
            setTimeout(function () {
                var inpt = document.getElementsByClassName("tagInptEle")[0].getElementsByTagName("input")[0];
                inpt.value = "";
            }, 500);
        });
    });
}



function callDownload() {
    /*var filter =document.getElementById("search").value;
    var modul =document.getElementById("modulFilter").value;
    var order = document.getElementById("orderBy").value;
    order = Math.abs(order);
    var dir = document.getElementById("orderDirect").value;
    if(dir=="desc")order="-"+order;
    order = order;

    download("audit/listcsv?filter="+filter+"&modul="+modul+"&order="+order+"&sessionid="+sessionId);
    return;*/

    var tagBar = document.getElementsByClassName("tag");
    var parmTag = "";
    if (tagBar.length > 0) {
        for (var i = 0; i < tagBar.length; i++) {
            parmTag += tagBar[i].getAttribute("data-tag") + "-";
        }
        parmTag = parmTag.substr(0, parmTag.length - 1);
    }

    var req = {
        "filter": document.getElementById("search").value,
        "order": document.getElementById("cmsFilter").value,
        "datefrom": document.getElementById("addDate").value,
        "dateto": document.getElementById("addDate1").value,
        "sessionid": sessionId,
        "fee": document.getElementById("feeInput").value,
        "tags": parmTag
    }

    //totalsoftware.la/~afxuser/dev/cms/api/reports/feealliesreport?filter=&order=1&datefrom=2020-10-10&dateto=2021-10-10&sessionid=wlqosJpCLWW9Enfu8f3pw5BAXFhlV8pp&fee=50&tags=%23testing

    download("reports/feealliesreport.php?sessionid=" + encodeURIComponent(req.sessionid) + "&filter=" + encodeURIComponent(req.filter) + "&order=" + encodeURIComponent(req.order) + "&datefrom=" + encodeURIComponent(req.datefrom) + "&dateto=" + encodeURIComponent(req.dateto) + "&fee=" + encodeURIComponent(req.fee) + "&tags=" + encodeURIComponent(req.tags));
    return;
}

function loadReportsFeealliesDummy() {

    var req = {
        "filter": '',
        "order": '1',
        "datefrom": '01/01/2000',
        "dateto": '01/01/2500',
        "sessionid": sessionId,
        "fee": 50,
        "tags": "#testing"
    }
    console.log(req)

    callWS("GET", "reports/feeallies", req, respLOadReportsFeeallies);
}

//Función para cargar listado
function loadList() {

    if (verifyData()) {

        document.getElementById('bodyTableCurrencies').style.display = "none"
        document.getElementById('noCurrencieDefine').style.display = "none"

        var tagBar = document.getElementsByClassName("tag");
        var parmTag = "";
        if (tagBar.length > 0) {
            for (var i = 0; i < tagBar.length; i++) {
                parmTag += tagBar[i].getAttribute("data-tag") + "-";
            }
            parmTag = parmTag.substr(0, parmTag.length - 1);
        }

        var req = {
            "filter": document.getElementById("search").value,
            "order": document.getElementById("cmsFilter").value,
            "datefrom": document.getElementById("addDate").value,
            "dateto": document.getElementById("addDate1").value,
            "sessionid": sessionId,
            "fee": document.getElementById("feeInput").value,
            "tags": parmTag
        }

        console.log(req)

        callWS("GET", "reports/feeallies", req, respLOadReportsFeeallies);
        return 0;
    } else {
        document.getElementById('serviceTable').style.display = "none"
    }
}

function verifyData() {
    document.getElementById('noServiceTable').style.display = "none"
    var ok = true;
    var arrayData = []
    if (!document.getElementById("addDate").value) {
        arrayData.push('Fecha inicial')
    }
    if (!document.getElementById("addDate1").value) {
        arrayData.push('Fecha Final')
    }
    if (!document.getElementById("feeInput").value) {
        arrayData.push('Comisión')
    }
    if (!document.getElementById("feeTag").value) {
        arrayData.push('Etiquetas')
    }

    if (arrayData.length > 0) {
        ok = false
        if (arrayData.length > 1) {
            document.getElementById('msgInTable').innerHTML = "Faltan los siguientes datos: "
            for (var i = 0; i < arrayData.length; i++) {
                if (i + 1 == arrayData.length) {
                    document.getElementById('msgInTable').innerHTML += ' y ' + arrayData[i] + '.'
                } else {
                    document.getElementById('msgInTable').innerHTML += arrayData[i] + ', '
                }
            }
        } else {
            document.getElementById('msgInTable').innerHTML = "Falta el siguiente dato: " + arrayData[0] + '.'
        }
        document.getElementById('bodyTableCurrencies').style.display = "table"
        document.getElementById('noCurrencieDefine').style.display = "table-cell"
    }
    return ok
}

function setTableModel() {
    document.getElementById('serviceTable').innerHTML = `
                                        <div style="display: table; width: 94%; padding: 0% 3%;margin-top: 5px;">
                                            <div style="display: table-cell; width: calc(100% - 45px); vertical-align: middle; height: 45px;">
                                                <p class="infT" id="infT">
                                                </p>
                                            </div>
                                            <div style="display: table-cell; width: 45px; vertical-align: middle;">
                                                 <div class="circledown" id="downloadData" style="width: 45px;">
                                                    <i class="fa fa-download blue" aria-hidden="true"></i>
                                                </div>
                                            </div>
                                        </div>
                                        <div id="reportImp">
                                            <div class="tableInf">
                                                <div class="tableInfName">
                                                    <!--Name-->
                                                    <p></p>
                                                </div>
                                                
                                                <!-- Accounts  children[1]-->
                                                <div class="curAc">
                                                    <div class="acInf">
                                                        <!-- Currency -->
                                                        <div class="tableInfCurrency">
                                                            <p> <span class="tableInfNamePrincipal">Bitcoin  - </span>  <span class="spanIcon" style="background-image:url('./img/01 Regular BW/SVG/Bitcoin.svg');"></span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <span>  BTC </span> &nbsp;&nbsp;&nbsp; (Creación del wallet el 15/12/2020) </p>
                                                        </div>
                                                        <!-- Table -->
                                                        <div class="tableTable">
                                                            <div class="headlist">
                                                                <div class="cell1">
                                                                    <span class="colHead"> Fecha  de intercambio </span>
                                                                </div>
                                                                    
                                                                <div class="cell2">
                                                                    <span class="colHead"> Ref. </span>    
                                                                </div>
                                                                
                                                                <div class="cell3">
                                                                    <span class="colHead"> Par </span>    
                                                                </div>
                                                                    
                                                                <div class="cell4">
                                                                    <span class="colHead"> Tipo </span>    
                                                                </div>
                                                                <div class="cell5">
                                                                    <span class="colHead"> # Orden </span>    
                                                                </div>
                                                                
                                                                <div class="cell6">
                                                                    <span class="colHead"> Comisión </span>    
                                                                </div>
                                                                    
                                                                <div class="cell7">
                                                                    <span class="colHead"> Monto Fee con % </span>    
                                                                </div>
                                                            </div>
                                                            <div class="feesTTT">
                                                                <div class="tableLine">
                                                                    <div class="cell1">
                                                                        <div class="divCellCnt">
                                                                            <span class="dateInput">15/12/2020</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell2">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">123</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell3">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">BTC/VES</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell4">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">Compra</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell5">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">210134</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell6">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">0,01</span>
                                                                        </div>
                                                                    </div>
                                                                    <div class="cell7">
                                                                        <div class="divCellCnt">
                                                                            <span id="inputSymbol0">0,0005</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div>
                                                                    <div class="tableLine tableSubtotal">
                                                                        <div class="cellSubtotal1">
                                                                            <div class="divCellCnt">
                                                                                <span>Subtotal Bitcoin</span>
                                                                            </div>
                                                                        </div>
                                                                        <div class="cellSubtotal2">
                                                                            <div class="divCellCnt">
                                                                                <span>0,0105</span>
                                                                            </div>
                                                                        </div>
                                                                        <div class="cellSubtotal3">
                                                                            <div class="divCellCnt">
                                                                                <span>0,00525</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <!-- Subtotal  children[2]-->
                                                <div>
                                                    <div>
                                                        <div class="tableLine tableSubtotalPerson">
                                                            <div class="cellSubtotalPerson1">
                                                                <div class="divCellCnt">
                                                                    <div style="display: table-cell; width: 100%">
                                                                        <span class="tagNameSubt" style="text-align: left;margin-left: 16px;width: calc(100% - 20px);"></span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="cellSubtotalPerson2 totalsClassS">
                                                                <div style="display:table; width: 100%; height: 38px;">
                                                                    <div class="divCellCnt" style="border-right: 1px solid white !important; vertical-align: middle;">
                                                                        <div style="display: table; width: 100%">
                                                                            <div style="display: table-cell;">
                                                                                <span style="text-align: left;margin-left: 16px;">Petro</span>
                                                                            </div>
                                                                            <div style="display: table-cell;">
                                                                                <span style="display: initial;padding-right: 10px;">0,00525000</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="divCellCnt" style="vertical-align: middle;">
                                                                        <div style="display: table; width: 100%">
                                                                            <div style="display: table-cell;">
                                                                                <span style="text-align: left;margin-left: 16px;">VES</span>
                                                                            </div>
                                                                            <div style="display: table-cell;">
                                                                                <span style="display: initial;padding-right: 10px;">0,00</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>  
                                        <div class="tableInf">
                                            <div>
                                                <div>
                                                    <div class="tableLine tableSubtotalPerson">
                                                        <div class="cellSubtotalPerson1">
                                                            <div class="divCellCnt">
                                                                <div style="display: table-cell; width: 100%">
                                                                    <span id="tagName" style="text-align: left;margin-left: 16px; width: calc(100% - 20px);"></span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="cellSubtotalPerson2" id="totalsClass">
                                                            <div style="display:table; width: 100%; height: 38px;">
                                                                <div class="divCellCnt" style="border-right: 1px solid white !important; vertical-align: middle;">
                                                                    <div style="display: table; width: 100%">
                                                                        <div style="display: table-cell;">
                                                                            <span style="text-align: left;margin-left: 16px;"></span>
                                                                        </div>
                                                                        <div style="display: table-cell;">
                                                                            <span style="display: initial;padding-right: 10px;"></span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="divCellCnt" style="vertical-align: middle;">
                                                                    <div style="display: table; width: 100%">
                                                                        <div style="display: table-cell;">
                                                                            <span style="text-align: left;margin-left: 16px;"></span>
                                                                        </div>
                                                                        <div style="display: table-cell;">
                                                                            <span style="display: initial;padding-right: 10px;"></span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div>
                                                <div>
                                                    <div class="tableLine tableSubtotalPerson" style="border-top: 1px solid white;">
                                                        <div class="cellSubtotalFinal1">
                                                            <div class="divCellCnt">
                                                                <span id="inputName0">Total Bolívares a pagar FEE</span>
                                                            </div>
                                                        </div>
                                                        <div class="cellSubtotalFinal2">
                                                            <div class="divCellCnt">
                                                                <span id="totalVESinffee"></span>
                                                            </div>
                                                        </div>
                                                        <div class="cellSubtotalFinal3">
                                                            <div class="divCellCnt">
                                                                <!--<span id="inputSymbol0">Nota: Considerando tasas de cambio indicadas por usuario en input</span>-->
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>`

    document.getElementById('serviceTable').style.display = "initial"
    document.getElementById('noServiceTable').style.display = "none"

    addEvents()
}

function addEvents() {
    document.getElementById("downloadData").addEventListener('click', function () {
        callDownload();
    });
}

function respLOadReportsFeeallies(status, rsp) {
    switch (status) {
        case 200:
            setTableModel()
            putInf(JSON.parse(rsp))
            //if(currencies.records!==null)addOptions("modulFilter",currencies.records);
            break;
        case 400:
            console.log(rsp);
            break;
        case 401:
            document.getElementById('msgInTable').innerHTML = "Sesión expirada o inválida, vuelva a iniciar sesión";
            document.getElementById('msgInTable').classList.add("msgError");
            document.getElementById('msgInTable').style.display = "block";
            setTimeout(function () {
                document.getElementById('msgInTable').classList.remove("msgError");
                myLogout()
                document.getElementById('msgInTable').style.display = "none";
            }, 3000);
            break;
        case 403:
            document.getElementById('msgInTable').innerHTML = JSON.parse(rsp).msg;
            document.getElementById('msgInTable').classList.add("msgError");
            document.getElementById('msgInTable').style.display = "block";
            document.getElementById('bodyTableCurrencies').style.display = "table"
            document.getElementById('noCurrencieDefine').style.display = "table-cell"
            break;
        case 500:
            console.log(rsp);
            break;
        default:
            console.log(rsp);
    }
}

function putInf(inf) {
    console.log(inf)
    putRates(inf)
    putTags(inf)
    putTotalVes(inf)
    putTotals(inf)
    putRecords(inf)
}

function putRates(inf) {
    var temporalRates = "Tasa de cambio vigente: "
    if (inf.rates[0]) {
        temporalRates += "&nbsp;&nbsp;&nbsp;" + inf.rates[0].pair + "&nbsp;&nbsp;&nbsp;<span>" + inf.rates[0].lastprice.formatted + " </span>&nbsp;&nbsp;&nbsp;"
    }
    for (i = 1; i < inf.rates.length; i++) {
        temporalRates += "| &nbsp;&nbsp;&nbsp;" + inf.rates[i].pair + "&nbsp;&nbsp;&nbsp;<span>" + inf.rates[i].lastprice.formatted + " </span>&nbsp;&nbsp;&nbsp;"
    }
    document.getElementById('infT').innerHTML = temporalRates
}

function putTotalVes(inf) {
    document.getElementById('totalVESinffee').innerHTML = inf.totalVES ? inf.totalVES.formatted : 'N/A'
}

function putTags(inf) {
    document.getElementById('tagName').innerHTML = "Totales Fee " + inf.tags
}

function putTotals(inf) {
    drawTotals(inf.totals)
}

function drawTotals(rsp) {
    var tbl;
    var node;
    var error;
    var withWhiteBorder;
    var withoutWhiteBorder
    tbl = document.getElementById('totalsClass').children[0]
    node = tbl.children[0].cloneNode(true);
    error = tbl.children[0].cloneNode(true);
    withWhiteBorder = tbl.children[0]
    withoutWhiteBorder = tbl.children[1]
    tbl.innerHTML = "";
    //tbl.appendChild(error);
    var tmp = null; tmp = node.cloneNode(true);
    if ((rsp.numofrecords == 0)) {
        //var ele = null;
        //ele = tmp.cloneNode(true);
        //ele.style.display = "none";
        //tbl.appendChild(ele);
    } else {
        for (var i = 0; i < rsp.length; i++) {
            var ele = null;
            if (i + 1 == rsp.length) {
                ele = withoutWhiteBorder.cloneNode(true);
            } else {
                ele = withWhiteBorder.cloneNode(true);
            }
            ele.children[0].children[0].children[0].innerHTML = rsp[i].currency.symbol
            ele.children[0].children[1].children[0].innerHTML = rsp[i].formatted
            ele.style.display = "table-cell";
            ele.style.width = 100 / parseInt(rsp.length) + "%";
            tbl.appendChild(ele);
        }
    }
}

function putRecords(inf) {
    drawReportsInmp(inf.records)
}

function drawReportsInmp(rsp) {
    //console.log(rsp)
    var tbl;
    var node;
    var error;
    tbl = document.getElementById('reportImp')
    node = tbl.children[0].cloneNode(true);
    //error = tbl.children[0].cloneNode(true);
    tbl.innerHTML = "";
    //tbl.appendChild(error);
    var tmp = null; tmp = node.cloneNode(true);
    if ((rsp.numofrecords == 0)) {
        //var ele = null;
        //ele = tmp.cloneNode(true);
        //ele.style.display = "none";
        //tbl.appendChild(ele);
    } else {
        for (var i = 0; i < rsp.length; i++) {

            //console.log('-------------',i)

            var ele = null;
            ele = node.cloneNode(true);

            //console.log(rsp[i])
            // Name  
            ele.children[0].children[0].innerHTML = "<span class='tableInfNamePrincipal'>" + (rsp[i].fullname ? rsp[i].fullname : "N/A") + " </span> " + rsp[i].usr + " &nbsp;&nbsp;&nbsp; (Registrado el " + rsp[i].datecreated.formatted + " )"


            // Accounts
            //var nodeAccounts = null
            //console.log(ele)
            var nodeAccounts = ele.children[1].children[0].cloneNode(true);

            var nodeAccountsInt = ele.children[1].children[0].children[1].children[1].cloneNode(true);

            ele.children[1].innerHTML = ""
            //console.log(ele.children[1])
            //console.log(nodeAccounts)

            if ((rsp[i].accounts.length == 0)) {

            } else {

                var secondDiv, secondDivImg;
                var secondDivE, secondDivImgE;
                for (var j = 0; j < rsp[i].accounts.length; j++) {
                    //console.log(rsp[i].accounts[j])
                    secondDivImg = document.createElement("span")
                    secondDivImg.className = "divImg";
                    secondDiv = document.createElement("div");
                    secondDiv.className = "second";
                    secondDiv = nodeAccounts.cloneNode(true);
                    secondDiv.appendChild(secondDivImg);
                    secondDiv.children[0].children[0].innerHTML = "<span class='tableInfNamePrincipal'>" + rsp[i].accounts[j].currency.name +
                        " - </span>  <span class='spanIcon'>" +
                        "</span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  <span> " + rsp[i].accounts[j].currency.symbol +
                        "</span> &nbsp;&nbsp;&nbsp; " + " (Creación del wallet el " + rsp[i].accounts[j].datecreated.formatted + ")"
                    for (var z = 0; z < icons.length; z++) {
                        if (icons[z].name == rsp[i].accounts[j].currency.name) {
                            secondDiv.children[0].children[0].children[1].setAttribute("style", "background-image:url('" + icons[z].url + "')");
                        }
                    }

                    /*rsp[i].accounts[j].exchanges = [{
                        "id": 1045,
                        "datecreated": {
                            "date": '',
                            "formatted": "10/08/2020"
                        },
                        "pair": "PTR/VES",
                        "order": {
                            "id": 458,
                            "type": "Limit",
                            "side": "Compra"
                        },
                        "feeamount": {
                            "number": 0,
                            "formatted": "2847.05"
                        },
                        "feeallies": {
                            "number": 27,
                            "formatted": "27"
                        }
                    },
                    {
                        "id": 1045,
                        "datecreated": {
                            "date": '',
                            "formatted": "10/08/2020"
                        },
                        "pair": "PTR/VES",
                        "order": {
                            "id": 458,
                            "type": "Limit",
                            "side": "Compra"
                        },
                        "feeamount": {
                            "number": 0,
                            "formatted": "2847.05"
                        },
                        "feeallies": {
                            "number": 27,
                            "formatted": "27"
                        }
                    },
                    {
                        "id": 1045,
                        "datecreated": {
                            "date": '',
                            "formatted": "10/08/2020"
                        },
                        "pair": "PTR/VES",
                        "order": {
                            "id": 458,
                            "type": "Limit",
                            "side": "Compra"
                        },
                        "feeamount": {
                            "number": 0,
                            "formatted": "2847.05"
                        },
                        "feeallies": {
                            "number": 27,
                            "formatted": "27"
                        }
                    }]*/
                    ele.children[1].appendChild(secondDiv);
                }
            }

            tbl.appendChild(ele);

            drawExchange(rsp, i)
            drawSubtotalPerson(rsp, i)
        }
    }
}

function drawSubtotalPerson(rsp, i) {
    //console.log(rsp)
    document.getElementsByClassName('tagNameSubt')[i].innerHTML = "Subtotal " + (rsp[i].fullname ? rsp[i].fullname : "N/A")

    var tbl;
    var node;
    var error;
    var withWhiteBorder;
    var withoutWhiteBorder
    tbl = document.getElementsByClassName('totalsClassS')[i].children[0]
    node = tbl.children[0].cloneNode(true);
    error = tbl.children[0].cloneNode(true);
    withWhiteBorder = tbl.children[0]
    withoutWhiteBorder = tbl.children[1]
    tbl.innerHTML = "";
    var tmp = null; tmp = node.cloneNode(true);
    for (var j = 0; j < rsp[i].accounts.length; j++) {
        var ele = null;
        if (j + 1 == rsp[i].length) {
            ele = withoutWhiteBorder.cloneNode(true);
        } else {
            ele = withWhiteBorder.cloneNode(true);
        }
        ele.children[0].children[0].children[0].innerHTML = rsp[i].accounts[j].currency.symbol
        ele.children[0].children[1].children[0].innerHTML = rsp[i].accounts[j].subtotal.formatted
        ele.style.display = "table-cell";
        ele.style.width = 100 / parseInt(rsp[i].accounts.length) + "%";
        tbl.appendChild(ele);
    }
}

function drawExchange(rsp, i) {
    //console.log('drawExchange')
    //console.log(rsp)
    //console.log(i)
    var tbl;
    var node;
    var subtotal;
    if (rsp[i].accounts.length > 0) {
        var total = document.getElementsByClassName('feesTTT').length
        var me = document.getElementsByClassName('feesTTT').length - rsp[i].accounts.length
        for (var z = 0; z < total; z++) {
            if (document.getElementsByClassName('feesTTT')[z].children.length > 0) {
                tbl = document.getElementsByClassName('feesTTT')[z]
                //console.log(tbl)
                if (document.getElementsByClassName('feesTTT')[z].children.length > 1) {
                    node = tbl.children[0].cloneNode(true);
                    subtotal = tbl.children[1].cloneNode(true);
                } else {
                    subtotal = tbl.children[0].cloneNode(true);
                }
                //console.log('node',node)
            }
            if (z > me - 1) {
                document.getElementsByClassName('feesTTT')[z].innerHTML = "";
            }
        }
        //console.log(tbl)
        for (var j = 0; j < rsp[i].accounts.length; j++) {

            //.log(total)
            var ele = null;
            //console.log(me)
            //console.log(me + j) // Iterar
            ele = node.cloneNode(true);
            ele2 = subtotal.cloneNode(true)
            /*if(i+1 == rsp.length){
                ele = withoutWhiteBorder.cloneNode(true);
            }else{
                ele = withWhiteBorder.cloneNode(true);
            }
            ele.children[0].children[0].children[0].innerHTML = rsp[i].currency.symbol
            ele.children[0].children[1].children[0].innerHTML = rsp[i].formatted
            ele.style.display = "table-cell";
            ele.style.width = 100/parseInt(rsp.length) + "%";*/
            //console.log(me+j)
            //document.getElementsByClassName('feesTTT')[me+j].appendChild(ele); 
            for (var k = 0; k < rsp[i].accounts[j].exchanges.length; k++) {
                ele = node.cloneNode(true);
                if (k % 2 != 0) {
                    ele.classList.add('rowImpar')
                }
                ele.children[0].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].datecreated.formatted
                ele.children[1].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].id
                ele.children[2].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].pair
                ele.children[3].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].order.side
                ele.children[4].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].order.id
                ele.children[5].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].feeamount.formatted
                ele.children[6].children[0].children[0].innerHTML = rsp[i].accounts[j].exchanges[k].feeallies.formatted

                document.getElementsByClassName('feesTTT')[me + j].appendChild(ele);
            }
            //console.log(ele2.children[0].children[0].children[0])
            ele2.children[0].children[0].children[0].children[0].innerHTML = "Subtotal " + rsp[i].accounts[j].currency.name
            ele2.children[0].children[1].children[0].children[0].innerHTML = rsp[i].accounts[j].subtotalFee.formatted
            ele2.children[0].children[2].children[0].children[0].innerHTML = rsp[i].accounts[j].subtotal.formatted
            document.getElementsByClassName('feesTTT')[me + j].appendChild(ele2);
        }
    }
}

function addOptions(domElement, data) {
    var select = document.getElementById(domElement);
    select.innerHTML = '<option value="" selected style="font-size: 13px">Módulos</option>';
    for (i = 0; i < data.length; i++) {
        var option = document.createElement("option");
        option.value = data[i].dsc;
        option.text = data[i].dsc;
        select.add(option);
    }
}