function initWorkOrders() {

    loadFilters();

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

    $mainGridTable = $('#mainGrid');
    var table = $mainGridTable.DataTable({
        ajax: {

            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                d.DocTypes = $("#DocTypes").val();
                d.Statuses = $("#Status").val();
                d.Keywords = $("#Keywords").val();
                d.ProductionType = $("#ProdType").val();
                d.DataFromDailyPlan = $("#ProdType").val() === "MF" ? $("#data-from-daily-plan").is(":checked") : false;;
                d.DateFrom = reformatDate($("#Filter_DateFrom").val());
                d.DateTo = reformatDate($("#Filter_DateTo").val());
                d.Resources = $("#ResursID").val();
                d.SortColumn = $("#sortColumn").val();
                d.SortOrder = $("#sortOrder").val();

                saveFilters();
            },

        },
        columns: [
            {
                class: 'border-bottom text-center',
                data: function (data) {
                    var image = data.Picture !== '' ? " <img style='max-width:100%; max-height:150px'  src='" + data.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>";
                },
                orderable: false,
                render: function (data) {
                    return data;
                }
            },
            {
                data: "Product",
                name: "acName",
                filtertype: "text",
                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",
                filtertype: "text",
                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="far fa-hashtag"></i> </span> <span>' + data + '</span> ' +
                        '<div class="pulsating-circle pull-right ' + hidden + '" data-toggle="popover"  data-placement="bottom" ' +
                        '   data-url="' + $("#operRegURL").val() + '" data-original-title="' + $("#workRegistration").val() + '" data-key="' + full.AcKey + '" > ' +
                        '</div > ' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far 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) {
            $(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',
                    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();
                    }

                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        }

    }).on('click', 'tr', function () {
        var data = table.row($(this)).data();
        window.location.href = "Manufacturing/WorkOrderOperations?key=" + data.AcKey;
    });

    $(".datepicker").datepicker({
        format: 'dd.mm.yyyy',
        language: $('#languageDate').val()
    }).on('changeDate', function () {
        $(this).datepicker('hide');
        $.fn.dataTable.reload($mainGridTable);
    });

    $('.sortField').click(function () {

        $('.sortField').each(function () {
            $(this).find('i').addClass('hidden');
            $(this).removeClass('text-success');
        });


        $(this).find('i').removeClass('hidden');
        $(this).addClass('text-success');

        var sortOrder = 'ASC'
        var sortColumn = $(this).data('sort-column')

        if ($(this).find('i').hasClass('fa-sort-amount-down')) {
            sortOrder = 'ASC'
            $(this).find('i').removeClass('fa-sort-amount-down').addClass('fa-sort-amount-down-alt');
        } else {
            sortOrder = 'DESC'
            $(this).find('i').removeClass('fa-sort-amount-down-alt').addClass('fa-sort-amount-down');
        }
        $("#sortColumn").val(sortColumn);
        $("#sortOrder").val(sortOrder);

        $.fn.dataTable.reload($mainGridTable);

    });

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

    $('#clear').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");
        }

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

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


    $(".btn-toolbar > button.btn").on("click", function () {

        var buttonId = $(this).attr('id');
        var color = $(this).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", "");
            });
        }

        $(this).toggleClass('active').toggleClass('font-bold');

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

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

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

        $('#Status').val(text);
        $.fn.dataTable.reload($mainGridTable)
    });

    var typingTimer;
    var doneTypingInterval = 300;

    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {

        if ($("#Keywords").val().length > 0 && $("#Keywords").val().length < 3)
            return;

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

    });

};

