var confirmText = $("#Confirm").val();
var overwriteText = $("#Overwrite").val();
var completeText = $("#Complete").val();
var addText = $("#Add").val();
var continueText = $("#Continue").val();
var itemSelected = "T";
var warningType = "W";
var errorType = "E";
var lastOpenedModal;
var clickedFormButton;

$(document).ready(function () {
    getNotificationNumbers();
    setSelectedLeadersList();

    $('.preventEscape .select2, .dropdown').on('keydown', function (e) {
        if (e.key === 'Escape') {
            e.stopPropagation();
        }
    });
});

function showTooltip() {
    $('[rel="tooltip"]').tooltip();
}

showTooltip();

$('#WholesaleFilter').on('change', function () {
    var selectedFilter = $('#WholesaleFilter :selected').val();
    var currentDate = $('#currentDate').val();
    var startMonthDate = $('#startMonthDate').val();
    var endMonthDate = $('#endMonthDate').val();
    var lastTen = $('#lastTen').val();
    var lastMonth = $('#lastMonth').val();
    var lastQuarter = $('#lastQuarter').val();
    var dateFrom = $('#Filter_DateFrom');
    var dateTo = $('#Filter_DateTo');

    if (selectedFilter === 'LastTen') {
        dateFrom.val(lastTen);
        dateTo.val(currentDate);
    }
    if (selectedFilter === 'LastMonth') {
        dateFrom.val(lastMonth);
        dateTo.val(currentDate);
    }
    if (selectedFilter === 'LastQuarter') {
        dateFrom.val(lastQuarter);
        dateTo.val(currentDate);
    }
    if (selectedFilter === 'CustomDate') {
        dateFrom.val(startMonthDate);
        dateTo.val(endMonthDate);
    }

    submitFilterForm();
});

function startLoading(container) {
    var content = "<div class='time-record-loader'><i class='fa fa-spinner fa-spin fa-2x fa-fw text-muted'></i><span class='sr-only'></span></div>";
    var mainContainer = $("#" + container);
    mainContainer.html(content);
}

$(".multidropdown").on('change', function () {
    var parentClass = $(this).closest('.col-md-2, .col-md-1');
    $(parentClass).css("overflow-y", "scroll");

    var selected = $(this).val();
    if (selected === null) {
        $(parentClass).css("overflow-y", "unset");
    }
});

function newRecordDatePicker() {
    var daysForChange = parseInt($("#DaysForChangePermission").val());

    $('.new-record-datetimepicker').datetimepicker({
        format: 'DD.MM.YYYY HH:mm',
        locale: 'sl-SI',
        minDate: moment({ h: 0, m: 0 }).add(-daysForChange, 'days'),
        //maxDate: moment({ h: 23, m: 59 }).add(7, 'days')
    }).on('dp.change', function (event) {
        $(this).trigger('change');
    });
}

newRecordDatePicker();

function confirmDelete() {
    var cancelText = $("#Cancel").val();
    var deleteWorkObligation = $("#DeleteWorkObligation").val();
    var deleteAbsence = $("#DeleteAbsence").val();
    let isAbsence = $("#Absence").val();
    let isValid = validateTime(false);
    let modalText;

    isAbsence === "true" ? modalText = deleteAbsence : modalText = deleteWorkObligation;

    if (isValid) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: modalText,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: cancelText,
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    action: async function () {
                        deleteRecord(isAbsence);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

function deleteRecord(isAbsence) {
    var url = $("#DeleteRecord").val();
    var NewRecordStartDate = $("#NewRecordStartDate").val();
    var NewRecordEndDate = $("#NewRecordEndDate").val();
    var Type = $("#Type").val();
    var workers = $("#NewRecordEmployee").val();
    var Department = $("#Department").val();
    var Note = $("#Note").val();

    if (!validateRequiredRecordFields(Type, workers, NewRecordStartDate, NewRecordEndDate)) {
        return;
    }

    $.ajax({
        cache: false,
        type: "post",
        url: url,
        async: false,
        data: {
            DateStart: NewRecordStartDate,
            DateEnd: NewRecordEndDate,
            Type: Type,
            Workers: workers,
            Department: Department,
            Note: Note,
            IsAbsence: isAbsence
        },
        success: function (data) {
            if (!data) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: $("#NoDataToDeleteInThisPeriod").val(),
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: confirmText,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {
                $('#newrecord-modal').modal('hide');
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    text: $("#DeleteAbsenceCompleted").val(),
                    type: "alert",
                });
                SaveFilterCriteria(workers);
                window.location.href = $("#TimeRecordsUrl").val();
            }
        }
    });
}

