var globalWorkRegParams;
var globalWorkRegLoc;
var globalWorkRegUrls;

var initialIdent;
var initialActiveItem;
var initialWorker;
var initialActiveWorker;

function initializeWorkRegistrationSvc(localizations, urls, params) {

    globalWorkRegParams = params;
    globalWorkRegLoc = localizations;
    globalWorkRegUrls = urls;
    globalWorkRegParams.isMobile = globalWorkRegParams.isMobile == 'True' ? true : false;

    if ($("#Picture").val() == "") {
        $("#image").addClass('hidden');
        $("#noImage").removeClass('hidden');
    }

    setInProgressWork($("#EventType").val());

    if (globalWorkRegParams.isEventTypeNull === 'True') {
        $('#editMat-ident').on('change', function () {
            if (!initialIdent) {
                initialIdent = $('#Ident').val();
            }

            const ident = $('#editMat-ident').val();
            $('#Ident').val(ident);

            $('#start').hide();

            $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
            $('#confirmButton').removeClass('hidden');
            $('#cancelButton').attr('onclick', 'cancelIdentChange()');
            $('#cancelButton').removeClass('hidden');
        });

        if (params.isMobile) {
            $('#ident').on('click', function () {
                $('#tabCaption').text(globalWorkRegLoc.ident);
                $('#sideNavBar>.tab-pane').removeClass("active");
                $('#sideNavBar>.nav>.nav-item').removeClass("active");
                $('#sideNavBar>#ident-list').addClass("fade").addClass("in").addClass("active");

                $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
            });

            $('.ident-list-item').on("click", function () {
                if (!initialIdent) {
                    initialIdent = $('#Ident').val();
                    initialActiveItem = $('.ident-list-item.active');
                }

                $('.ident-list-item').find('i').removeClass('fa-check');
                $('.ident-list-item').removeClass('active');

                $('#ident').val($(this).data("value"));
                $('#Ident').val($(this).data("value"));

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

                $('#start').hide();

                $('#confirmButton').attr('onclick', 'UpdatePosition(this)');
                $('#confirmButton').removeClass('hidden');
                $('#cancelButton').attr('onclick', 'cancelIdentChange()');
                $('#cancelButton').removeClass('hidden');
                $('.btn-close-side-panel').click();
            });

        }
    }

    if (params.isMobile) {
        $('#mWorker').on('click', function () {
            $('#tabCaption').text(globalWorkRegLoc.worker);
            $('#sideNavBar>.tab-pane').removeClass("active");
            $('#sideNavBar>.nav>.nav-item').removeClass("active");
            $('#sideNavBar>#workers-list').addClass("fade").addClass("in").addClass("active");

            $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
        });

        $('.workers-list-item').on("click", function () {
            if (!initialWorker) {
                initialWorker = $('#Worker').val();
                initialActiveWorker = $('.workers-list-item.active');
            }

            $('.workers-list-item').find('i').removeClass('fa-check');
            $('.workers-list-item').removeClass('active');

            $('#mWorker').val($(this).data("value"));
            $('#Worker').val($(this).data("value"));

            $(this).find('i').toggleClass('fa-check');
            $(this).addClass("active");
            $('#Worker').trigger("change");

            $('.btn-close-side-panel').click();
        });
    }

    $('#editMat-ident').on('change', function () {
        const ident = $('#editMat-ident').val();
        $('#Ident').val(ident);

        $('#confirmButton').removeClass('disabled');
    });

    var decPlaces = globalWorkRegParams.woExDecPlacesOper;
    $('.btn-plus-minus').click(function () {
        var control = $(this).parents("div").children(".form-control");

        if ($(this).children().hasClass("fa-plus")) {
            control.val(roundToPercision(decPlaces, Number(control.val()) + 1)).change();
        };

        if ($(this).children().hasClass("fa-minus")) {
            if (Number(control.val()) > 0) {
                let newValue = roundToPercision(decPlaces, Number(control.val()) - 1);
                control.val(Math.max(0, newValue)).change();
            }
        };
    });

    $('#options').on("click", function () {
        $('#tabCaption').text(globalWorkRegLoc.additionalSettings);
        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

    $('.btn-back-to-menu').on("click", function () {

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        $('#sideNavBar>.tab-pane').removeClass("active");
        $('#sideNavBar>.nav>.nav-item').removeClass("active");
        $('#sideNavBar>#item-options').addClass("fade").addClass("in").addClass("active");

        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

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

    });

    $('.btn-close-side-panel').on("click", function () {
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    });

    $('#work-history').on("click", function () {
        var caption = $("#work-history").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        InitWoExregOperExp();

    });

    $('#image').on("click", function () {
        $("#imageModal").modal('show');
    }).hover(function () {
        $(this).css('cursor', 'pointer');
    });

    $('#note').on("click", function () {
        var caption = $("#note").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

    });

    $('#operation-materials').on("click", function () {
        var caption = $("#operation-materials").find("h3").text();
        $("#tabCaption>span").text(caption);

        $(".btn.btn-close-side-panel").toggleClass("hidden");
        $(".btn.btn-back-to-menu").toggleClass("hidden");

        initializeMaterialsTab();

    });

    $('#finish-task').on("click", function () {

        if ($("#finish-task").hasClass('active')) {
            $("#finish-task").removeClass("active");
            $("#finish-task :input").prop('checked', false);

        } else {
            $("#finish-task").addClass("active");
            $("#finish-task :input").prop('checked', true);
        }


    });

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

    if ($(".divided-content-toggle-open").hasClass('hidden')) {
        InitWoExregOperExp();
    }

    $('.divided-content-toggle-open').on("click", function () {
        InitWoExregOperExp();
    });

    $("#Worker").off("change.tableReload");
    $("#Worker").on("change.tableReload", function (e) {

        $("#Worker").val($("#Worker option:selected").val());
        createEvent(this);

    });

    $("#billable").on('change', updateTime);
    $("#nonChargeable").on('change', updateTime);
};

function startWorkRecording(button) {

    var icon = $(button).data("icon");

    if ($('#Worker').val() === "") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedEmployee",
            type: "alert",
            text: globalWorkRegLoc.notEmployeeText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        return false;
    }

    swapLoadingIcon(true, $(button).attr('id'), icon);
    $(button).attr("disabled", true);

    createEvent(button);

}

function createEvent(button) {

    var eventType = $(button).data("event-type");
    var buttonId = $(button).attr('id');
    var fromDailyPlan = globalWorkRegParams.prodType === "MF" ? localStorage.getItem('WoFromDailyPlan') : "false";

    $.ajax({
        url: globalWorkRegUrls.createEvent,
        type: "POST",
        dataType: 'json',
        data: {
            AcKey: $("#AcKey").val(),
            AnNo: $("#AnNo").val(),
            Ident: $("#Ident").val(),
            Descr: $("#Descr").val(),
            UM: $("#UM").val(),
            EventType: eventType,
            EventTime: $("#EventTime").val(),
            ResursID: $("#ResursID").val(),
            Worker: $("#Worker").val(),
            Priority: $("#Priority").val(),
            CalendarQId: fromDailyPlan == 'true' ? $("#CalendarQId").val() : "",
            Shift: $("#Shift").val(),
            QId: $("#QId").val()
        },

        success: function (result) {

            $("#EventType").val(result.EventType);
            $("#Milliseconds").val(result.Milliseconds);
            $("#billable").val(result.UsedTime);
            $("#UsedTime").val(result.UsedTime);
            $("#QId").val(result.QId)
            $("#stopwatch-card h3:first-child").css("color", result.Color)
            $("#stopwatch-card i:first-child").css("color", result.Color).attr("class", result.Icon);

            ShowActionButtons(result.EventType);
            setInProgressWork(result.EventType);
            swapLoadingIcon(false, buttonId, result.Icon);
        },
        error: function (error) {
            swapLoadingIcon(false, buttonId, result.Icon);
        }
    });
}

function continueStopwatch(milliseconds, eventType) {

    $('#stopwatch').remove();
    $('#stopwatch-div').append('<span style="font-size: 18px" id="stopwatch" class="stopwatch">00:00:00</span>');

    if ((eventType === "OP") || (eventType === "OE")) {
        $('#stopwatch').unbind('tick.stopwatch');
        $('#stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('render');
        $('#stopwatch').stopwatch({ startTime: milliseconds }).stopwatch('stop');
        $("#progress-bar").removeClass("bg-c-green");
        switch (eventType) {
            case "OE": $("#progress-bar").removeClass("bg-c-yellow").addClass("bg-c-red"); break;
            default: $("#progress-bar").addClass("bg-c-yellow")
        }
    }
    else {
        $('#stopwatch')
            .stopwatch({ startTime: milliseconds })
            .bind('tick.stopwatch', function (e, elapsed) {

                let usedTime = toNumber($("#UsedTime").val());
                $("#billable").val((elapsed/3600/1000).toFixed(globalWorkRegParams.woExDecPlacesOper));

                let remainingTime = parseFloat($("#RemainingTime").val().replace(",", "."));
                remainingTime = remainingTime * 3600 * 1000;

                var _progressValue = elapsed > remainingTime ? 100 : (elapsed / remainingTime) * 100;
                var _progressPerc = _progressValue.toFixed(2) + "%";

                $("#progress-bar").css("width", _progressPerc);
                $("#progress-bar").attr("aria-valuenow", _progressValue);
                $("#progress-bar").attr("title", _progressPerc);
                $("#progress-bar").removeClass("bg-c-red").removeClass("bg-c-yellow").addClass("bg-c-green");
                _progressValue > 100 ? $("#progress-bar").removeClass("bg-c-green").addClass("bg-c-red") : $("#progress-bar").removeClass("bg-c-red").addClass("bg-c-green");

            }).stopwatch('start');
    }
}

function setInProgressWork(eventType) {

    let usedTime = toNumber($("#UsedTime").val());
    let remainingTime = toNumber($("#RemainingTime").val());
    let doneTime = toNumber($("#DoneTime").val());
    let planTime = toNumber($("#PlanTime").val());

    $("#billable").val(usedTime.toFixed(globalWorkRegParams.woExDecPlacesOper));
    $("#nonChargeable").val(0);

    let _progressValue = toNumber($("#ProgressValue").val());
    let _progressPerc = _progressValue.toFixed(2) + "%";

    if (eventType != "") {

        _progressValue = usedTime > remainingTime ? 100 : (usedTime / remainingTime) * 100;
        _progressPerc = _progressValue.toFixed(2) + "%";

        $('#planTime').html('/' + $("#RemainingTimeStr").val());
        $('#doneTime').addClass('hidden');
        $('#stopwatch').removeClass('hidden');  
        if (!globalWorkRegParams.isMobile) {
            $('#editMat-ident-div').parent().parent().addClass('document-head-disabled-input');
            $('#editMat-ident-div').addClass('hidden');
            $('#ident').removeClass('hidden');
        }

        continueStopwatch(parseInt($("#Milliseconds").val(), 0), eventType);
    }
    else {

        $('#doneTime').removeClass('hidden');
        $('#stopwatch').addClass('hidden');
        $('#stopwatch').unbind('tick.stopwatch');

        if (!globalWorkRegParams.isMobile) {
            if (doneTime > 0) {
                $('#editMat-ident-div').addClass('hidden');
                $('#ident').removeClass('hidden');
            }
            else {
                $('#editMat-ident-div').parent().parent().removeClass('document-head-disabled-input');
                $('#editMat-ident-div').removeClass(' document-head-select');
                $('#editMat-ident-div').removeClass('hidden');
                $('#ident').addClass('hidden');
            }
        }
    }

    $("#progress-bar").css("width", _progressPerc);
    $("#progress-bar").attr("aria-valuenow", _progressValue);
    $("#progress-bar").attr("title", _progressPerc);

    _progressValue > 100 ?? $("#progress-bar").removeClass("bg-c-green").addClass("bg-c-red");

}

function confirmOperationWork() {

    if ($('#Worker').val() === "") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedEmployee",
            type: "alert",
            text: globalWorkRegLoc.notEmployeeText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(globalWorkRegParams.isMobile);
        return false;
    }  

    if (toNumber($("#UsedTime").val()) == 0) {
        var requiedText = globalWorkRegLoc.requiedQty;
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedInput",
            type: "alert",
            text: requiedText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(globalWorkRegParams.isMobile);
        return false;
    };

    swapLoadingIcon(true, "confirmButton", "fa fa-check");
    $("#confirmButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Date: $("#Date").val(),
        UM: $("#UM").val(),
        Worker: $("#Worker").val(),
        BeginTime: $("#EventTime").val(),
        Time: $("#billable").val().replace('.', ','),
        Qty: $("#billable").val().replace('.', ','),
        WasteQty: $("#nonChargeable").val().replace('.', ','),
        Note: $("#Note").val(),
        Finished: $("#finishOperation").is(":checked"),
        ProdType: globalWorkRegParams.prodType
    };

    $.post(globalWorkRegUrls.confirmOperation, data)
        .done(function (response) {

            if (response.Success) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupSuccessModal",
                    type: "success",
                    text: globalWorkRegLoc.successWorkMsg,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary',
                            action: function () {
                                if (data.Finished == 'Y') {
                                    location.href = "WorkOrderOperations?key=" + data.AcKey;
                                }
                                else {
                                    location.reload();
                                }
                            }
                        }
                    ]
                });
                customModalForMobile(globalWorkRegParams.isMobile);

            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(globalWorkRegParams.isMobile);

            }

            swapLoadingIcon(false, "confirmButton", "fa fa-check");
            $("#confirmButton").removeClass('disabled');
        });

}

