var globalWorkOrderLoc;
var globalWorkOrderUrls;
var globalWorkOrderParams;

var _isMobileWO;
var hasPersonalFolder;


function initWorkOrders(localization, urls, params) {

    globalWorkOrderLoc = localization;
    globalWorkOrderUrls = urls;
    globalWorkOrderParams = params;

    _isMobileWO = globalWorkOrderParams.isMobile === 'True' ? true : false;
    hasPersonalFolder = globalWorkOrderParams.hasPersonalFolder === 'True' ? true : false;

    if (!_isMobileWO) {

        $("#mainGrid").appendTo(".document-list" );

        $('#X').addClass('active').css('border-bottom', '4px solid #faaf14');

        $('.d-datepicker').datepicker()
            .on('click', function (e) {
                $(this).select();
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

    }
    else {
        $("#mainGrid").appendTo(".document-list-no-footer");
    }

    $('.daily-plan-switch').on('change', function () {
        localStorage.setItem('WoFromDailyPlan', this.checked);
        $.fn.dataTable.reload($mainGridTable);
    });

    $('.active-work-orders-switch').on('change', function () {
        localStorage.setItem('ActiveWorkOrders', this.checked);
        $.fn.dataTable.reload($mainGridTable);
    });

    loadStatuses();
    setFromButtonStates();

    $mainGridTable = $('#mainGrid');
    var mainTable = $mainGridTable.DataTable({

        initComplete: function (settings, json) {

            $('.menu-open-button').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
                $(this).toggleClass('active');
            });

            $('.menu-item').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
            });

        },

        ajax: {

            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                var selectedDocTypes = $('#DocTypes').val();
                if (!selectedDocTypes || selectedDocTypes.length === 0) {
                    selectedDocTypes = $('#DocTypes option').map(function () { return $(this).val(); }).get();
                }
                d.DocTypes = selectedDocTypes;
                d.Statuses = $('#Status').val();
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $('.search-input[name="Keywords"]').val();
                d.ProductionType = $("#ProdType").val();
                d.ActiveWorkOrders = localStorage.getItem('ActiveWorkOrders') === 'true';
                d.EmployeeHasPersonalFolder = hasPersonalFolder;
                d.DataFromDailyPlan = $("#ProdType").val() === "MF" ? localStorage.getItem('WoFromDailyPlan') === 'true' : false;
                d.DateFrom = _isMobileWO ? $("#mDateFrom").val() : reformatDate($("#dDateFrom").val());
                d.DateTo = _isMobileWO ? $("#mDateTo").val() : reformatDate($("#dDateTo").val());
                d.Resources = $('#ResursID').val();
                d.SortColumn = $('#OrderBy').val();
                d.SortOrder = $("#sortType").attr('data-value');
            }
        },

        columns: [
            {
                render: $.fn.dataTable.render.previewWorkOrderReportTreeOptions()
            },
            {
                class: 'border-bottom text-center',
                orderable: false,
                render: function (data, type, full) {

                    var image = full.Picture ? " <img  loading='lazy' style='max-width:100%; max-height:150px' src='" + full.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";

                    return "<span style = 'width:100rem;position: relative;text-align: center;vertical-align: middle;display: table-cell;height: 150px;'>" + image + " </span>";

                }
            },
            {
                data: "Product",
                name: "acName",
                render: function (data, type) {
                    return type === 'display' ?
                        '<span data-toggle="tooltip" class="card-caption" data-original-title = "' + data + '">' + data + ' </span> ' : data;
                }

            },
            {
                data: "AcKeyDisplay",
                name: "AcKey",
                className: "dt-body-left",

                render: function (data, type, full) {
                    var hidden = full.WoExOperRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="fal fa-hashtag"></i> </span> <span>' + data + '</span> ' +
                        '<div class="pulsating-circle pull-right ' + hidden + '" data-toggle="popover"  data-placement="bottom" ' +
                        '   data-url="' + globalWorkOrderUrls.operRegURL + '" data-original-title="' + globalWorkOrderLoc.workRegistration + '" data-key="' + full.AcKey + '" > ' +
                        '</div > ' : data;
                }
            },
            {
                data: 'VariantName',
                name: "VariantName",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="overflow:hidden;text-overflow:ellipsis;display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;" data-toggle="tooltip"  data-original-title = "' + data + '">' +
                        '<i class="fal fa-boxes"></i> ' + data + '</span>' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="fal fa-calendar alt"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrc',
                render: function (data, type, full) {
                    var color = full.StatusMF == 'Z' ? "bg-c-red" : (data < 100 ? "bg-c-yellow" : "bg-c-green")
                    var value = data > 100 ? 100 : data
                    return type === 'display' ?
                        '<div class="progress-card">' +
                        '<div class="progress">' +
                        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + data + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                        '</div>' +
                        '</div>' +

                        '<div class="cardStatus">' +
                        '   <div class="cardStatus" style="justify-content: normal;">' +
                        '       <span>' + full.StatusDisplay + '</span>' +
                        '       <span>(' + round(full.CompletedPrc, 2).toString().replace('.', ',') + '%)</span>' +
                        '   </div>' +
                        '   <span>' + round(full.ProducedQty, 2).toString().replace('.', ',') + '/' + round(full.PlanQty, 2).toString().replace('.', ',') + '</span>' : data +
                        '</div>';
                }
            }
        ],
        createdRow: function (row, data) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function (settings) {

            $('#X > span:last-child').text(settings.json.prop.All);

            if ($("#ProdType").val() === "MF") {
                $('#P > span:last-child').text(settings.json.prop.Planned);
                $('#O > span:last-child').text(settings.json.prop.Opened);
                $('#I > span:last-child').text(settings.json.prop.Reserved);
                $('#R > span:last-child').text(settings.json.prop.Released);
                $('#D > span:last-child').text(settings.json.prop.InProgress);
                $('#E > span:last-child').text(settings.json.prop.PartialyFinished);
                $('#Z > span:last-child').text(settings.json.prop.Finished);
            } else {
                $('#N > span:last-child').text(settings.json.prop.Opened);
                $('#L > span:last-child').text(settings.json.prop.Released);
                $('#D > span:last-child').text(settings.json.prop.InProgress);
                $('#I > span:last-child').text(settings.json.prop.Finished);
            }

            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            }),
                $("[data-toggle=popover]").popover({

                    html: true,
                    container: "body",
                    trigger: 'hover',
                    placement:'auto',
                    content: function () {
                        $.ajax({
                            url: $(this).attr('data-url'),
                            type: 'POST',
                            async: false,
                            data: {
                                Key: $(this).attr('data-key'),
                                ItemType: ""
                            },
                            success: function (response) {
                                getWOOperRegTable(response);
                            }
                        });

                        return $('#operPopover').html();
                    }

                }),
                $("[data-toggle=notePopover]").popover({
                    html: true,
                    container: "body",
                    trigger: 'hover',
                    content: function () {

                        $.ajax({
                            cache: false,
                            type: "GET",
                            url: globalWorkOrderUrls.getNoteURL,
                            data: { key: $(this).attr('data-key') },
                            async: false,
                            success: function (response) {
                                $("#notePopover").empty();
                                var noteHTML =
                                    '<div><h3>' + globalWorkOrderLoc.noteCaption + '</h3></div>' +
                                    '<textarea id="note-input" style="resize: vertical; height: 200px; width:400px" class="form-control">' + response.Content + '</textarea>'
                                $('#notePopover').append(noteHTML);
                            },
                            error: function (error) {
                                console.error(error);
                            }
                        });

                        return $('#notePopover').html();
                    }
                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        }

    }).on('click', 'tr', function (e) {

        let $cell = $(e.target).closest('td, th');
        let cellIndex = $cell.index();

        if (cellIndex === 0) {
            return;
        }

        var data = mainTable.row($(this)).data();
        window.location.href = `${globalWorkOrderUrls.workOrderOperationsURL}?key=${data.AcKey}`;
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function (e) {
        setFiltersMobile();
        $.fn.dataTable.reload($mainGridTable);
    });


    $(".btn-toolbar > button.btn").on("click", function () {
        handleButtonClick($(this));
        saveStatuses();
        $.fn.dataTable.reload($mainGridTable)
    });

    setFiltersMobile();

    $('.btn-back').on("click", function () {
        if ($("#filters").hasClass("active")) {
            $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
        } else {
            $('#filtersTabs>.tab-pane').removeClass("active");
            $('#filtersTabs>#filters').addClass("fade").addClass("in").addClass("active");
        }

    });

    $('#filter').on("click", function () {
        $('#filtersTabs>.tab-pane').removeClass("active");
        $('#filtersTabs>#filters').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

    $('#apply').on("click", function () {
        $.fn.dataTable.reload($mainGridTable);
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    })

    $('.menu-open-button').on("click", function () {
        $('.menu-open-button').toggleClass('active');

    });

    $('.filter-list-item').on("click", function () {

        var selectedValues = [];

        $(this).find('i').toggleClass('fa-check');
        $(this).toggleClass("active");

        var parent = $(this).parent().attr('id');

        $("#" + parent + " .filter-list-item.active").each(function (index) {
            selectedValues.push($(this).data("value"));
        });

        var control = $(this).parent().data('control')
        $(control).val(selectedValues);
        $(control).trigger("change");

        localStorage.setItem('selectedStatuses2', JSON.stringify(selectedValues));
    });

    $('.clear-filters').on("click", function () {
        if ($("#DocTypes").val()) {
            $("#DocTypes").val('');
            $("#DocTypes").trigger("change");
        }
        if ($("#Status").val()) {
            $("#Status").val('');
            $("#Status").trigger("change");
        }
        if ($("#ResursID").val()) {
            $("#ResursID").val('');
            $("#ResursID").trigger("change");
        }

        handleButtonClick($("#X"));
        localStorage.removeItem('selectedStatuses2');

        $("#Keywords").val('');
        $("#Keywords").trigger("change");
    });

    var typingTimer;
    var doneTypingInterval = 300;

    $('.search-input[name="Keywords"]').off('keyup');
    $('.search-input[name="Keywords"]').on('keyup', function () {

        if ($('.search-input[name="Keywords"]').val().length > 0 && $('.search-input[name="Keywords"]').val().length < 3)
            return;

        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($mainGridTable); }, doneTypingInterval);

    });

    $('#save-note-btn').on('click', function () {
        saveWorkOrderNote(globalWorkOrderUrls.saveNoteURL);
    });

    $("#selected-daily-plan").off("change.tableReload");
};