function createNewRecord(clickedButton) {
    let newRecordStartDate = $("#NewRecordStartDate").val();
    let newRecordEndDate = $("#NewRecordEndDate").val();
    const type = $("#Type").val();
    const workers = $("#NewRecordEmployee").val();
    const isAbsence = $("#Absence").val();
    const urlParams = new URLSearchParams(window.location.search);

    if (urlParams.has("WFInstanceKey")) {
        const [startDay, startMonth, startYear] = newRecordStartDate.split('.');
        newRecordStartDate = `${startYear}-${startMonth.padStart(2, '0')}-${startDay.padStart(2, '0')}`;
        const [endDay, endMonth, endYear] = newRecordEndDate.split('.');
        newRecordEndDate = `${endYear}-${endMonth.padStart(2, '0')}-${endDay.padStart(2, '0')}`;
    }
    
    if (!validateRequiredRecordFields(type, workers, newRecordStartDate, newRecordEndDate)) {
        return;
    }

    const isValid = validateTime(false);
    if (!isValid) return;
    
    swapLoadingIcon(true, "newrecord-modal-add", "fa fa-check");
    clickedFormButton = $(clickedButton).text();

    const data = {
        DateStart: newRecordStartDate,
        DateEnd: newRecordEndDate,
        Type: type,
        Workers: workers,
        IsAbsence: isAbsence,
        Department: $("#DepartmentModal").val(),
        Note: $("#Note").val(),
        CostDrv: $("#CostDrvModal").val(),
        Status: $("#Status").val()
    }

    if (isAbsence == "false" && !urlParams.has("WFInstanceKey")) {
        overlapCheck(data);
    } else {
        createNewRecordAsync(false, data);
    }
}

function overlapCheck(data) {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: $("#OverlapCheck").val(),
        data: data,
        success: function (data) {
            if (!data || data.length == 0) {
                createNewRecordAsync(false);
            } else {
                $("#newrecord-modal").modal("hide");

                const tableBody = $("#ovelaping-commitment tbody");
                $.each(data, function (i, item) {
                    const dateStart = fromISOToStandardDateFormatString(item.DateStart);
                    const dateEnd = fromISOToStandardDateFormatString(item.DateEnd);
                    const row =
                        `<tr>
                            <td>${item.Worker}</td>
                            <td>${item.CalendarId}</td>
                            <td>${dateStart}</td>
                            <td>${dateEnd}</td>     
                            <td>${item.TypeCode}</td>     
                            <td>${item.TypeName}</td>     
                        </tr>`
                    tableBody.append(row);
                });

                $("#ovelaping-commitment").modal("show");
            }
        }
    });
}

