var confirmText = $("#Confirm").val();
var cancelText = $("#Cancel").val();
var visibleWorkerColumns = false;

dateTimePickersOnChange();

$(document).ready(function () {
    initializeEducations();
    workerDropDownListOnChange();
    disableDeleteButtonForOpenEducation();   
});

function initializeEducations() {
    let columns = [
        {
            data: function (data) {
                return data.QId;
            },
            orderable: false,
            className: 'dt-body-center',
            render: function (data) { return '<input class="id" name="educationId" onclick=CheckBoxClicked("' + data + '") value="' + data + '" type="checkbox"/>'; }
        },
        { data: "", name: "", render: $.fn.dataTable.render.preview("Id"), className: 'dt-body-center dt-head-center' },
        { data: "Type", name: "Type", filtertype: "text" },
        { data: "FuncKnow", name: "FuncKnow", filtertype: "text", render: $.fn.dataTable.render.link("QId") },
        { data: "Performer", name: "Performer", filtertype: "text" },
        { data: "Fee", name: "Fee", filtertype: "text", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val(), '') },
        { data: "PrimCurrency", name: "PrimCurrency", filtertype: "text" },
        { data: "Duration", name: "Duration", filtertype: "text" },
        {
            data: "DateStart", name: "DateStart", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        {
            data: "DateEnd", name: "DateEnd", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        {
            data: "PassedTest", name: "PassedTest", filtertype: "text", render: function (data) {
                if (data === null || data == "F") {
                    return "";
                } else {
                    return "<i class='fa fa-medal text-primary'></i>"
                }
            }
        },
        { data: "Rating", name: "Rating", filtertype: "text" },
        { data: "Periodical", name: "Periodical", filtertype: "text" },
        {
            data: "NextDate", name: "NextDate", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        { data: "Description", name: "Description", filtertype: "text" },
    ];

    initializeEducationDataTables('education', 'Keywords', columns);
}

function initializeEducationDataTables(tableId, keywordsId, columns) {
    var typingTimer;
    var doneTypingInterval = 600;

    if (keywordsId.length > 0) {
        $('#' + keywordsId).off('keyup');
        $('#' + keywordsId).on('keyup', function () {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(function () { reloadDataTable(tableId); }, doneTypingInterval);
        });
    }

    $(".selectpicker-dropdown").on("hide.bs.dropdown", function () {
        reloadDataTable(tableId);
    });

    if ($('#' + tableId).length !== 0) {
        $dataTable = $('#' + tableId);
        $dataTable.DataTable({
            ajax: {
                url: $dataTable.attr('data-url'),
                data: function (d) {
                    d.Keywords = $('#' + keywordsId).val();
                    d.DateFrom = $("#EducationDateFrom").val();
                    d.DateTo = $("#EducationDateTo").val();
                    d.SelectedTypes = $("#Types").val();
                    d.SelectedWorkers = $("#Workers").val();
                    d.Names = $("#Names").val();
                    d.Performers = $("#Performers").val();
                }
            },
            columns: columns,
        });
    }
}

function initializeSidebarEducations(activeEducationQId) {
    $dataTable = $('#side-educations-table');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.Keywords = $("#Keywords").val();
                d.DateTo = moment(new Date()).toISOString();
            }
        },
        columns: [
            {
                data: function (data) {
                    var rowDiv = "<div onclick=openEducationUrl('" + data.QId + "'); class='row dt-education-row' data-education='" + data.FuncKnow + "'>";
                    var subtext = '';

                    if (data.Type && data.Performer) {
                        subtext = data.Type + " • " + data.Performer;
                    } else if (data.Type) {
                        subtext = data.Type;
                    } else if (data.Performer) {
                        subtext = data.Performer;
                    }

                    return rowDiv + "<div class='col-md-12'>" + data.FuncKnow + "<br/><span class='text-muted'>" + subtext + "</span></div></div>";
                },
                orderable: false,
                className: 'dt-education-side-col',
                render: function (data) {
                    return data;
                }
            }
        ],
        "createdRow": function (row, data, dataIndex) {
            if (data.QId == activeEducationQId) {
                $(row).children().addClass('side-menu-item-active');
            }
        }
    });

    var typingTimer;
    var doneTypingInterval = 600;
    $('#Keywords').off('keyup');
    $('#Keywords').on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($dataTable); }, doneTypingInterval);
    });
}