function deleteWorkReg() {

    swapLoadingIcon(true, "cancelButton", "far fa-window-close");
    $("#confirmButton").addClass('disabled');
    $("#cancelButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Worker: $("#Worker").val(),
        ResursID: $("#ResursID").val()
    };

    $.post(globalWorkRegUrls.deleteOperWork, data)
        .done(function (response) {

            if (response.Success) {
                location.reload();
            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(globalWorkRegParams.isMobile);

            }

            swapLoadingIcon(false, "cancelButton", "far fa-window-close");
            $("#cancelButton").removeClass('disabled');
            $("#confirmButton").removeClass('disabled');
        });

}

function deleteWOExRegOperExp(isMobile) {

    swapLoadingIcon(true, "cancelButton", "far fa-window-close");
    $("#confirmButton").addClass('disabled');
    $("#cancelButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Worker: $("#Worker").val(),
        ResursID: $("#ResursID").val(),
        QId: $("#QId").val()
    };

    $.post(globalWorkRegUrls.deleteWOExRegOperExp, data)
        .done(function (response) {

            if (response.Success) {
                let queryParams = new URLSearchParams(window.location.search);
                queryParams.set('sET', '');
                url.search = queryParams.toString();
                new_url = url.toString();
                window.location.href = new_url;
            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(globalWorkRegParams.isMobile);

            }

            swapLoadingIcon(false, "cancelButton", "far fa-window-close");
            $("#cancelButton").removeClass('disabled');
            $("#confirmButton").removeClass('disabled');
        });

}

