Source: rendertable.js

var hovered = '';
var clicked = '';

/**
 * Renders the table
 * @param tableid table id of the element in which the data should be rendered
 * @param data data to render
 */
function rendertable(tableid, data) {

    var data;
    var dataOld;
    if (tableid == 'tableyears') {
        data = datayears;
        if (Object.keys(datayearsOld).length > 0) {
            dataOld = datayearsOld;
        } else {
            dataOld = data;
        }
    } else {
        data = databegegnungen;
        if (Object.keys(databegegnungen).length > 0) {
            dataOld = databegegnungen;
        } else {
            dataOld = data;
        }
    }

    var table = document.getElementById(tableid);
    table.innerHTML = "";

    var keys = Object.keys(data);

    var max_axis_value = [];
    for (var i = 0; i < Object.keys(data).length; i++) {
        max_axis_value[i] = 0;
        for (var rank = 0; rank < data[keys[i]].length; rank++) {
            if (parseInt(max_axis_value[i]) < parseInt(data[keys[i]][rank]["ES"])) {
                max_axis_value[i] = parseInt(data[keys[i]][rank]["ES"]);
            }
            if (parseInt(max_axis_value[i]) < parseInt(data[keys[i]][rank]["EN"])) {
                max_axis_value[i] = parseInt(data[keys[i]][rank]["EN"]);
            }
        }
    }

    /////////////////////////////////////////////////
    /////////// Year/Begegnung Labels ///////////////
    /////////////////////////////////////////////////
    var trHeader = document.createElement("TR");
    //trHeader.setAttribute("nowrap", "1");
    table.appendChild(trHeader);

    var colspan = 0;
    var colspanKummu = 0;
    var colspanEinzel = 0;
    var col_keys = Object.keys(filter.cols);
    for (var c = 0; c < col_keys.length; c++) {
        var col_key = col_keys[c];
        var col = filter.cols[col_key];
        if (col.visible === true) {
            colspan++;
            if (col.kummuliert) {
                colspanKummu++;
            } else {
                colspanEinzel++;
            }
        }
    }

    for (var i = 0; i < Object.keys(data).length; i++) {
        var td = document.createElement("TH");

        td.colSpan = colspan;
        td.className = "header";
        if (tableid == "tableyears") {
            td.innerHTML = "<span class='highlight'>" + keys[i].split("_")[0] + "</span>";
        }
        if (tableid == "tablebegegnungen") {
            td.innerHTML = "Zwischenstand nach der<br /><span class='highlight'>" + keys[i].split("_")[1] + ". Begegnung</span> (" + keys[i].split("_")[0] + ")";
        }
        trHeader.appendChild(td);

        if (i < Object.keys(data).length - 1) {
            var td = document.createElement("TH");
            trHeader.appendChild(td);
        }
    }

    /////////////////////////////////////////////////
    ///////////// Kummuliert Labels /////////////////
    /////////////////////////////////////////////////
    var trHeader = document.createElement("TR");
    //trHeader.setAttribute("nowrap", "1");
    table.appendChild(trHeader);

    for (var i = 0; i < Object.keys(data).length; i++) {
        if (tableid == 'tableyears') {
            var td = document.createElement("TH");
            td.colSpan = colspan;
            td.className = "header";
            td.innerHTML = "Endergebnis";
            trHeader.appendChild(td);
        } else {
            var td = document.createElement("TH");
            td.colSpan = colspanKummu;
            td.className = "header";
            td.innerHTML = "Kummuliert bis <br />zur " + keys[i].split("_")[1] + ". Begegnung";
            td.style.borderRight = "1px solid black";
            trHeader.appendChild(td);

            var td = document.createElement("TH");
            td.colSpan = colspanEinzel;
            td.className = "header";
            td.innerHTML = "nur diese <br />Begegnung";
            trHeader.appendChild(td);
        }

        if (i < Object.keys(data).length - 1) {
            var td = document.createElement("TH");
            trHeader.appendChild(td);
        }
    }

    /////////////////////////////////////////////////
    //////////////// Col Labels /////////////////////
    /////////////////////////////////////////////////
    var trLabels = document.createElement("TR");
    //trHeader.setAttribute("nowrap", "1");
    table.appendChild(trLabels);
    for (var i = 0; i < Object.keys(data).length; i++) {
        var col_keys = Object.keys(filter.cols);
        for (var c = 0; c < col_keys.length; c++) {

            var col_key = col_keys[c];

            var col = filter.cols[col_key];
            if (col.visible === true) {
                var td = document.createElement("TH");
                td.className = "rotate header";
                var title = filter.cols[col_key].title;
                if (filter.cols[col_key].title == "Ergebnisse") {
                    td.style.minWidth = "120px";
                }
                if (filter.cols[col_key].title == "Verein") {
                    td.style.minWidth = "34px";
                }
                if (filter.cols[col_key].title == "Ă„nderung") {
                    td.style.minWidth = "38px";
                }
                td.innerHTML = "<div><span>" + title + "</span></div>";
                trLabels.appendChild(td);
            }
        }
        if (i < Object.keys(data).length - 1) {
            var td = document.createElement("TH");
            trLabels.appendChild(td);
        }
    }

    var trAxis = document.createElement("TR");
    table.appendChild(trAxis);
    for (var i = 0; i < Object.keys(data).length; i++) {
        Object.keys(filter.cols).forEach(function (key) {
            var row = 1;
            var col = filter.cols[key];
            if (col.visible === true) {
                var tdlable = document.createElement("TD");
                tdlable.className = "header";
                tdlable.style.fontSize = "0px";
                var svgID = 'sbc' + row + '_' + i + 'label' + tableid; // sbc1_0label
                //console.log(svgID);
                trAxis.appendChild(tdlable);

                if (key == "sbc" && max_axis_value[i] > 0) {
                    tdlable.innerHTML = '<svg id="' + svgID + '" width="120" height="21" style="margin:0px;" ' +
                        'class="tooltip"></svg>';
                    var data_row_year = data[keys[i]][row];
                    /*
                    console.log(data_row_year);
                    console.log(max_axis_value[i]);
                    console.log(i);
                    console.log(svgID);
                    // */

                    buildgraphicAxis(data_row_year, max_axis_value[i], "#" + svgID);
                    //td.innerHTML = "TODO";
                }
                else {
                    tdlable.innerHTML = "";
                }
                /*
                var svgID = 'sbc' + row + '_' + keys[i];
                td.innerHTML = '<svg id="' + svgID + '" width="120" height="34" style="margin:0px;" ' +
                    'class="tooltip" onmouseover="displayToolTipBox(' + svgID + ')" onmouseout="hideToolTipBox()"></svg>';
                buildgraphic(data_row_year, max_axis_value[i], "#sbc" + row + "_" + keys[i] + "");
                */
            }
        });
        var td = document.createElement("TD");
        trAxis.appendChild(td);

    }

    var rankVar = changeRank ? "rank" : "rankTrue";


    var maxrows = 0;
    for (var i = 0; i < Object.keys(data).length; i++) {
        if (data[keys[i]].length > maxrows) {
            maxrows = data[keys[i]].length;
        }
    }

    var alternativerow = [];
    for (var i = 0; i < Object.keys(data).length; i++) {
        alternativerow[i] = -1;
    }

    for (var row = 0; row < maxrows; row++) {
        var tr = document.createElement("TR");
        tr.zIndex = 2;
        tr.setAttribute("nowrap", "1");
        table.appendChild(tr);

        //console.log("alternativerow");
        //console.log(alternativerow);

        for (var i = 0; i < Object.keys(data).length; i++) {

            if (row >= data[keys[i]].length) {
                var td = document.createElement("TD");
                td.colSpan = colspan;
                tr.appendChild(td);
                continue;
            }

            var correctrow = -1;
            for (var r = 0; r < maxrows; r++) {
                if (data[keys[i]][r] !== undefined && data[keys[i]][r] !== null && data[keys[i]][r][rankVar] == row + 1) {
                    correctrow = r;
                }
            }

            if (correctrow > -1) {


                var data_row_year = data[keys[i]][correctrow];
                var data_row_year_Old = dataOld[keys[i]] !== undefined ? dataOld[keys[i]][correctrow] : undefined;

                var changed = data_row_year_Old !== undefined && data_row_year.nameId !== data_row_year_Old.nameId;

                if (data_row_year == undefined) {
                    continue;
                }

                var diff = parseInt(data_row_year['rankTrue']) - parseInt(data_row_year[rankVar]);
                //var cols = Object.keys(data_row_year);
                Object.keys(filter.cols).forEach(function (key) {

                    var col = filter.cols[key];
                    if (col.visible === true) {

                        var td = document.createElement("TD");
                        tr.appendChild(td);
                        td.style.paddingTop = 0;
                        td.style.paddingBottom = 0;
                        td.style.paddingLeft = "2px";
                        td.style.paddingRight = "2px";
                        td.style.textAlign = "center";
                        td.setAttribute("nowrap", "1");
                        var className = data_row_year.nameId.replace(/[^a-zA-Z]/g, "") + (row % 2 == 0 ? " even" : " odd") + " line";

                        if (changed) {
                            td.style.fontSize = "22px";
                        } else {
                            td.style.fontSize = "16px";
                        }

                        switch (key) {
                            case 'name':
                                var imagename = data_row_year.nameId.replace(/[^a-zA-Z]/g, "");
                                if (data_row_year.nameId == "Bulldogs") {
                                    imagename = "Imagenotfound";
                                }
                                td.style.marginTop = 0;
                                td.style.marginBottom = 0;
                                td.style.paddingLeft = "0px";
                                td.style.paddingRight = "0px";
                                td.style.fontSize = 0;
                                td.valign = "center";
                                td.innerHTML = '<img src="logos/' + imagename + '.png" alt="' + data_row_year[key] + '" title="' + data_row_year[key] + '" />';
                                break;
                            case 'rank':
                                className += (changed ? " changed" : "");
                                td.style.textAlign = "center";
                                td.innerHTML = data_row_year[rankVar];
                                if (diff > 0) {
                                    td.style.backgroundColor = "hsl(137, 100%, " + (100 - diff * 10) + "%)";
                                }
                                if (diff < 0) {
                                    td.style.backgroundColor = "hsl(0, 100%, " + (100 - (-diff) * 10) + "%)";
                                }
                                break;
                            case 'rankTrue':
                                className += (changed ? " changed" : "");
                                td.style.textAlign = "center";
                                td.style.minWidth = "34px";
                                if (diff > 0) {
                                    td.innerHTML = "(" + "+" + diff + ")";
                                    td.style.backgroundColor = "hsl(137, 100%, " + (100 - diff * 10) + "%)";
                                }
                                else if (diff < 0) {
                                    td.innerHTML = "(" + diff + ")";
                                    td.style.backgroundColor = "hsl(0, 100%, " + (100 - (-diff) * 10) + "%)";
                                }
                                else {
                                    td.innerHTML = "";
                                }
                                break;
                            case 'sbc':
                                td.style.padding = 0;
                                td.style.fontSize = 0;
                                //td.innerHTML = '<div id="sbc'+correctrow+'_'+i+'"></div>';
                                var svgID = 'sbc' + correctrow + '_' + keys[i];
                                td.innerHTML = '<svg id="' + svgID + '" width="120" height="34" style="margin:0px;" ' +
                                    'class="tooltip" onmouseover="displayToolTipBox(' + svgID + ')" onmouseout="hideToolTipBox()"></svg>';
                                buildgraphic(data_row_year, max_axis_value[i], "#sbc" + correctrow + "_" + keys[i] + "");
                                break;
                            default:
                                className += (changed ? " changed" : "");
                                td.innerHTML = data_row_year[key];
                                break;
                        }
                        td.className = className;
                    }
                });

            } else {

                for (var r = 0; r < maxrows; r++) {
                    if ((data[keys[i]][r] !== undefined && data[keys[i]][r] !== null && data[keys[i]][r].rank == null)) {
                        //console.log(i + " leer: " + data[keys[i]][r].name);
                    }
                    if ((data[keys[i]][r] !== undefined && data[keys[i]][r] !== null && data[keys[i]][r].rank == null)) {
                        if (r > alternativerow[i]) {
                            alternativerow[i] = r;
                            break;
                        }
                    }
                }

                var data_row_year = data[keys[i]][alternativerow[i]];
                var data_row_year_Old = dataOld[keys[i]][alternativerow[i]];

                Object.keys(filter.cols).forEach(function (key) {

                    var col = filter.cols[key];
                    if (col.visible === true) {

                        var td = document.createElement("TD");
                        tr.appendChild(td);
                        td.style.paddingTop = 0;
                        td.style.paddingBottom = 0;
                        td.style.paddingLeft = "5px";
                        td.style.paddingRight = "5px";
                        td.setAttribute("nowrap", "1");
                        var className = (row % 2 == 0 ? " even" : " odd") + " line";

                        if (data_row_year !== null && data_row_year !== undefined) {
                            switch (key) {
                                case 'rank':
                                    td.innerHTML = changeRank ? "" : data_row_year['rankTrue'];
                                    break;
                                case 'name':
                                    var imagename = data_row_year.nameId.replace(/[^a-zA-Z]/g, "");
                                    if (data_row_year.nameId == "Bulldogs") {
                                        imagename = "Imagenotfound";
                                    }
                                    td.style.marginTop = 0;
                                    td.style.marginBottom = 0;
                                    td.style.fontSize = 0;
                                    td.valign = "center";
                                    td.innerHTML = '<img src="logos/' + imagename + '.png" alt="' + data_row_year[key] + '" title="' + data_row_year[key] + '" />';
                                    break;
                                default:
                                    td.innerHTML = "";
                                    break;
                            }
                        } else {
                            td.innerHTML = "";
                        }
                        td.className = className;
                    }
                });
            }

            if (row == 0 && i < Object.keys(data).length - 1) {
                var td = document.createElement("TD");
                td.rowSpan = maxrows;
                td.style.padding = 0;
                td.style.fontSize = 0;
                td.innerHTML = '<svg id="linegraph_' + keys[i] + '_' + keys[i + 1] + '" width="50" height="' + (34 * maxrows) + '" style="margin:0" onmouseout="hideToolTipBox()"></svg>';
                tr.appendChild(td);

                linechart("#linegraph_" + keys[i] + "_" + keys[i + 1], data[keys[i]], data[keys[i + 1]], '', '', maxrows, changeRank);
            }

        }
    }
    if (tableid == "tableyears") {
        var tr = document.createElement("TR");
        tr.setAttribute("nowrap", "1");
        table.appendChild(tr);
        for (var i = 0; i < Object.keys(data).length; i++) {
            var year = parseInt(keys[i].split("_")[0]);
            var td = document.createElement("TD");
            td.colSpan = colspan;
            td.style.textAlign = "center";
            if (filter.yearBegegnung.indexOf(year) < 0) {
                td.innerHTML = "<span class='highlight clickable' id='ViewDetails" + year + "' onclick='changeBegegnungYear(event)'>Zeige Begegnungen von " + year + "</span>";
            } else {
                td.innerHTML = "<span class='highlight clickable' id='ViewDetails" + year + "' onclick='hideBegegnungYear(event)'>Verstecke Begegnungen von " + year + "</span>";
            }
            tr.appendChild(td);

            var tdSpacing = document.createElement("TD");
            tdSpacing.innerHTML = "";
            tr.appendChild(tdSpacing);
        }
    }


    $(".line").on("mouseenter", function (id) {
        var target = id.target;
        //console.log(target);
        if (target.tagName == "path") {
            return;
        }
        while (target.tagName != "TD") {
            target = target.parentNode;
        }
        var lineclass = target.className.split(" ")[0];

        hovered = lineclass;

        $("." + lineclass).addClass("hovered");
    });

    $(".line").unbind('click');
    $(".line").click(function (id) {
        var target = id.target;
        if (target.tagName == "path") {
            return;
        }
        //TODO ADD here on click for balcken to get grey or remove grey color
        while (target.tagName !== "TD" && target.tagName !== "PATH") {
            target = target.parentNode;
        }
        var lineclass = target.className.split(" ")[0];

        if ($(target).hasClass("clicked")) {
            $(".clicked").removeClass("clicked");
        } else {
            $(".clicked").removeClass("clicked");

            clicked = lineclass;
            $("." + lineclass).addClass("clicked");
        }
    });

    $(".line").on("mouseout", function (id) {
        var target = id.target;

        if (target.tagName == "path") {
            return;
        }
        while (target.tagName !== "TD") {
            target = target.parentNode;
        }
        var lineclass = target.className.split(" ")[0];

        hovered = '';
        var xyzzyx = '.' + lineclass;
        $(xyzzyx).removeClass('hovered');
    });
}

/**
 * Event handler to set/change the year of the detail table
 * @param e event that triggered the function call
 */
function changeBegegnungYear(e) {
    var year = parseInt(e.target.id.replace("ViewDetails", ""));
    filter.yearBegegnung = [year];
    update();
}

/**
 * Hides the detail table
 * @param e event that triggered the function call
 */
function hideBegegnungYear(e) {
    filter.yearBegegnung = [];
    update();
}