function initializeRegisteredWorkers() {
    $dataTable = $('#registered-workers');
    $dataTable.DataTable({
        ajax: {
            url: $dataTable.attr('data-url'),
            data: function (d) {
                d.educationId = $("#EducationId").val();
            }
        },
        columns: [
            {
                data: function (data) {
                    return data.Worker;
                },
                orderable: false,
                className: 'dt-body-center',
                render: function (data) { return '<input class="id" name="workerId" type="checkbox"/>'; }
            },
            {
                data: function (data) {
                    if (data.ProfilePhoto) {
                        return "<img class='dt-image-circle' src='" + data.ProfilePhoto + "' />";
                    }
                    else {
                        return "<div class='dt-text-avatar'>" + data.Avatar + "</div>";
                    }
                },
                orderable: false,
                className: 'dt-col-no-padding',
                render: function (data) {
                    return data;
                }
            },
            { data: "Worker", name: "Worker", filtertype: "text" },
            { data: "FullName", name: "FullName", filtertype: "text" },
            { data: "Department", name: "Department", filtertype: "text" },
            { data: "Job", name: "Job", filtertype: "text" },
        ]
    });
}

function openEducationUrl(educationQId) {
    window.location = $('#side-educations-table').attr('data-details-url') + "?qId=" + educationQId;
}

function dateTimePickersOnChange() {
    $("#DateStart").on("change", function () {
        if ($("#DateEnd").val()) {
            const duration = calculateEducationDuration("DateStart", "DateEnd");
            $("#Education_Duration").val(duration);
        }
    });

    $("#DateEnd").on("change", function () {
        if ($("#DateStart").val()) {
            const duration = calculateEducationDuration("DateStart", "DateEnd");
            $("#Education_Duration").val(duration);
        }
    });
}

function workerDropDownListOnChange() {
    $("#Workers").on("change", function () {
        if ($(this).val() && !visibleWorkerColumns) {
            showHideWorkerColumns(true);
            addItemsInDropdown();
        }

        if (!$(this).val()) {
            $('.worker-col-to-hide').remove();
            showHideWorkerColumns(false);
        }
    });
}

function showHideWorkerColumns(hidden) {
    $('#education').DataTable().column(10).visible(hidden);
    $('#education').DataTable().column(11).visible(hidden);

    visibleWorkerColumns = hidden;
}

function addItemsInDropdown() {
    let listElements = "";

    $('.dataTable:first > thead > tr > th').each(function (index) {
        if ($(this).hasClass("workerhidden")) {
            var thNodeText = $(this).text().trim();
            if (thNodeText) {
                var dropdownElement = `
                <li class='worker-col-to-hide' style='padding: 4px 6px;'>
                    <label style='width: 100%' class='custom-checkbox-container'>
                        <input type='checkbox' data-column='${index}' name='${thNodeText}' class='custom-checkbox-DT' checked='checked' />
                        ${thNodeText}
                        <span class="custom-checkbox-checkmark"></span>
                    </label>
                </li>`;

                listElements += dropdownElement;
            }
        }
    });

    $('.show-hide-column').append(listElements);
    $(".show-hide-column li")
        .sort((a, b) => $(a).find('label').find('input').data("column") - $(b).find('label').find('input').data("column"))
        .appendTo(".show-hide-column");
};