function saveWorkRegOperExp(isMobile) {

    if ($('#Worker').val() === "") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            id: "requiedEmployee",
            type: "alert",
            text: globalWorkRegLoc.notEmployeeText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: globalWorkRegLoc.ok,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
        customModalForMobile(globalWorkRegParams.isMobile);
        return false;
    }

    swapLoadingIcon(true, "saveButton", "fa fa-check");
    $("#saveButton").addClass('disabled');

    var data = {
        AcKey: $("#AcKey").val(),
        AnNo: $("#AnNo").val(),
        Ident: $("#Ident").val(),
        Descr: $("#Descr").val(),
        UM: $("#UM").val(),
        EventType: $("#EventType").val(),
        EventTime: $("#EventTime").val(),
        ResursID: $("#ResursID").val(),
        Worker: $("#Worker").val(),
        ParentWorker: $("#ParentWorker").val(),
        Priority: $("#Priority").val(),
        CalendarQId: $("#CalendarQId").val(),
        Date: $("#Date").val(),
        Shift: $("#Shift").val(),
        QId: $("#QId").val(),
        Milliseconds: toNumber($("#Milliseconds").val()),
        GoodPcs: $("#goodPcs").val().replace('.', ','),
        ScrapPcs: $("#scrapPcs").val().replace('.', ','),
        ScrapId: $('#selected-scrap').val(),
        WastePcs: $("#wastePcs").val().replace('.', ','),
        RepairQty: $("#repairPcs").val().replace('.', ','),
        RepairId: $('#selected-repair').val(),
        HoldUps: $("#holdUpQty").val().replace('.', ','),
        HoldUpId: $('#selected-holdup').val(),
        Note: $("#Note").val(),
        Finished: $("#finishOperation").is(":checked") ? "Y" : "N",
        ConfirmReceive: $("#confirmReceive").is(":checked") ? "1" : "0",
        ProdType: globalWorkRegParams.prodType

    };

    $.post(globalWorkRegUrls.saveWOExRegOperExp, data)
        .done(function (response) {

            if (response) {
                location.reload();
            } else {

                let errorText = response.Error;

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    id: "displayPopupErrorModal",
                    type: "alert",
                    text: errorText,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: globalWorkRegLoc.ok,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
                customModalForMobile(globalWorkRegParams.isMobile);
            }
            swapLoadingIcon(false, "saveButton", "fa fa-check");
            $("#saveButton").removeClass('disabled');
        });
}