function getWOOperRegTable(response) {
    $("#popoverTable").empty();
    var trHTML = '';
    $.each(response, function (i, item) {

        item.Icon = item.Icon.replace("fa-lg", "fa-2x");

        trHTML +=
            '<tr>' +
            '   <td style="width:50px"> ' +
            '       <i class="' + item.Icon + '" style= "color:' + item.Color + '"></i>' +
            '   </td>' +
            '   <td style="width:200px">' +
            '       <label class="control-label">' + item.EventTypeCaption + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.EventTimeStr + '</span>' +
            '       </div >' +
            '   </td>' +
            '   <td style="width:300px">' +
            '       <label class="control-label">' + item.ResursID.trim() + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.Ident.trim() + " - " + item.Descr.trim() + '</span>' +
            '       </div >' +
            '       <span>' + item.Worker + '</span>' +
            '   </td>' +
            '</tr>';
    });

    $('#popoverTable').append(trHTML);
}

function setFromButtonStates() {
    $(".daily-plan-switch").prop('checked', function () {
        return localStorage.getItem('WoFromDailyPlan') === "true"
    });

    $(".active-work-orders-switch").prop('checked', function () {
        return localStorage.getItem('ActiveWorkOrders') === "true"
    });
}

function setSortType(obj) {
    $(obj).find("i").toggleClass('fa-arrow-down-short-wide').toggleClass('fa-arrow-down-wide-short')
    $(obj).attr('data-value', $(obj).attr('data-value') == 'ASC' ? 'DESC' : 'ASC')
    localStorage.setItem('sortType', $(obj).attr('data-value'));
    $.fn.dataTable.reload($mainGridTable);
}