var deleteItems = [];
var selectedKeys = [];
var allowedDeleteQids = [];
function CheckBoxClicked(id) {
    if (!selectedKeys.includes(id)) {
        selectedKeys.push(id);
    }
    else {
        let index = selectedKeys.indexOf(id);
        selectedKeys.splice(index, 1);
    }
    
    if (selectedKeys.length > 0) {
        $('#duplicateButton').removeClass('disabled');
        $('#deleteButton').removeClass('disabled');
    }
    else {
        $('#duplicateButton').addClass('disabled');
        $('#deleteButton').addClass('disabled');
    }
}

function showGeneralErrorMessage() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#GeneralErrorMessage").val() + error,
        buttons: [
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function calculateEducationDuration(dateStartId, dateEndId) {
    let [dateStart, timeStart] = $("#" + dateStartId).val().split(" ");
    let reformatedDateStart = reformatDate(dateStart);
    let [dateEnd, timeEnd] = $("#" + dateEndId).val().split(" ");
    let reformatedDateEnd = reformatDate(dateEnd);
    let dateTime = calculateDuration(new Date(reformatedDateStart + " " + timeStart), new Date(reformatedDateEnd + " " + timeEnd));

    let duration = `${dateTime.days} ${$("#DurationDays").val()} ${dateTime.hours} ${$("#DurationHours").val()} ${dateTime.minutes} ${$("#DurationMinutes").val()}`;

    if (duration.length > 19) {
        duration = duration.substring(0, 19);
    }

    return duration;
}

function disableSaveButton() {
    swapLoadingIcon(true, "saveButton", "fa fa-save");
    $("#saveButton").addClass("print-btn-disable");
}

function enableSaveButton() {
    swapLoadingIcon(false, "saveButton", "fa fa-save");
    $("#saveButton").removeClass("print-btn-disable");
}

function onCreateEditBegin() {
    disableSaveButton();
}

function onCreateEditSuccess(response) {
    if (response.redirectUrl) {
        window.location.href = response.redirectUrl;
    } else {
        enableSaveButton();
        dateTimePickersOnChange();

        dateTimePicker("DateStart");
        dateTimePicker("DateEnd");

        $("#PrimCurrency").selectpicker();
        initializeSelect2WithAPI("#FuncKnowValue");
        initializeSelect2WithAPI("#Worker");
    }
}

function educationDropDownChange() {
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetSubjEducation").val(),
        data: {
            id: $("#FuncKnowValue").val()
        },
        success: function (result) {
            $("#Performer").val(result.Performer);
            $("#EducationType").val(result.Type);
            $("#Education_TypeValue").val(result.TypeValue)
            $("#Education_FuncKnow").val(result.FuncKnow);
        },
        error: function (error) {
            console.log(error)
        }
    });
}

function getOpenedEducationRowsIds() {
    const openedRowsIds = [];
    $("#collapse-educations .open-position a:not(.collapsed)").each(function () {
        const educationRowId = $(this).closest(".education-panel").attr("id");
        openedRowsIds.push(educationRowId)
    });

    return openedRowsIds;
}

function reloadEducationsPartial(data, rowsToOpen) {
    $("#registered-workers-educ").html(data);
    applyJsSwitch();
    $.each(rowsToOpen, function (i, row) {
        $("#" + row).find(".open-position").first().click();
    });
    disableDeleteButtonForOpenEducation();   
}

function addWorkerToEducation() {
    const worker = $("#NewWorker").val();
    if (worker) {
        $.ajax({
            cache: false,
            type: "GET",
            url: $("#GetEducationWorker").val(),
            data: {
                worker: worker
            },
            success: function (data) {
                $("#NewlyAddedWorker").val(worker); 
                $("#NewWorker").val("").change();
                $(".new-worker-avatar, .new-worker-image").addClass("hidden");
                $(".new-worker-name").text(data.FullName);
                if (data.ProfilePhoto) {
                    $(".new-worker-image").attr("src", data.ProfilePhoto).removeClass("hidden");
                } else if (data.Avatar) {
                    $(".new-worker-avatar").text(data.Avatar).removeClass("hidden");
                }
                $('.new-worker-row').removeClass('hidden');
            }
        });
    }
}

function hideNewWorkerSection() {
    $('.new-worker-row').addClass('hidden');
}