function InitWoExregOperExp() {
    var decPlaces = globalWorkRegParams.woExDecPlacesOper;

    $dataTable = $('#woExRegOperExp');

    $dataTable.DataTable({
        responsive: true,
        serverSide: false,
        scroller: false,
        paging: false,
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Key = $("#AcKey").val();
                d.No = $("#AnNo").val();
                d.ResursID = $("#ResursID").val();
                d.ProductionType = globalWorkRegParams.prodType;
                d.ParentKey = $("#WoExItem_QId").val();
            }
        },
        columns: [

            { data: "Worker", name: "Worker" },
            {
                data: "DateStr", name: "DateStr",
                render: function (data, type, full) {
                    return data + " " + full.BeginTimeStr
                }
            },

            {
                data: "GoodPcs", name: "GoodPcs", className: "dt-body-center",
                render: function (data, type, full) {
                    return '<span class="label-danger" style="padding:5px; border-radius:10px">' + round(full.GoodPcs, decPlaces).toString().replace('.', ',') + '</span>';
                }
            },

            {
                name: "ScrapPcs", className: "dt-body-center",
                render: function (data, type, full) {
                    return '<span class="label-success m-r-sm" style="padding:5px; border-radius:10px">' + round(full.ScrapPcs, decPlaces).toString().replace('.', ',') + '</span>';
                }
            },

            {
                data: "Time", name: "Time", className: "dt-body-center",
                render: function (data, type, full) {
                    return '<span class="label-primary m-r-sm" style="padding:5px; border-radius:10px">' + round(full.Time, decPlaces).toString().replace('.', ',') + '</span>';
                }
            },

            {
                data: "Note", name: "Note",
                render: function (data, type, full) {
                    console.log(data)

                    var noteClass = (data == null || data == undefined || data == '') ? " transparent-color" : "theme-color";
                    return type === 'display' ?
                        '<button type="button" class="btn btn-link m-r-sm" data-note="' + data + '" onclick="openWoExOperRegExpNoteModal(this)">' +
                        '<i class="fa fa-comment description-hidden-icon ' + noteClass + '" ></i>' +
                        '</button >' : data;
                }
            }

        ]
    });

}