function initWorkOrdersMobile() {

    loadFilters();

    $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) {
                d.DocTypes = $('#DocTypes').val().split(",");
                d.Statuses = $('#Status').val().split(",");
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $("#Keywords").val();
                d.ProductionType = $("#ProdType").val();
                d.DataFromDailyPlan = $("#ProdType").val() === "MF" ? $("#data-from-daily-plan").is(":checked") : false;
                d.DateFrom = $("#Filter_DateFrom").val();
                d.DateTo = $("#Filter_DateTo").val();
                d.Resources = $('#ResursID').val().split(",");
            }

        },


        columns: [
            {
                class: 'border-bottom text-center',
                orderable: false,
                render: function (data, type, full) {

                    var image = full.Picture !== '' ? " <img 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>" +

                        '<nav class="menu hidden">' +
                        '    <label class="menu-open-button" for="menu-open-' + full.AcKey + '" >' +
                        '        <span class="hamburger hamburger-1"></span>' +
                        '        <span class="hamburger hamburger-2"></span>' +
                        '        <span class="hamburger hamburger-3"></span>' +
                        '    </label>' +

                        '    <a href="#" class="menu-item"> <i class="fa fa-bar-chart"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-plus"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-heart"></i> </a>' +
                        '    <a href="#" class="menu-item"> <i class="fa fa-envelope"></i> </a>' +
                        '</nav>';

                }
            },
            {
                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="far fa-hashtag"></i> </span> <span>' + data + '</span> ' +
                        '<div class="pulsating-circle pull-right ' + hidden + '"</div > ' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far 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>';
                }
            }
        ],

        drawCallback: function () {

        }

    }).on('click', 'tr', function () {
        var data = mainTable.row($(this)).data();
        window.location.href = "Manufacturing/WorkOrderOperations?key=" + data.AcKey;
    });


    $('.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 () {
        saveFilters();
        $.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");

    });

    $('#clear').on("click", function () {

        $("#DocTypes").val('');
        $("#Status").val('');
        $("#ResursID").val('');

        $("#doc-types > .filter-list-item").each(function () {
            $(this).find('i').removeClass('fa-check');
            $(this).removeClass("active");
        });

        $("#status > .filter-list-item").each(function () {
            $(this).find('i').removeClass('fa-check');
            $(this).removeClass("active");
        });

        $("#resurs > .filter-list-item").each(function () {
            $(this).find('i').removeClass('fa-check');
            $(this).removeClass("active");
        });

        $("#Keywords").val('');

        $(this).trigger("change");
        $.fn.dataTable.reload($mainGridTable);
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");

    });


};

function getWOOperRegTable(response) {

    var icon = '';
    var color = '';
    var caption = '';

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

        switch (item.EventType) {
            case 'OB':
                icon = "fad fa-2x fa-play";
                color = "#7EAF3F";
                caption = $("#operationStart").val();
                break;
            case 'OP':
                icon = "fad fa-2x fa-pause-circle";
                color = "goldenrod";
                caption = $("#operationPause").val();
                break;
            case 'OC':
                icon = "fad fa-2x fa-play-circle";
                color = "#7EAF3F";
                caption = $("#operationContinue").val();
                break;
            case 'OE':
                icon = "fad fa-2x fa-stop-circle";
                color = "#BB5534";
                caption = $("#operationEnd").val();
                break;

            default:
                icon = "fa fa-clock-o";
                break;
        }

        trHTML +=
            '<tr>' +
            '   <td style="width:50px"> ' +
            '       <i class="' + icon + '" style= "color:' + color + '"></i>' +
            '   </td>' +
            '   <td style="width:200px">' +
            '       <label class="control-label">' + caption + ' </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 loadFilters() {

    var formName = $("#localStorageFiltersFor").val();

    $("#data-from-daily-plan").prop('checked', function () {
        return localStorage.getItem(formName + '.FromDailyPlan') === "true"
    });

    let dateFrom = localStorage.getItem(formName + '.Filter_DateFrom');
    let dateTo = localStorage.getItem(formName + '.Filter_DateTo');

    if (dateFrom != null)
        $("#Filter_DateFrom").val(dateFrom);
    if (dateTo != null)
        $("#Filter_DateTo").val(dateTo);    
}

function saveFilters() {

    var formName = $("#localStorageFiltersFor").val();

    localStorage.setItem(formName + '.FromDailyPlan', $("#data-from-daily-plan").prop('checked'));
    localStorage.setItem(formName + '.Filter_DateFrom', $("#Filter_DateFrom").val());
    localStorage.setItem(formName + '.Filter_DateTo', $("#Filter_DateTo").val());
}