function addEducationForWorker() {
    const educationRowsIds = getOpenedEducationRowsIds();
    $.ajax({
        cache: false,
        type: "POST",
        url: $("#AddEducation").val(),
        data: {
            FuncKnow: $("#Education_FuncKnow").val(),
            Performer: $("#Performer").val(),
            TypeValue: $("#Education_TypeValue").val(),
            DateStart: moment($("#NewParticipationFrom").val(), 'DD.MM.YYYY HH:mm:ss').toISOString(),
            Duration: calculateEducationDuration("NewParticipationFrom", "NewParticipationTo"),
            Fee: $("#RegistrationFee").val(),
            PrimCurrency: $("#PrimCurrency").val(),
            MaxNoRegistered: $("#MaxNoRegistered").val(),
            Worker: $("#AddParticipationForWorker").val()
        },
        success: function (data) {
            $("#new-participation-modal").modal("hide");
            reloadEducationsPartial(data, educationRowsIds);
        }
    });
}

//#region DELETE

//#region DELETE SINGLE
function deleteSingleEducation(qId) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#DeleteEducation").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    location.href = $("#DeleteEducationUrl").val() + "?qId=" + qId;
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function deleteRegisteredEducation(qId) {
    if (qId == $("#Education_QId").val()) {
        deleteSingleEducation(qId);
    } else {
        const educationRowsIds = getOpenedEducationRowsIds();
      
        $.ajax({
            type: "DELETE",
            url: $("#DeleteRegisteredEducation").val(),
            data: {
                qId: qId
            },
            success: function (data) {
                reloadEducationsPartial(data, educationRowsIds);
            }
        });
    }
}

function disableDeleteButtonForOpenEducation() {
    const openEducation = $(".delete-education-" + $("#Education_QId").val());
    openEducation.find("a").addClass("disabled");
    openEducation.css("cursor", "not-allowed");
}
//#endregion DELETE SINGLE

//#region DELETE MULTIPLE
function deleteMultipleEducations() {
    var deleteText = $("#DeleteEducation").val();

    if (selectedKeys.length > 1) {
        deleteText = $("#DeleteEducations").val();
    }

    getEducationDeleteStatuses().then(function (data) {  
        var closeOnConfirm = true;
        if (deleteItems.length > 0) {
            closeOnConfirm = false;
        }
        showEducationActionConfirmation({
            description: deleteText,
            cancel: cancelText,
            confirm: confirmText
        }, function () {
            if (!closeOnConfirm) {
                showStatusMessages(deleteItems, allowedDeleteQids, function () {
                    isDeleteConfirmed(true);
                }, function () {
                    isDeleteConfirmed(false);
                });
            }
            else {
                isDeleteConfirmed(true);
            }
        }, closeOnConfirm);

        return;
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: deleteText,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: cancelText,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    action: async function () {
                        if (!closeOnConfirm) {
                            showStatusMessages(deleteItems, allowedDeleteQids, function () {
                                isDeleteConfirmed(true);
                            }, function () {
                                isDeleteConfirmed(false);
                            });
                        }
                        else {
                            isDeleteConfirmed(true);
                        }
                    },
                    closeOnAction: closeOnConfirm,
                    type: 'primary'
                }
            ]
        });
    });
}

function deleteMultipleEducationsAsync(allowedDeleteQids) {
    $.ajax({
        cache: false,
        type: "POST",
        url: $("#DeleteEducationsUrl").val(),
        data: {
            qIds: allowedDeleteQids
        },
        success: function (result) {
            location.reload();
        },
        error: function (error) {
            showGeneralErrorMessage();
        }
    });
}

function deleteWorkerFromEducation(worker) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#DeleteEducations").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    checkIfWorkerCanDeleteEducation(worker);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
    
}