function initializeMaterialsTab() {

    $itemsTable = $('#mainGridMaterials');
    var itemsTable = $itemsTable.DataTable({
        initComplete: function () {
            $('.dataTables_scrollBody').css('max-height', '100vh');
            $('.dataTables_scrollBody').css('height', '100vh');

        },
        ajax: {
            url: $itemsTable.attr('data-url'),
            data: function (d) {
                d.Key = $("#AcKey").val();
                d.No = $("#AnNo").val();
                d.ItemType = "";
            }
        },
        columns: [
            {
                class: 'border-bottom',
                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: "IdentDescr",
                name: "IdentDescr",
                filtertype: "text",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '    <span data-toggle="tooltip"  class="card-caption"  data-original-title="' + data + '" >' + data + '</span>' : data;

                }
            },
            {
                data: "AnNo",
                name: "AnNo",
                filtertype: "text",
                className: "dt-body-left",
                render: function (data, type, full) {
                    return type === 'display' ?
                        '<span style="margin-right:2px"> <i class="fa fa-hashtag"></i> </span> <span>' + data + '</span>' : data;
                }
            },
            {
                data: 'CompletedPrcQty',
                render: function (data, type, full) {
                    var color = data >= 100 ? "bg-c-green" : "bg-c-yellow"
                    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>' + full.Status + ' (' + round(full.CompletedPrcQty, decPlaces).toString().replace('.', ',') + '%)</span>' +
                        '<span class="pull-right">' + round(full.DonePcs, decPlaces).toString().replace('.', ',') + '/' + round(full.PlanPcs, decPlaces).toString().replace('.', ',') + ' ' + full.UM + '</span>' : data;

                }
            }

        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
        },
        drawCallback: function () {
            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            });
        }
    }).on('click', 'tr', function () {
        var data = itemsTable.row($(this)).data();
        window.location.href = "IssuingMaterial?key=" + data.AcKey + '&no=' + data.AnNo;
    });


};

