//Date: 22.12.2020
//Name: Responsive collapsible table
// Call this table in $(document).ready(function () { setCollapseTable(tableId); });
//Note: Set .collapse-table class to table element to work with css

function setCollapseTable(tableId) {
    $('#' + tableId + ' tbody tr').each(function (index) {
        var num = index - 1;
        var rowClass = "collapse-table-row-" + num;
        $(this).addClass(rowClass);
    });

    setActionButtons(tableId);
}

function setActionButtons(tableId) {

    var tabletWidth = window.innerWidth >= 576 && window.innerWidth <= 768;
    var mobileWidth = window.innerWidth < 576;

    var colNum = $("#" + tableId + " > tbody > tr:first > td").length;

    if (tabletWidth === true && colNum > 4) {
        $('#' + tableId + ' tr').each(function () {
            $('th:last', this).remove().insertAfter($('th:nth-child(3)', this));
            $('td:last', this).remove().insertAfter($('td:nth-child(3)', this));
        });

        setExpandIcon(tableId);
    }

    if (mobileWidth === true && colNum > 2) {
        $('#' + tableId + ' tr').each(function () {
            $('th:last', this).remove().insertAfter($('th:nth-child(1)', this));
            $('td:last', this).remove().insertAfter($('td:nth-child(1)', this));
        });

        setExpandIcon(tableId);
    }
}

function setExpandIcon(tableId) {
    $('#' + tableId + ' tbody tr td:first-child').each(function (index) {
        var num = index - 1;
        var expandIcon = "expand-icon-" + num;
        $(this).prepend('<i id="' + expandIcon + '" +  class="fa fa-caret-right" onclick="expandTableRow(\'' + tableId + '\', \'' + num + '\')"></i>');
    });
}

function expandTableRow(tableId, index) {

    var rowId = "#" + tableId + " .collapse-table-row-" + index;
    var expandIconObj = $("#" + tableId).find("#expand-icon-" + index);
    var borderClass = "border-left-success";
    var iconRight = "fa-caret-right";
    var iconDown = "fa-caret-down";

    if ($(rowId).hasClass(borderClass)) {
        $(rowId).removeClass(borderClass);
        expandIconObj.addClass(iconRight);
        expandIconObj.removeClass(iconDown);
    }
    else {
        $(rowId).addClass(borderClass);
        expandIconObj.removeClass(iconRight);
        expandIconObj.addClass(iconDown);
    }

    $(rowId).find('td').each(function (column, td) {
        if ($(td).css('display') == 'none') {
            $(td).css("display", "flex");
        }
        else if ($(td).css('display') == 'flex') {
            $(td).css("display", "none");
        }
    });
}