function checkIfWorkerCanDeleteEducation(worker) {
    $.ajax({
        type: "GET",
        url: $("#CheckIfWorkerCanDeleteEducationUrl").val(),
        data: { worker },
        success: function (data) {
            if (data) {
                deleteWorkerFromEducationsAsync(worker);
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: $("#YouAreNotAllowedToDeleteEducation").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: confirmText,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        }
    });
}

function deleteWorkerFromEducationsAsync(worker) {
    const qId = $("#Education_QId").val();
    const openEducationWorker = $("#Worker").val();
    const educationRowsIds = getOpenedEducationRowsIds();

    $.ajax({
        type: "DELETE",
        url: $("#DeleteWorkerFromEducation").val(),
        data: {
            qId: qId,
            worker: worker
        },
        success: function (data) {
            if (worker == openEducationWorker) {
                window.location = $("#EducationsList").val();
            } else {
                reloadEducationsPartial(data, educationRowsIds);
            }
        }
    });
}

function getEducationDeleteStatuses() {
    var d = paw.utils.async.defer();
    $.ajax({
        type: "GET",
        url: $('#GetDeleteStatusesUrl').val(),
        data: {
            qIds: JSON.stringify(selectedKeys)
        },
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].DisplayMessage === true) {
                    deleteItems.push({ ackey: data[i].Qid, message: data[i].Message });
                }

                if (data[i].CanBeDeleted === true) {
                    allowedDeleteQids.push(data[i].Qid);
                }
            }
            d.resolve();
        }
    });
    return d.promise;
}

function isDeleteConfirmed(inputValue) {
    if (inputValue === false) {
        deleteItems = [];
        allowedDeleteQids = [];
    } else {
        deleteMultipleEducationsAsync(allowedDeleteQids);
        deleteItems = [];
        allowedDeleteQids = [];
    }
}

function showStatusMessages(messageItems, allowedQids, onConfirm, onCancel) {
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    var output = "";
    for (var i = 0; i < messageItems.length; i++) {
        output += "<p>" + messageItems[i].message + "</p>";
    }

    var buttons = [
        {
            icon: 'fa fa-times',
            text: cancelText,
            closeOnAction: true,
            action: async function () {
                onCancel();
            },
            type: 'ghost'
        }
    ];
    
    if (allowedQids.length > 0) {
        buttons.push(
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    onConfirm();
                },
                closeOnAction: true,
                type: 'primary'
            }
        );
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: output,
        buttons: buttons
    });
}

function showEducationActionConfirmation(texts, onConfirm, closeOnConfirm) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: texts.description,
        buttons: [
            {
                icon: 'fa fa-times',
                text: texts.cancel,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: texts.confirm,
                action: async function () {
                    onConfirm();
                },
                closeOnAction: closeOnConfirm,
                type: 'primary'
            }
        ]
    });
}
//#endregion DELETE MULTIPLE

//#endregion DELETE

//#region COPY
var copyNotAllowedMessages = [];
var copyAllowedQids = [];

function copyRegisteredEducation(qId) {
    const educationRowsIds = getOpenedEducationRowsIds();

    $.ajax({
        url: $("#CopyRegisteredEducation").val(),
        data: {
            qId: qId
        },
        success: function (data) {
            reloadEducationsPartial(data, educationRowsIds);
        }
    });
}

function copyMultipleEducations() {
    return getMultipleEducationCopyStatuses().then(function () {
        var closeOnConfirm = true;
        if (copyNotAllowedMessages.length > 0) {
            closeOnConfirm = false;
        }
        if (!closeOnConfirm) {
            showStatusMessages(copyNotAllowedMessages, copyAllowedQids, function () {
                isCopyConfirmed(true);
            }, function () {
                isCopyConfirmed(false);
            });
        }
        else {
            isCopyConfirmed(true);
        }
    });
}

