function initializeWorkOrders() {

    setFromDailyPlanButtonState();

    var urlString = window.location.href;
    var url = new URL(urlString);
    var dateISO = decodeURI(url.searchParams.get("date"));
    var productionType = $("#ProductionType").val();
    var datafromDP = productionType === "MF" ? $("#data-from-daily-plan").is(":checked") : false;
    $("#DocTypes option[value='']").attr('selected', 'selected');

    if (urlString.includes("date")) {
        var date = fromISOToStandardDateFormatString(dateISO);
        $("#Filter_DateFrom").val(date);
    }

    initializeIdentBasicTypeahead(
        $('#IdentFilterSearch').attr('dataUrl'),
        $('#IdentFilterSearch'),
        $('#IdentFilterSearch'),
        { item: $("#identFilterItem").val(), name: $("#identFilterName").val() },
        null,
        function (item) {           
            $("#IdentFilterSearch").val(item.id);
            $.fn.dataTable.reload($mainGridTable);
            return { selected: true, value: item.id };

    });


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

    $mainGridTable = $('#mainGrid');

    var operRegUrl = $("#operRegURL").val();

    var mainTable = $mainGridTable.DataTable({

        ajax: {
            
            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                d.DocTypes = $("#DocTypes").val();
                d.Statuses = $("#Status").val();
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $("#Keywords").val();
                d.ProductionType = productionType;
                d.DataFromDailyPlan = datafromDP;
                d.DateFrom = reformatDate($("#Filter_DateFrom").val());
                d.DateTo = reformatDate($("#Filter_DateTo").val());
                d.Resources = $("#ResursID").val();
            },
            
        },
        columns: [
            {
                data: function (data) {
                    var image = data.Picture !== '' ? " <img style='max-width:100%'  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' ?
                        '<p data-toggle="tooltip" class="twoLines" data-original-title = "' + data + '"  style="height:40px;font-size: 14px;font-weight: bold;overflow: hidden;text-overflow: ellipsis; margin:0px auto;">' + data + ' </p> ': data;
                }

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

                render: function (data, type, full) {
                    var hidden = full.WoExRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far fa-hashtag"></i> </span> <span>' + data + '</span> ' +

                        '<a id="operReg" class="fas fa-spinner fa-spin fa-lg pull-right ' + hidden + '" href="#" role="button" data-toggle="popover" data-url="' + operRegUrl +
                        '" data-original-title="' + $("#workRegistration").val() + '" data-key="' + full.AcKey +
                        '" style = "color: #7EAF3F"></a>' 
                        : 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 status = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.Status);
                    var completedPrc = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.CompletedPrc);
                    var planQty = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.PlanQty);
                    var producedQty = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.ProducedQty);
                    var color = data > 100 ? "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>' +

                        '<span>' + status + ' (' + completedPrc + '%)</span>  <span class="pull-right">' + producedQty + '/' + planQty + '</span>' : data;
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function () {
            $("[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();
            });
        }

    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function () {
        $.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);

    });

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


    $identTable = $('#stockGrid');
    $identTable.DataTable({
        ajax: {
            url: $identTable.attr('data-url'),
            data: function (d) {
                d.Ident = $("#IdentFilterSearch").val();    
            }
        },
        columns: [
            { data: "Ident", name: "AcIdent", filtertype: "text", render: $.fn.dataTable.render.link("Ident") },
            { data: "Name", name: "AcIdentNavigation.AcName", filtertype: "text", render: $.fn.dataTable.render.link("Ident") }
        ]
    });

};

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:200px">' +
            '       <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 >' +
            '   </td>' +
            '   <td style="width:100px">  ' +
            '       <span>' + item.Worker + '</span>' +
            '   </td > ' +

            '</tr>';
    });
    $('#popoverTable').append(trHTML);
}

function SetDataFromDP(isMobile) {
    var datafromDP = $("#data-from-daily-plan").is(":checked");
    localStorage.setItem('WoFromDailyPlan', datafromDP);
    if (!isMobile)
        location.reload();
}

function setFromDailyPlanButtonState() {
    var fromDailyPlan = localStorage.getItem('WoFromDailyPlan');
    if (fromDailyPlan && fromDailyPlan.toString() === "true") {
        $("#data-from-daily-plan").prop('checked', true);
    }
}

function initializeWorkOrdersMobile() {

    setFromDailyPlanButtonState();
    
    $mainGridTable = $('#work-orders-mobile');


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

        var selectedValues = [];
        var selectedText = [];

        $(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"));
            selectedText.push($(this).data("display"));
        });

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

    });

    function getFilterValues(element) {
        return element.data('value');
    };
   

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

    $('#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('');

    })

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

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

    var productionType = $("#ProductionType").val();
    $("#DocTypes option[value='']").attr('selected', 'selected');

    var operRegUrl = $("#operRegURL").val();

    var mainTable = $mainGridTable.DataTable({

        initComplete: function (settings, json) {

            var viewType = localStorage.getItem('WOMobileViewType');

            if (viewType == "fas fa-th") {
                $("#work-orders-mobile").toggleClass("card");
                $("#changeView").find("i").toggleClass("fa-th").toggleClass("fa-th-list");
            }
            else {
                $("#headerGrid").toggleClass("hidden");
                $("#work-orders-mobile").toggleClass("table");
            }
            
            $("#changeView").on("click", function () {
                $("#headerGrid").toggleClass("hidden");
                $("#work-orders-mobile").toggleClass("card");

                localStorage.setItem('WOMobileViewType', $(this).find("i").attr("class"));
                $(this).find("i").toggleClass("fa-th").toggleClass("fa-th-list");
                              
            });

        },
        
        ajax: {

            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                d.DocTypes = getFilterValues($('#DocTypes'));
                d.Statuses = getFilterValues($('#Status')); 
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $("#Keywords").val();
                d.ProductionType = productionType;
                d.DataFromDailyPlan = productionType === "MF" ? $("#data-from-daily-plan").is(":checked") : false;
                d.DateFrom = $("#Filter_DateFrom").val();
                d.DateTo = $("#Filter_DateTo").val();
                d.Resources = getFilterValues($('#ResursID'));
            },

        },



        columns: [
            {
                class:'border-bottom text-center',
                data: function (data) {
                    var image = data.Picture !== '' ? " <img style='max-width:100%' 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",
                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.WoExRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="far fa-hashtag"></i> </span> <span>' + data + '</span> ' : 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 status = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.Status);
                    var completedPrc = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.CompletedPrc);
                    var planQty = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.PlanQty);
                    var producedQty = $.fn.dataTable.render.number('.', ',', 0, '', "").display(full.ProducedQty);
                    var color = data > 100 ? "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>' +

                        '<span>' + status + ' (' + completedPrc + '%)</span>  <span class="pull-right">' + producedQty + '/' + planQty + '</span>' : data;
                }
            }
        ],

        drawCallback: function () {

        }

    });

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


};