function createNewRecordAsync(saveManualRecord, data = null) {
    const isAbsence = $("#Absence").val();
    if (!data) {
        data = {
            DateStart: $("#NewRecordStartDate").val(),
            DateEnd: $("#NewRecordEndDate").val(),
            Type: $("#Type").val(),
            Workers: $("#NewRecordEmployee").val(),
            IsAbsence: isAbsence,
            Department: $("#DepartmentModal").val(),
            Note: $("#Note").val(),
            CostDrv: $("#CostDrvModal").val(),
            Status: $("#Status").val(),
            SaveManualRecord: saveManualRecord
        }
    }

    $.ajax({
        cache: false,
        type: "post",
        dataType: 'json',
        url: $("#NewRecordForm").attr("action"),
        async: true,
        data: data,
        success: function (data) {
            if (isAbsence == "true") {
                handleAbsence(data);
            } else {
                handleRecord(data);
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function handleAbsence(data) {
    swapLoadingIcon(false, "newrecord-modal-add", "fa fa-check");

    if (data.Message == $("#CreateNewRecordsError").val()) {
        $("#newrecord-modal .close").click();
        return;
    }

    data = JSON.parse(data);

    if (data.className == "THRAbsencePlanned") { // Regular absence form
        $("#newrecord-modal .close").click();
        openModal('absence-planned-working-hours', false);
        setAbsenceTitle(data.caption);
        setAbsenceHelpUrl($("#NoWorkPlanHelpUrl").val());
        fillAbsenceForm(data.dataset, false);
        setFormButtons(data.buttons, data.className);
        $("#jobId").attr("value", data.jobID);

    } else if (data.className == "TPrekrivanjeOdsotnosti") { // Something already exists at this time
        $("#newrecord-modal .close").click();
        openModal('absence-planned-working-hours', false);
        setAbsenceTitle(data.label1);
        setAbsenceHelpUrl($("#AbsenceExistHelpUrl").val());
        fillAbsenceForm(data.dataset, true);
        setFormButtons(data.buttons, data.className);
        $("#jobId").attr("value", data.jobID);
        
    } else if (data.guid) { // Successfully added
        let urlString = window.location.href;
        let url = new URL(urlString);
        let taskInstanceKey = decodeURI(url.searchParams.get("taskInstanceKey"));

        if (taskInstanceKey && taskInstanceKey != "null") {
            if ($("#newrecord-modal").is(':visible')) {
                swapLoadingIcon(true, "newrecord-modal-add", "fa fa-check");
            } else {
                disablePartialView("wrapper");
            }
            $.ajax({
                type: "post",
                url: $("#CloseWFTaskInstanceFormUrl").val(),
                data: {
                    taskInstanceKey: taskInstanceKey
                },
                success: function (result) {
                    swapLoadingIcon(false, "newrecord-modal-add", "fa fa-check");
                    enablePartialView("wrapper");
                    displayMessageModal(data);
                }
            });
        }
        else {
            displayMessageModal(data);
        }

    } else if (data.type == "warning") { // Warning form
        $("#newrecord-modal .close").click();
        $("#rest-state-message").text(data.message);
        openModal('absence-vacation', false);
        $("#dialogChecksum").attr("value", data.checksum);

    } else if (data.Status === true && data.Message == $("#StatusResponseMessageOk").val()) {
        $("#newrecord-modal .close").click();
        showMessageModal(data.Status);

    } else if (data.Status === false && (data.Message == $("#DateStartGreaterThanDateEnd").val() || data.Message == $("#StartTimeMustBeGreaterThenEndTime").val())) {
        showInvalidTimeMessage(data.Message);
    } else {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: $("#AbsenceControlModalErrorMessage").val(),
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#Confirm").val(),
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }

    $("#absence-planned-working-hours").on("hide.bs.modal", function () {
        $(".absence-control-table tbody").empty();
        $("#absence-form-buttons").empty();
    });
}

function displayMessageModal(data) {
     //"w" and "i" are array of strings with warning and info messages
    if (data.w) {
        showWarrningOrErrorModal(data.w);
    } else if (data.i) {
        showWarrningOrErrorModal(data.i);
    } else if (clickedFormButton === confirmText || clickedFormButton === overwriteText || clickedFormButton === completeText || clickedFormButton === addText || clickedFormButton === continueText) {
        showMessageModal(true, true);
        window.location.href = $("#TimeRecordsUrl").val();
    }
}

function submitVacationForm(clickedButton) {
    var url = $("#AbsenceRestState").attr("action");
    let valueClickedButton = $(clickedButton).text();
    $("#dialogResponse").attr("value", valueClickedButton.trim());
    swapLoadingIcon(true, "absence-vacation-yes", "fa fa-check");

    $.ajax({
        type: "post",
        url: url,
        async: true,
        data: {
            dialogResponse: $("#dialogResponse").val(),
            dialogChecksum: $("#dialogChecksum").val()
        },
        success: function (data) {
            swapLoadingIcon(false, "absence-vacation-yes", "fa fa-check");
            $("#absence-vacation .close").click();
        }
    });
}

function handleRecord(data) {
    data = JSON.parse(data);
    let workers = $("#NewRecordEmployee").val();

    if (data.Status === true) {
        showMessageModal(data.Status);
        SaveFilterCriteria(workers);
        $("#ovelaping-commitment").modal("hide");
        setTimeout(function () {
            window.location.href = $("#TimeRecordsUrl").val();
        }, 3000);
    } else {
        swapLoadingIcon(false, "newrecord-modal-add", "fa fa-check");
        showInvalidTimeMessage(data.Message, true);
    }
}

function submitAbsenceForm() {
    let tableBodyRows = $("#no-work-plan tbody tr");
    let buttonsDiv = $("#absence-form-buttons button");
    let url = $("#SubmitAbsencePAASFormUrl").val();
    swapLoadingIcon(true, "confirm-form", "fa fa-check");

    $.ajax({
        type: "post",
        url: url,
        async: true,
        data: $("#NoWorkPlan").serialize(),
        success: function (data) {
            swapLoadingIcon(false, "confirm-form", "fa fa-check");
            $("#absence-planned-working-hours .close").click();
            handleAbsence(data);
            tableBodyRows.remove();
            buttonsDiv.remove();
        }
    });
}

function setFormResult(clickedButton) {
    let valueClickedButton = $(clickedButton).text();
    $("#form-result").attr("value", valueClickedButton.trim());
    clickedFormButton = valueClickedButton.trim();
}

function setFormButtons(buttons, formName) {
    let buttonsDiv = $("#absence-form-buttons");

    $.each(buttons, function (i, item) {
        let buttonClass, buttonClassMargin, buttonIcon;
        let lastItem = i == buttons.length - 1;

        if (formName == "THRAbsencePlanned") {
            buttonClass = i == 0 ? "btn-primary" : "btn-link";
            buttonClassMargin = i == 0 ? "" : "m-r-xs";
            buttonIcon = i == 0 ? "fa fa-check m-r-xs" : "fa fa-times m-r-xs text-primary";
        } else {
            buttonClass = lastItem ? "btn-link" : "btn-primary";
            buttonClassMargin = i == 0 ? "" : "m-r-xs";
            buttonIcon = lastItem ? "fa fa-times m-r-xs text-primary" : "fa fa-check m-r-xs";
        }
        
        let button =
            `<button id="${item}"
                    type="button"
                    class="btn pull-right ${buttonClass} ${buttonClassMargin}"
                    onclick="setFormResult(this);swapLoadingIcon(true, '${item}', 'fa fa-check');submitAbsenceForm();">
                <i class="${buttonIcon}"></i>
                ${item}
            </button>`
        
        buttonsDiv.append(button);
    });
}

function setAbsenceTitle(titleText) {
    $("#absence-modal-title").text(titleText);
}

function setAbsenceHelpUrl(url) {
    $("#absence-help-url").attr("href", url);
}

function fillAbsenceForm(data, hasAbsence) {
    let tableBody = $("#no-work-plan tbody");
    let startAtMidnight = $("#NewRecordStartDate").val().includes("00:00");
    let endAtMidnight = $("#NewRecordEndDate").val().includes("00:00");

    $.each(data, function (i, item) {
        let isChecked = item.acSelected == itemSelected ? true : false;
        let dateStart;
        let dateEnd;
        let worker = "";
        let messageType = item.acTypeCal == warningType ? $("#Warning").val() : item.acTypeCal == errorType ? $("#Error").val() : "";
        let message = !item.acMessage ? "" : item.acMessage.trim();
        message = message.replace(/(\d+,\d*)/, n => Math.round(parseInt(n)));

        if (hasAbsence) {
            worker = item.ACCODE;
            dateStart = fromISOToStandardDateFormatString(item.ADDATESTART);
            dateEnd = fromISOToStandardDateFormatString(item.ADDATEEND);
        } else {
            worker = item.acWorker;
            dateStart = fromISOToStandardDateFormatString(item.adDateStart);
            dateEnd = fromISOToStandardDateFormatString(item.adDateEnd);
        }
        
        let row =
            `<tr>
                <td>
                    <label class="custom-checkbox-container">
                        <input id="checkbox-${i}" onchange="setSelectedValue('${i}')" type='checkbox' class='modal-checkbox custom-checkbox' ${isChecked ? 'checked' : ''} />
                        <span class="custom-checkbox-checkmark"></span>
                    </label>
                </td>
                <td>${worker}</td>
                <td>${dateStart}</td>
                <td>${dateEnd}</td>     
                
                <td style="display: none">
                    <input hidden id="selected-${i}"    name="Dataset[${i}].acSelected"     value="${item.acSelected}" class="selected-checkbox-value">
                </td>
            </tr>`

        if (startAtMidnight && endAtMidnight && message != "" && messageType != "") {
            $(".absence-midnight").removeClass("hidden");

            row =
                `<tr>
                <td>
                    <label class="custom-checkbox-container">
                        <input id="checkbox-${i}" onchange="setSelectedValue('${i}')" type='checkbox' class='modal-checkbox custom-checkbox' ${isChecked ? 'checked' : ''} />
                        <span class="custom-checkbox-checkmark"></span>
                    </label>
                </td>
                <td>${worker}</td>
                <td>${dateStart}</td>
                <td>${dateEnd}</td>                
                <td class="separate-mess">${message}</td>
                <td>${messageType}</td>
                
                <td style="display: none">
                    <input hidden id="selected-${i}"    name="Dataset[${i}].acSelected"     value="${item.acSelected}" class="selected-checkbox-value">
                </td>
            </tr>`
        } else {
            $(".absence-midnight").addClass("hidden");
        }

        tableBody.append(row);
    });
}

function toggleCheckboxes() {
    $(".toggle-checkboxes").change(function () {
        $(".modal-checkbox").prop('checked', $(this).prop("checked"));

        if ($(".toggle-checkboxes").is(":checked")) {
            $(".selected-checkbox-value").attr("value", "T");
        } else {
            $(".selected-checkbox-value").attr("value", "F");
        }

        $('.modal-checkbox').on('click', function () {
            if ($('.modal-checkbox:checked').length == $('.modal-checkbox').length) {
                $('.toggle-checkboxes').prop('checked', true);
            } else {
                $('.toggle-checkboxes').prop('checked', false);
            }
        });
    });
}

function setSelectedValue(index) {
    if ($("#checkbox-" + index).is(":checked")) {
        $("#selected-" + index).attr("value", "T");
    } else {
        $("#selected -" + index).attr("value", "F");
    }
}

function validateTime(isRequest) {
    let NewRecordStartDate = $("#NewRecordStartDate").val();
    let NewRecordEndDate = $("#NewRecordEndDate").val();
    let dateTimeFrom = $('[name="DateTimeFrom"]').val();
    let dateTimeTo = $('[name="DateTimeTo"]').val();

    let timeStartGreaterThanTimeEnd = $("#DateStartGreaterThanDateEnd").val();
    let timeStartCannotBeEmpty = $("#TimeStartCannotBeEmpty").val();
    let timeEndCannotBeEmpty = $("#TimeEndCannotBeEmpty").val();
    var startTimeMustBeGreaterThenEndTime = $("#StartTimeMustBeGreaterThenEndTime").val()

    if (isRequest) {
        if (new Date(dateTimeFrom) > new Date(dateTimeTo)) {
            if (new Date(dateTimeFrom).toDateString() == new Date(dateTimeTo).toDateString()) {
                showInvalidTimeMessage(startTimeMustBeGreaterThenEndTime, false);
            }
            else {
                showInvalidTimeMessage(timeStartGreaterThanTimeEnd, false);
            }
            return false;
        }
        if (!dateTimeFrom) {
            showInvalidTimeMessage(timeStartCannotBeEmpty, false);
            return false;
        }
        if (!dateTimeTo) {
            showInvalidTimeMessage(timeEndCannotBeEmpty, false);
            return false;
        }

        return true;
    }

    if (new Date(NewRecordStartDate) > new Date(NewRecordEndDate)) {
        if (new Date(NewRecordStartDate).toDateString() == new Date(NewRecordEndDate).toDateString()) {
            showInvalidTimeMessage(startTimeMustBeGreaterThenEndTime, false);
        }
        else {
            showInvalidTimeMessage(timeStartGreaterThanTimeEnd, false);
        }
        return false;
    }
    if (!NewRecordStartDate) {
        showInvalidTimeMessage(timeStartCannotBeEmpty, false);
        return false;
    }
    if (!NewRecordEndDate) {
        showInvalidTimeMessage(timeEndCannotBeEmpty, false);
        return false;
    }

    return true;
}

function showInvalidTimeMessage(message, alert) {
    var type = alert == true ? "alert" : "error";

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: type,
        text: message,
        buttons: [
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function showMessageModal(status, absenceAdded = false) {
    var text = $("#CreateNewRecordsError").val();

    if (status) text = $("#RecordAdded").val();
    if (absenceAdded) text = $("#AbsencePropagationCompleted").val();

    $().customModal({
        onClose: function () { $('#newrecord-modal').modal('hide'); },
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: text,
        buttons: [
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function showWarrningOrErrorModal(listOfMess) {
    const combinedMessages = listOfMess.join("\n");

    $().customModal({
        onClose: function () {
            $("#newrecord-modal .close").click();
            window.location.href = $("#TimeRecordsUrl").val();
        },
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: combinedMessages,
        buttons: [
            {
                icon: 'fa fa-check',
                text: confirmText,
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}


function SaveFilterCriteria(newRecordWorkers) {

    var currentWorker = $("#Worker").val();
    var workObligations = $("#WorkObligations").val();
    var department = $("#Department").val();
    var period = $("#WholesaleFilter").val();
    var dateFrom = $("#Filter_DateFrom").val();
    var dateTo = $("#Filter_DateTo").val();

    if (newRecordWorkers.length > 0)
        currentWorker = newRecordWorkers[0];

    var filter = { department: department, period: period, dateFrom: dateFrom, dateTo: dateTo, worker: currentWorker };

    localStorage.setItem('NewTimeRecordFilter', JSON.stringify(filter));
}

function GetFilterCriteria() {
    var filterObject = localStorage.getItem('NewTimeRecordFilter');

    if (filterObject !== null) {
        var filter = JSON.parse(filterObject);

        $("#Filter_DateFrom").val(filter.dateFrom);
        $("#Filter_DateTo").val(filter.dateTo);
        var workerOption = new Option(filter.worker, filter.worker, false, true);
        $('#Worker').append(workerOption).trigger('change');

        if (filter.department) {
            var department = new Option(filter.department, filter.department, false, true);
            $('#Department').append(department);
        }
    }
}

GetFilterCriteria();

function changeRequestType() {
    var typeOfRequest = $("#TypeOfRequest").val();
    var absenceType = $("#AbsenceType").val();
    var obligationType = $("#ObligationType").val();
    var requestType = $("#RequestType").val();
    var absencePlaceholder = $("#AbsencePlaceholder").val();
    var obligationPlaceholder = $("#ObligationPlaceholder").val();
    var otherPlaceholder = $("#OtherPlaceholder").val();
    var dynamicLabel = $("#dynamic-label");
    var dynamicPlaceholder = $("#select2-DynamicTypeDropdown-container");
    var absences = $("#Absences").val();
    var obligations = $("#Obligations").val();
    var other = $("#Other").val();

    $("#DynamicTypeDropdown").val("").trigger("change");
    $("#RequestTypeNumber").val(typeOfRequest);

    if (typeOfRequest === absences) {
        dynamicLabel.text(absenceType);
        dynamicPlaceholder.children(".select2-selection__placeholder").text(absencePlaceholder);
        setDatePicker();
    }
    if (typeOfRequest === obligations) {
        dynamicLabel.text(obligationType);
        dynamicPlaceholder.children(".select2-selection__placeholder").text(obligationPlaceholder);
        setDateTimePicker();
    }
    if (typeOfRequest === other) {
        dynamicLabel.text(requestType);
        dynamicPlaceholder.children(".select2-selection__placeholder").text(otherPlaceholder);
        setDateTimePicker();
    }
}

function setDatePicker() {
    if ($("#dateBegin-dtp").hasClass("custom-datetimepicker")) {
        $("#dateBegin-dp").removeClass("hidden").attr("name", "DateTimeFrom");
        $("#dateEnd-dp").removeClass("hidden").attr("name", "DateTimeTo");
        $("#dateBegin-dtp, #dateEnd-dtp").addClass("hidden").removeAttr("name");
    }
}

function setDateTimePicker() {
    if ($("#dateBegin-dp").hasClass("custom-datepicker")) {
        $("#dateBegin-dp, #dateEnd-dp").addClass("hidden").removeAttr("name");
        $("#dateBegin-dtp").removeClass("hidden").attr("name", "DateTimeFrom");
        $("#dateEnd-dtp").removeClass("hidden").attr("name", "DateTimeTo");
    }
}

function getNotificationNumbers() {
    var url = $('#NotificationNumbersUrl').val();

    $.ajax({
        type: "get",
        url: url,
        success: function (number) {
            var isActive = $('#Request-number').parent().parent().hasClass('active');

            if (isActive) {
                $('#Request-number').addClass('badge-primary');
            }
            $('#Request-number').append(number.InProgress);
        }
    });
}

function formatLeaderString() {
    var leader = $('#select2-Leader-container').text();

    leader = leader.split(", ")[1] + " " + leader.split(", ")[2];
    $('#select2-Leader-container').text(leader);
}

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

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

function exportTimeRecordsReport(action, isAttendaceReport) {

    $("#report-form").attr("action", action);

    if (isAttendaceReport === true) {
        $(".attendance-report-input").val(true);
        $("#report-form").submit();
    }
    else {
        $(".attendance-report-input").val(false);
        $("#report-form").submit();
    }
}

function openModal(id, absence = false) {
    $('#' + id).find('input[type="checkbox"]').customCheckbox();
    $('#' + id).modal('show');

    let modelWorker = $("#ModelWorker").val();
    let absenceHelpUrl = $("#AbsenceHelpUrl").val();
    let absenceHelpExampleUrl = $("#AbsenceHelpExampleUrl").val();
    let addOrDeleteAbsence = $("#AddOrDeleteAbsence").val();
    let absenceType = $("#AbsenceType").val();
    let absenceStart = $("#AbsenceStart").val();
    let absenceEnd = $("#AbsenceEnd").val();
    let obligationHelpUrl = $("#ObligationHelpUrl").val();
    let obligationHelpExampleUrl = $("#ObligationHelpExampleUrl").val();
    let addOrDeleteWorkCommitment = $("#AddOrDeleteWorkCommitment").val();
    let enterNewRecordUrl = $("#EnterNewRecordUrl").val();
    let enterNewAbsenceUrl = $("#EnterNewAbsenceUrl").val();
    let obligationType = $("#ObligationType").val();
    let obligationStart = $("#ObligationStart").val();
    let obligationEnd = $("#ObligationEnd").val();

    if (absence) {
        $("#Absence").val(true);
        $("#NewRecordForm").attr("action", enterNewAbsenceUrl);
        $("#Type").attr("filter-by", "AbsenceTypeNumber");
        $("#newrecord-help-url").attr("href", absenceHelpUrl);
        $("#newrecord-help-example-url").attr("href", absenceHelpExampleUrl);
        $("#newrecord-modal-title").text(addOrDeleteAbsence);
        $("#newrecord-modal-type").text(absenceType);
        $("#newrecord-modal-begin").text(absenceStart);
        $("#newrecord-modal-end").text(absenceEnd);
        $("#newrecord-modal-statuses").removeClass("hidden");

        if (id === 'newrecord-modal') {
            paw.view.workhours.newRecordModal.init('absence');
        }
    } else {
        $("#Absence").val(false);
        $("#NewRecordForm").attr("action", enterNewRecordUrl);
        $("#Type").attr("filter-by", "EntryTypeNumber");
        $("#newrecord-help-url").attr("href", obligationHelpUrl);
        $("#newrecord-help-example-url").attr("href", obligationHelpExampleUrl);
        $("#newrecord-modal-title").text(addOrDeleteWorkCommitment);
        $("#newrecord-modal-type").text(obligationType);
        $("#newrecord-modal-begin").text(obligationStart);
        $("#newrecord-modal-end").text(obligationEnd);
        $("#newrecord-modal-statuses").addClass("hidden");

        if (id === 'newrecord-modal') {
            paw.view.workhours.newRecordModal.init('workCommitment');
        }
        
    }

    if (lastOpenedModal != undefined && absence != lastOpenedModal) {
        refreshOpenedModal(modelWorker);
    }

    lastOpenedModal = absence; 
}

function swapLoadingIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("i");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
        $buttonGroupButtons.attr("disabled", true);
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
        $buttonGroupButtons.removeAttr("disabled");
    }
}

function refreshOpenedModal(modelWorker) {
    $("#NewRecordEmployee").val(modelWorker).change();
    $("#Type").val("").change();
    $("#DepartmentModal").val("").change();
    $("#CostDrvModal").val("").change();
    $("#Status").val("").change();
    $("#Note").val("");

    let currentDate = new Date();
    currentDate = moment(new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), 0, 0, 0, 0)).format("DD.MM.YYYY HH:mm");
    $("#NewRecordStartDate").val(currentDate);
    $("#NewRecordEndDate").val(currentDate);
}

function setSelectedLeadersList() {
    let preSelectedLeaders = $("#PreSelectedLeaders").val();
    if (preSelectedLeaders) {
        $("#Leader").selectpicker('val', preSelectedLeaders.split(","));
    }
}

function SetWorkerLeadersAndContact(worker) {
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetWorkerActiveLeadersUrl").val(),
        data: {
            worker: worker
        },
        success: function (data) {
            if (data != null && data.length > 0) {
                if ($("#HasTimeRecordsOwnDataOnly").val() === 'True') {
                    $("#LeaderSelect .filter-option-inner-inner").text(data[0]);
                }
                else {
                    $("#Leader").selectpicker('val', data);
                }
            }
            else {
                $("#Leader").selectpicker('val', '');
            }
        }
    });

    $.ajax({
        cache: false,
        type: "GET",
        url: $("#GetWorkerContactUrl").val(),
        data: {
            worker: worker
        },
        success: function (data) {
            $("#WorkerContact").val(data);
        }
    });
}

function workerHaveContact() {
    return !$("#WorkerContact").val() || $("#WorkerContact").val().length === 0 ? false : true;
}

function createCalendarRequest() {
    if (!validateFields()) return;
    if (!workerHaveContact()) {
        $("#new-request-modal-form .close").click()
        $('#time-record-iris').modal('show');
        return;
    } 

    swapLoadingIcon(true, "new-request-btn", "fa fa-check");
    $.ajax({
        url: $("#AddCalendarRequestUrl").val(),
        type: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: new FormData($("#new-request-modal-form")[0]),
        success: function (data) {
            const response = JSON.parse(data);
            if (response.Status === false) {
                swapLoadingIcon(false, "new-request-btn", "fa fa-check");
                showInvalidTimeMessage(response.Message);
                return;
            }

            const workflowResponse = response.WorkflowResponse;
            const newIds = response.ApprovalQIds;
            const wfId = response.IsWFAbsenceExist;

            if (workflowResponse.error) {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: workflowResponse.error,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: $("#Confirm").val(),
                            closeOnAction: true,
                            type: 'primary',
                        }
                    ]
                });
                swapLoadingIcon(false, "new-request-btn", "fa fa-check");
            } else {
                if (workflowResponse.i && workflowResponse.i.length > 0) {
                    showCalendarRequestResponse(workflowResponse.i[0], newIds, wfId);
                }
                else if (workflowResponse.w && workflowResponse.w.length > 0) {
                    showCalendarRequestResponse(workflowResponse.w[0], newIds, wfId)
                }
                else {
                    window.location = $("#TimeRecordRequestsUrl").val() + "?newIds=" + encodeURIComponent(JSON.stringify(newIds)) + "&wfId=" + wfId;
                }
            }
        }
    });
}

function showCalendarRequestResponse(message, newIds, wfId) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: message,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#Confirm").val(),
                closeOnAction: true,
                type: 'primary',
                action: function () {
                    window.location = $("#TimeRecordRequestsUrl").val() + "?newIds=" + encodeURIComponent(JSON.stringify(newIds)) + "&wfId=" + wfId;
                }
            }
        ]
    });
}