function getSortType() {
    $("#sortType").attr('data-value', localStorage.getItem('sortType'));
    if (localStorage.getItem('sortType') === 'ASC') {
        $("#sortType").find("i").addClass('fa-arrow-down-short-wide').removeClass('fa-arrow-down-wide-short')
    } else {
        $("#sortType").find("i").removeClass('fa-arrow-down-short-wide').addClass('fa-arrow-down-wide-short')
    }
}
function setFiltersMobile() {

    var selDocs = $("#DocTypes option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selDocs == "" ? selDocs = $("#DocTypes").attr("title") : selDocs;
    $("#doc-type-list").text(selDocs);

    var selStatus = $("#Status option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selStatus == "" ? selStatus = $("#Status").attr("title") : selStatus;
    $("#status-list").text(selStatus);

    var selRes = $("#ResursID option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selRes == "" ? selRes = $("#ResursID").attr("title") : selRes;
    $("#res-list").text(selRes);

}

function customModalForMobile(_isMobile) {
    if (_isMobile) {
        $(".custom-modal-footer>div>button").addClass("btn-rounded");
        $(".custom-modal-body-content>span").addClass("h4");
        $(".custom-modal-title").css("font-size", 24);
    }
}

function closeInfoCard() {
    if (!_isMobileWO && !$('#info-card').is(":hidden")) {
        let parent = $('.project-list');
        let parentHeight = parent.height();
        let child = $('.document-list');
        let newHeight = parentHeight + 164;
        child.height(newHeight);
    }

    $('#info-card-status').addClass('hidden');
    $('#info-card-acLnkKey-container').addClass('hidden');
    $('#info-card-acVariant-container').addClass('hidden');
    $('#info-card-costDrv-container').addClass('hidden');
    $('#info-card-Dept-container').addClass('hidden');

    $('#info-card').hide();
}

function loadInfoCard(full) {
    closeInfoCard();
    if (typeof full === 'string') {
        full = JSON.parse(full);
    }

    var image = full.Picture ? " <img id='info-card-image' src='" + full.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";
    $('.card-image').html(image);

    $('#info-card-title').text(full.Product);
    $('#info-card-acKey').text(full.AcKeyDisplay);
    $('#info-card-date').text(full.Date);

    if (full.DPKeyList) {
        
        $('#info-card-DPKeyList').text(full.DPKeyList);
        $('#info-card-DPKeyList-container').removeClass('hidden');
    }

    if (full.Status != 'Z' && $("#ProdType").val() === "MF") {
        $('#info-card-addOnDP').removeClass('hidden');
    }
    else {
        $('#info-card-addOnDP').addClass('hidden');
    }

    if (full.AcLnkKey) {
        $('#info-card-acLnkKey').text(full.AcLnkKey);
        $('#info-card-acLnkKey-container').removeClass('hidden');
    }

    if (full.VariantName) {
        $('#info-card-acVariant').text(full.VariantName);
        $('#info-card-acVariant-container').removeClass('hidden');
    }

    if (full.CostDrv) {
        $('#info-card-costDrv').text(full.CostDrv);
        $('#info-card-costDrv-container').removeClass('hidden');
    }

    if (full.Dept) {
        $('#info-card-Dept').text(full.Dept);
        $('#info-card-Dept-container').removeClass('hidden');
    }

    if (full.Receiver) {
        $('#info-card-Rec').text(full.Receiver);
        $('#info-card-Recevier-container').removeClass('hidden');
    }

    if (full.Consignee) {
        $('#info-card-Consig').text(full.Consignee);
        $('#info-card-Consignee-container').removeClass('hidden');
    }

    if (full.Priority) {
        $('#info-card-Priority').text(full.Priority);
        $('#info-card-Priority-container').removeClass('hidden');
    }

    if (full.Status === 'Z' && $("#ProdType").val() === "MF") {
        $('#info-card-close-dn').attr('onclick', `openRN('${full.AcKey}','${full.StatusDisplay}','${globalWorkOrderUrls.openWOURL}')`);
        $('#info-card-close-dn').attr('title', globalWorkOrderLoc.openRN);
        $('#info-card-close-dn>i').removeClass('fa-file-xmark').addClass('fa-file-check');
    } else {
        $('#info-card-close-dn').attr('onclick', `closeRN('${globalWorkOrderUrls.closeWOURL}', '${full.AcKey}', '${globalWorkOrderLoc.ok}')`);
        $('#info-card-close-dn').attr('title', globalWorkOrderLoc.closeRN);
        $('#info-card-close-dn>i').removeClass('fa-file-check').addClass('fa-file-xmark');
    }

    if ($("#ProdType").val() === "MF") {
        if (full.Status == "O") {
            $('#info-card-status').off('click').on('click', function () {
                changeWOStatus(globalWorkOrderUrls.changeWOStatusURL, full.AcKey, 'R');
            });
            $('#info-card-status').attr('title', globalWorkOrderLoc.changeStatusOpenToReleased);
            $('#info-card-status').removeClass('hidden');
        } else if (full.Status == "R") {
            $('#info-card-status').off('click').on('click', function () {
                changeWOStatus(globalWorkOrderUrls.changeWOStatusURL, full.AcKey, 'O');
            });
            $('#info-card-status').attr('title', globalWorkOrderLoc.changeStatusReleasedToOpen);
            $('#info-card-status').removeClass('hidden');
        }
    }

    let percentageText = full.StatusDisplay;
    if (full.Status !== 'O' && full.Status !== 'Z') {
        percentageText += ` (${full.CompletedPrc}%)`;
    }

    let color = full.StatusMF == 'Z' ? "bg-c-red" : (full.CompletedPrc < 100 ? "bg-c-yellow" : "bg-c-green");
    let value = full.CompletedPrc > 100 ? 100 : full.CompletedPrc;
    let progress =
        '<div class="progress-card">' +
        '<div class="progress">' +
        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + full.CompletedPrc + '" aria-valuemin="0" aria-valuemax="100"></div>' +
        '</div>' +
        '</div>' +

        '<div class="cardStatus">' +
        '   <div class="cardStatus" style="justify-content: normal;">' +
        '       <span>' + percentageText + '</span>' +
        '   </div>' +
        '   <span>' + round(full.ProducedQty, 2).toString().replace('.', ',') + '/' + round(full.PlanQty, 2).toString().replace('.', ',') + '</span>' +
        '</div>';

    $('#info-card-progress').html(progress);

    $('#info-card-materials').off("click").on("click", function () {
        window.location.href = `${globalWorkOrderUrls.workOrderMaterialsURL}?key=${full.AcKey}`;
    });

    $('#info-card-operations').off("click").on("click", function () {
        window.location.href = `${globalWorkOrderUrls.workOrderOperationsURL}?key=${full.AcKey}`;
    });
    $('#info-card-recieve').off("click").on("click", function () {
        window.location.href = `${globalWorkOrderUrls.workOrderReceivingsURL}?id=${full.AcKey}`;
    });

    $('#info-card-documents').off("click").on("click", function () {
        window.location.href = `${globalWorkOrderUrls.documentsURL}?key=${full.AcKey}`;
    });

    $('#info-card-note').off("click").on("click", function () {
        loadWorkOrderNote(globalWorkOrderUrls.getNoteURL, full.AcKey);
    });

    $('#info-card-addOnDP').off("click").on("click", function () {
        ADPMurl = globalWorkOrderUrls.addOnDPURL;
        ADPMWOKey = full.AcKey;
        $('#add-on-dp-modal').modal('show');
    });

    if (!_isMobileWO && $('#info-card').is(":hidden")) {
        let parent = $('.project-list');
        let parentHeight = parent.height();
        let child = $('.document-list');
        let newHeight = parentHeight - 261;
        child.height(newHeight);
    }

    if (_isMobileWO) {
        $('#info-card').css('width', 'calc(100% + 30px)');
    }

    $('#info-card').show();
}

function openRN(acKey, status, url, continueUrl) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#WOClosedToOpen").val().replace("{0}", status),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                action: function () {
                    $.ajax({
                        cache: false,
                        type: "POST",
                        url: url,
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({
                            key: acKey
                        }),
                        success: function (response) {
                            if (response.Success) {
                                if (continueUrl) {
                                    window.location.href = continueUrl;
                                }
                                else {
                                    $.fn.dataTable.reload($mainGridTable);
                                    closeInfoCard();
                                }
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function closeRN(closeWOUrl, acKey, okLoc) {
    $.ajax({
        cache: false,
        type: "POST",
        url: closeWOUrl,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            key: acKey
        }),
        success: function (response) {
            if (response.Success) {
                $.fn.dataTable.reload($mainGridTable);
                closeInfoCard();
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: response.Message.join('<br>'),
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: okLoc,
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function saveStatuses() {
    let selectedStatuses = [];
    $('.btn-toolbar > button.btn.active').each(function () {
        selectedStatuses.push($(this).attr('id'));
    });
    localStorage.setItem('selectedStatuses2', JSON.stringify(selectedStatuses));
}

function loadStatuses() {
    let selectedStatuses = JSON.parse(localStorage.getItem('selectedStatuses2'));
    if (selectedStatuses && selectedStatuses.length > 0) {
        selectedStatuses.forEach(function (filterId) {
            handleButtonClick($("#" + filterId));
        });
    }
}

function handleButtonClick(button) {
    var buttonId = button.attr('id');
    var color = button.css("color");

    if (buttonId != 'X') {
        $('#X').removeClass('font-bold').removeClass('active').css("border-bottom", "");
    } else {
        color = "#faaf14";
        $(".btn-toolbar > button.btn").each(function () {
            $(this).removeClass('font-bold').removeClass('active').css("border-bottom", "");
        });
    }

    button.toggleClass('active').toggleClass('font-bold');

    if (button.hasClass('active')) {
        button.css("border-bottom", "4px solid " + color);
    } else {
        button.css("border-bottom", "")
    }

    let text = [""];
    $(".btn-toolbar > button.btn").each(function () {
        if ($(this).hasClass('active') && buttonId != 'X') {
            text.push($(this).attr('id'));
        }
    });

    if (text.length === 1) {
        $('#X').addClass('font-bold').addClass('active').css("border-bottom", "4px solid #faaf14");
    }

    $('#Status').val(text);
}

$.fn.dataTable.render.previewWorkOrderReportTreeOptions = function () {
    return function (data, type, row, meta) {
        if (type === 'display') {
            let printUrl = globalWorkOrderUrls.printReport;
            let func = `openPdfPreview('${printUrl}?printType=317&ident=${row.Ident}')`;

            let response = `<span onclick=${func} title='${globalWorkOrderLoc.labelPrinting}'>
                    <i class="fal fa-eye fa-2x text-muted m-r-xs"></i>
                </span>
                <div style="float:right;padding-left:5px" onclick='loadInfoCard(${JSON.stringify(row)})'>
                    <i class="fal fa-search fa-2x"></i>
                </div>
                <a class="text-default" style="float:right" data-toggle="notePopover" data-placement="auto" data-key="${row.AcKey}"  '>
                    <i class="fal fa-comment-alt-lines fa-2x"></i>
                </a>`;
            return response;
        }

        return data;
    };
};