function editTime(e) {
    element.innerHTML = '<input class="required" type="text" inputmode="none" name="time" value="00:00" style="font-size: 18px;width:80px"  onblur="spanReset(this)"  data-last-value="' + $(e).text() + '" /> ';
    $('[name="time"]').datetimepicker({
        format: 'HH:mm'
    });

    $('[name="time"]').focus();
}

function spanReset(e) {
    let value = e.value;
    let timePrev = $(e).attr("data-last-value");
    let element = document.getElementById('element');

    let seconds = moment.duration(value).asSeconds();
    let hours = seconds / 3600;
    let formattedHours = hours.toFixed(6);

    $("#UsedTime").val(formattedHours.replace('.', ','));

    if (seconds === 0) {
        value = timePrev;
        $("#start").removeClass("hidden");
        $("#confirmButton").addClass("hidden");
        $("#cancelButton").addClass("hidden");
    }
    else {
        $("#start").addClass("hidden");
        $("#confirmButton").removeClass("hidden");
        $("#cancelButton").removeClass("hidden");

        $('#billable').val(formattedHours);
    }

    element.innerHTML = "<span id='doneTime' style='font-size: 18px' class='@(!Model.EventType.IsEmpty() ? 'hidden' : String.Empty) ' onclick = 'editTime(this)' >" + value + "</span >";
}

function openWoExOperRegExpNoteModal(button) {
    $("#modalSave").addClass("hidden");
    $("#modalClose").removeClass("hidden");

    $("#modalNote").text($(button).data("note"));
    $('#note-modal').modal('show');
}

function UpdatePosition(button) {
    var buttonId = $(button).attr('id');
    var formData = $("#workRegistrationForm").serializeArray();

    $.each(formData, function () {
        if (!isNaN(this.value)) {
            this.value = this.value.replace('.', ',');
        }
    });
    swapLoadingIcon(true, buttonId, "fa fa-check");

    $.ajax({
        cache: false,
        type: "POST",
        url: globalWorkRegUrls.updatePosition,
        data: formData,
        success: function (response) {
            if (response.success) {
                location.reload();
            }
            else {
                response.message = response.message.replace(/\\n/g, "<br>");

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: response.message,
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: globalWorkRegParams.ok,
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }

            swapLoadingIcon(false, buttonId, "fa fa-check");
        },
        error: function (error) {
            console.error(error);

            swapLoadingIcon(false, buttonId, "fa fa-check");
        }
    });
}

function cancelIdentChange() {
    $('Ident').val(initialIdent);

    if (initialIdent !== null) {
        $('#Ident').val(initialIdent);
        $('#ident').val(initialIdent);
        $('#editMat-ident').val(initialIdent);
        $('#editMat-ident').selectpicker('refresh');
    }
    $('.ident-list-item').find('i').removeClass('fa-check');
    $('.ident-list-item').removeClass('active');
    if (initialActiveItem) {
        initialActiveItem.find('i').addClass('fa-check');
        initialActiveItem.addClass('active');
    }

    $('#start').show();
    $('#confirmButton').addClass('hidden');
    $('#confirmButton').attr('onclick', 'confirmOperationWork()');
    $('#cancelButton').addClass('hidden');
    $('#cancelButton').attr('onclick', 'deleteWorkReg()');

    initialIdent = null;
    initialActiveItem = null;
}

function updateTime() {


    let billableDecimal = parseFloat($("#billable").val()) || 0;
    let nonBillableDecimal = parseFloat($("#nonChargeable").val()) || 0;
    let timeDecimal = billableDecimal + nonBillableDecimal;
    let time = decimalToTime(billableDecimal + nonBillableDecimal);

    if (globalWorkRegParams.isEventTypeNull === "True") {
        $("#start").addClass("hidden");
        $("#confirmButton").removeClass("hidden");
        $("#cancelButton").removeClass("hidden");
    }

    $('#stopwatch').text(time);
    $('#doneTime').text(time);
    $("#UsedTime").val(timeDecimal);
    $('#planTime').html('/' + $("#RemainingTimeStr").val());
}