function validateFields() {
    var leader = $("#Leader").val();
    var typeOfRequest = $("#TypeOfRequest").val();
    var dynamicTypeDropdown = $("#DynamicTypeDropdown").val();
    var dateBegin = $("#dateBegin-dp").val();
    var dateEnd = $("#dateEnd-dp").val();

    $('#LeaderValidation, #RequestValidation, #AbsenceValidation, #DateBeginValidation, #DateEndValidation').addClass('hidden');

    if (leader.length === 0 || !typeOfRequest || !dynamicTypeDropdown || !dateBegin || !dateEnd) {
        if (leader.length === 0) {
            $("#LeaderValidation").removeClass('hidden');
        }
        if (!typeOfRequest) {
            $("#RequestValidation").removeClass('hidden');
        }
        if (!dynamicTypeDropdown) {
            $("#AbsenceValidation").removeClass('hidden');
        }
        if (!dateBegin) {
            $("#DateBeginValidation").removeClass('hidden');
        }
        if (!dateEnd) {
            $("#DateEndValidation").removeClass('hidden');
        }
        return false;
    }
    return true;
}

function validateRequiredRecordFields(type, workers, dateStart, dateEnd) {
    let isValid = true;
    $("#type-validation, #worker-validation, #timestart-validation, #timeend-validation").addClass('hidden');

    if (!type) {
        $("#type-validation").removeClass('hidden');
        isValid = false;
    }
    if (!workers.length) {
        $("#worker-validation").removeClass('hidden');
        isValid = false;
    }
    if (!dateStart) {
        $("#timestart-validation").removeClass('hidden');
        isValid = false;
    }
    if (!dateEnd) {
        $("#timeend-validation").removeClass('hidden');
        isValid = false;
    }

    return isValid;
}