function copyMultipleEducationsAsync() {
    $.ajax({
        cache: false,
        type: "POST",
        url: $("#CopyEducationsUrl").val(),
        data: {
            qIds: copyAllowedQids
        },
        success: function (qIds) {
            selectedKeys = [];

            // Focus and scroll to education
            if (qIds.length == 1) {
                var scrollToQId = qIds[0];
                $('#education').DataTable().ajax.reload(function (data) {
                    var rows = data.data;
                    for (var i = 0; i < rows.length; i++) {
                        if (rows[i].QId == scrollToQId) {
                            var newRow = $("#education tbody tr").eq(i);
                            newRow.first().addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                            newRow[0].scrollIntoView({ behavior: "smooth", block: "start" });
                        }
                    }
                });
            } else {
                reloadDataTable('education');
                $('#education tbody tr')[0].scrollIntoView({ behavior: "smooth", block: "start" });
            }
        },
        error: function (error) {
            showGeneralErrorMessage();
        }
    });
}

function getMultipleEducationCopyStatuses() {
    var d = paw.utils.async.defer();
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#EducationCopyStatusUrl").val(),
        async: false,
        data: {
            qIds: JSON.stringify(selectedKeys)
        },
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].DisplayMessage === true) {
                    copyNotAllowedMessages.push({ qId: data[i].Qid, message: data[i].Message });
                }

                if (data[i].CanBeCopied === true) {
                    copyAllowedQids.push(data[i].Qid);
                }
            }
            d.resolve();
        }
    });
    return d.promise;
}

function isCopyConfirmed(isConfirmed) {
    if (isConfirmed) {
        copyMultipleEducationsAsync(allowedDeleteQids);
    }
    copyNotAllowedMessages = [];
    copyAllowedQids = [];
}
//#endregion COPY

//#region PERIODS
function setPeriod(period) {
    if (period == $("#Day").val()) {
        $("#certain-day").attr("hidden", true);
        return;
    }
    $("#certain-day").removeAttr("hidden");

    if (period == $("#Month").val()) {
        showHidePeriod("#certain-day-month", "#certain-day-week");
    }
    else if (period == $("#Week").val()) {
        showHidePeriod("#certain-day-week", "#certain-day-month");
    }
}

function showHidePeriod(showId, hideId) {
    $(showId).removeAttr("hidden");
    $(hideId).attr("hidden", true);
}
//#endregion PERIODS

function collapseEducationAccordion(id, element) {
    if ($(id).hasClass('in')) {
        $(id).removeClass('in');
        $(id).addClass('collapsed');
        $(element).addClass('collapsed');
    }
    else {
        $(id).addClass('in');
        $(id).removeClass('collapsed');
        $(element).removeClass('collapsed');
    }
}

function workerOnChangeActions(worker) {
    let workers = $(worker).val() || [];

    if (workers.length > 1 || !workers.length || $("#Workers").val()[0] == "") {
        $("#performersFilter").removeClass("col-md-1").addClass("col-md-2");
        $("#statusFilter, #educationAddNew").hide();
    } else {
        $("#performersFilter").removeClass("col-md-2").addClass("col-md-1");
        $("#statusFilter, #educationAddNew").show();
    }
}

function displayEmployeeFullName() {
    var worker = $('#select2-Worker-container').text();

    if (worker.indexOf(",") > -1) {
        worker = worker.split(", ")[2] + " " + worker.split(", ")[1];
        $('#select2-Worker-container').text(worker);
    }
}

function registerEducationWorkerSelect2APIResponseFilter(currentWorkerCode, canUpdateOwnData) {
    select2WithAPIResponseFilters['education-worker'] = function (workers) {
        var index = -1;
        for (var i = 0; i < workers.length; i++) {
            var worker = workers[i];
            if (worker.Key === currentWorkerCode && !canUpdateOwnData) {
                index = i;
                break;
            }
        }
        if (index > -1) {
            workers.splice(index, 1);
        }
        return workers;
    };
}

function openSubjectSelectionModal() {
    $('#subject-selection-modal').modal('show');
}

function openSubjectInstitution() {
    const subject = $("#SelectSubject").val();
    window.location = $("#EditSubjectUrl").val() + "?type=institution&id=" + subject + "&institutionType=" + $("#EducationalInstitutionType").val();
}