$(document).ready(function () {
    enablePartialView("RecordsID");
    setInProgress();
    applyJsSwitch();
    setWorkFromHomeButtonState();
    GetWorkFromHomeState();
    setNoteLengthForSmallerDevices();
    openIrisModal();
    sortEntryTypeButtons();
    listenForAddedTimeRecordsToDOM();   
    timeRecordForWorkerFromTimeAttendence();
    getAbsenceTaskVariables();
    openWorkPlanIrisModal();

    if ($("#isLicenseCM").val() === "True") {
        setGlobalHelpUrl($("#WorkRecordsLicenseCMHelpUrl").val());

        if ($("#Worker").val()) {
            checkAndOpenEmployeeEntryDateIRIS($("#Worker").val());
        }
    }

    mapPermissionsHelperValues();
    handleTimeRecordsPermissions();
});

$('.plannedInput').on('click', function (e) {
    e.preventDefault();
});

var urlString = window.location.href;
var url = new URL(urlString);
var timeRecordsPermissions = {
    CurrentWorkerCode: null,
    TimeRecordsEntryUpdateOwn: false,
    TimeRecordsEntryUpdateOther: false,
    WorkRosterGranule: false
};

function timeRecordForWorkerFromTimeAttendence() {
    let worker = decodeURI(url.searchParams.get("Workers"));

    if (worker !== "null") {
        let workerName = decodeURI(url.searchParams.get("WorkerFromAttendence"));
        let dateStart = decodeURI(url.searchParams.get("DateStart"));
        let dateEnd = decodeURI(url.searchParams.get("DateEnd"));

        $("#Filter_DateFrom").val(fromISOToStandardDateFormatString(dateStart));
        $("#Filter_DateTo").val(fromISOToStandardDateFormatString(dateEnd));
        $("#select2-Worker-container").attr("title", workerName);
        $("#select2-Worker-container").text(workerName);
        $("#Worker").append(new Option(workerName, worker));
        $("#Worker").children(":first").removeAttr("selected");
        $("#Worker").children(":last").attr("selected", "selected");
    }
}

function checkAndOpenEmployeeEntryDateIRIS(workerId) {
    $.ajax({
        type: "GET",
        url: $("#CheckEmployeeHasRecordUrl").val(),
        data: {
            acWorker: workerId
        },
        success: function (hasRecord) {
            if (hasRecord === "False") {
                openEmployeeEntryDateIRIS(workerId);
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

function openEmployeeEntryDateIRIS(workerId) {
    $('#iris-header').text($('#EmployeeMissingEntryDateTitle').val());
    $('#iris-message').text($('#EmployeeMissingEntryDateDescription').val());
    $('#option-1-header').text($('#EnterEntryDate').val());
    $('#option-1-text').text($('#EnterEntryDateDescription').val());
    $('#option-3-header').text($('#PoIrisHelp').val());
    $('#option-3-text').text($('#ViewInstructionsDescription').val());
    $('#option-2-clickable').hide()

    $('#option-1-clickable').click(function () {
        window.open($('#EditEmployeeUrl').val() + '?id=' + workerId + '&focusDateOfEntry=true', '_blank');
    });

    $('#option-3-clickable').click(function () {
        window.open($('#DateOfEntryHelpUrl').val(), '_blank')
    });

    $('#blank-iris').modal('show');
}

//#region BUTTONS SCROLL

//Show/hide arrows
$('.timerecord-col').hover(
    function () {
        $(".panner").addClass('nontransparent-arrow');
    },
    function () {
        $(".panner").removeClass('nontransparent-arrow');
    }
);

if (document.documentElement.clientWidth <= 768) {
    //Mobile & tablet
    $(".panner").on("touchstart", startScrollingHelper);

    $(".panner").on("touchend", stopScrollingHelper);
} else {
    //Laptop & PC
    $(".panner").on("mouseenter", startScrollingHelper);
    
    $(".panner").on("mouseleave", stopScrollingHelper);
}

function startScrollingHelper() {
    var data = $(this).data('scrollModifier');
    var direction = parseInt(data);
    $(this).addClass('active');
    startScrolling(direction);
}

function stopScrollingHelper() {
    stopScrolling();
    $(this).removeClass('active');
}

var scrollHandle = 0;

//Actual handling of the scrolling
function startScrolling(direction) {
    var parent = $("#timerecord-col");
    var scrollStep = 5;

    if (scrollHandle === 0) {
        scrollHandle = setInterval(function () {
            var newOffset = parent.scrollLeft() + (scrollStep * direction);
            parent.scrollLeft(newOffset);
        }, 10);
    }
}

function stopScrolling() {
    clearInterval(scrollHandle);
    scrollHandle = 0;
}
//#endregion BUTTONS SCROLL

//region FILTERS
function showFilter() {
    var mobile = isMobile();
    var tablet = isTablet();
    $(".filter-row").toggleClass("hidden");
    $("#RecordsID").toggleClass("records-height");

    if (mobile) {
        $(".filter-row").toggleClass("enable-filters-scroll");
    }

    if (mobile || tablet) {
        $("#WholesaleFilter").parent().addClass("align-arrow");
    }
}

var timeRecordsSearchDebounced = debouncer(function () {
    $('#submit-filter-form').submit();
    fillExportForm();
}, 400);

function submitFilterForm(id = "", isFilter = false, element = '') {
    if (element && !element.hasClass("date-changed")) return;

    let filterDateFrom = decodeURI(url.searchParams.get("FilterDateFrom"));
    let filterDateTo = decodeURI(url.searchParams.get("FilterDateTo"));

    if (filterDateFrom === "True" || filterDateTo === "True") {
        if (id === "Filter_DateFrom" && filterDateFrom === "True") {
            disableFilter("FilterDateFrom");
            return;
        } else if (id === "Filter_DateTo" && filterDateTo === "True") {
            disableFilter("FilterDateTo");
            return;
        } else {
            if (isFilter) {
                startLoading("RecordsID");
            }

            timeRecordsSearchDebounced();
            return;
        }
    } else {
        if (isFilter) 
            startLoading("RecordsID");

        if (element) 
            element.removeClass("date-changed")

        timeRecordsSearchDebounced();
    }
}

function disableFilter(paramId) {
    var search_params = url.searchParams;
    search_params.set(paramId, "False");
    url.search = search_params.toString();
}

$(".selectpicker-dropdown").on("hide.bs.dropdown", function () {
    submitFilterForm("", true);
});
//#endregion FILTERS

var previousClicked;
var resetStopwatch = false;
var recordingData = {};
function startRecording(canUpdate, num, setOf, overlapCheck = true) {
    if (!canUpdate) {
        return;
    }

    let currentBtnId = 'record-button-' + num
    var currentBtn = $('#record-button-' + num);
    var color = $(currentBtn).data("color");
    var icon = $(currentBtn).data("icon");

    $('#stop-records').removeClass('stop-recordings');

    if (num !== previousClicked) {
        if ($('.entry-type-button').hasClass('pressed')) {
            $('.pressed').removeClass('pressed')
                .css("border-bottom", "");
        }

        $(currentBtn).addClass('pressed')
            .css("border-bottom", "4px solid " + color);

        if (previousClicked)
            resetStopwatch = true;

        swapLoadingIcon(true, currentBtnId, icon);

        recordingData = { setOf, resetStopwatch, color, icon, currentBtnId, num };

        if (overlapCheck) {
            overlapCheckStopwatch();
        }
    }
}

function overlapCheckStopwatch() {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: $("#OverlapCheckStopwatch").val(),
        data: {},
        success: function (data) {
            const tableBody = $("#ovelaping-commitment tbody");
            tableBody.empty();

            if (!data || data.length == 0) {
                addNewRecord(recordingData.setOf, recordingData.resetStopwatch, recordingData.color, recordingData.icon, recordingData.currentBtnId);
            } else {
                $.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);
                });

                $("#overlap-overwrite").attr("onclick", "overwriteNewRecordCall();");
                $("#overlap-complete").attr("onclick", "addNewRecordCall();");
                $("#ovelaping-commitment").modal("show");
            }
        }
    });
}

function addNewRecordCall() {
    addNewRecord(recordingData.setOf, recordingData.resetStopwatch, recordingData.color, recordingData.icon, recordingData.currentBtnId);
}

function overwriteNewRecordCall() {
    addNewRecord(recordingData.setOf, recordingData.resetStopwatch, recordingData.color, recordingData.icon, recordingData.currentBtnId, true);
}

function addNewRecord(setOf, resetStopwatch, color, icon, currentBtnId, isOverwrite = false) {
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: $('#NewRecordUrl').val(),
        data: { setOf, isOverwrite },
        success: function (data) {
            submitFilterForm();
            startStopwatch(resetStopwatch);
            colorStopwatch(color, icon);
            swapLoadingIcon(false, currentBtnId, icon);
        },
        error: function (error) {
            swapLoadingIcon(false, currentBtnId, icon);
        },
        complete: function () {
            $('#ovelaping-commitment').modal('hide');
            previousClicked = recordingData.num; 
            recordingData = {};
        }
    });
}

function startStopwatch(resetStopwatch) {
    $("#stopwatch").removeClass("hidden");
    $("#stopwatch-progress").addClass("hidden");

    if (resetStopwatch === true) {
        $("#stopwatch").stopwatch('reset');
    }
    else {
        $('#stopwatch').stopwatch().stopwatch('start');
    }
}

//#region MODALS
var selectedNoteNo = '';
function openNoteModal(anQId) {
    selectedNoteNo = anQId;
    $("#item-note").val($("#NoteId-" + anQId).val());
    $('#note-modal').modal('show');
}

var selectedNewRowNoteNo = '';

function saveNote() {
    var isNewRow = $('#note-modal').data('new-row');

    var noteValue = $("#item-note").val();

    if (isNewRow) {
        $("#NewRowNoteId-" + selectedNewRowNoteNo).val(noteValue);
        $("#note-new-row-span-" + selectedNewRowNoteNo).empty();
        $("#note-new-row-span-" + selectedNewRowNoteNo).html(noteValue);
    }
    else {
        $("#NoteId-" + selectedNoteNo).val(noteValue);
        $("#note-span-" + selectedNoteNo).empty();
        $("#note-span-" + selectedNoteNo).html(noteValue);
        $("#NoteId-" + selectedNoteNo).trigger('change');
    }
}
//#endregion MODALS

function setInProgress() {

    var isBtnStarted = $(".set-in-progress");

    if (isBtnStarted.length > 0) {
        var button = $(".set-in-progress")[0];
        var color = $(button).data('color');
        var ms = $(button).data('milliseconds');

        $(button).addClass('pressed')
            .css("border-bottom", "4px solid " + color);

        countUpFromStopwatch(ms);

    } else {
        $("#stopwatch-progress").addClass("hidden");
        $("#stopwatch").removeClass("hidden");
    }
}

function countUpFromStopwatch(milliseconds) {
    $('#stopwatch-progress').stopwatch({ startTime: milliseconds }).stopwatch('start');
}

function colorStopwatch(color, icon) {
    $("#main-icon").empty();
    $("#main-icon").append("<i class='" + icon + "' style=color:" + color + "></i>");

    $("#stopwatch-div").css("color", color);
}

function stopTimeRecordings() {
    if ($('.entry-type-button').hasClass('pressed')) {
        $('.pressed').removeClass('pressed')
            .css("border-bottom", "");
    }

    $('#stop-records').addClass('stop-recordings');

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: $('#StopRecordUrl').val(),
        success: function (data) {
            location.reload();
        }
    });
}

function editRecord(anQId, dropdownName = null, container = null) {
    var timeStart = $("#TimeStartId-" + anQId).val();
    var timeEnd = $("#TimeEndId-" + anQId).val();
    var confirmText = $("#Confirm").val();
    var timeStartGreaterThanTimeEnd = $("#TimeStartGreaterThanTimeEnd").val();

    if (timeEnd.length > 0 && timeStart > timeEnd) {
        return $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: timeStartGreaterThanTimeEnd,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
    var isOpenRecord = $("#IsOpenRecord-" + anQId).val();

    if (dropdownName == 'TypeId') {
        setTypeIcon(anQId, dropdownName);
    }

    swapElementLoadingIcon(container, true);
    disablePartialView("RecordsID");

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: $('#EditRecordUrl').val(),
        data: {
            AnQId: anQId,
            Type: $("#TypeId-" + anQId).val(),
            Department: $("#DepartmentId-" + anQId).val(),
            TimeStart: timeStart,
            TimeEnd: timeEnd,
            DateStart: $("#DateStart-" + anQId).val(),
            DateEnd: $("#DateEnd-" + anQId).val(),
            Note: $("#NoteId-" + anQId).val(),
            CostDrv: $("#CostDrvId-" + anQId).val()
        },
        success: function (data) {
            $("#time-record-to-focus").val(anQId);

            if (isOpenRecord === "True") {
                closeDropdownAfterClear(dropdownName, anQId);
                location.reload();
            }
            else {
                closeDropdownAfterClear(dropdownName, anQId);
                submitFilterForm();
            }
        },
        error: function (error) {
            swapElementLoadingIcon(container, false);
        }
    });
}

function swapElementLoadingIcon(element, show, deleteOrDuplicate = false) {
    if (element != null) {
        let elementParent = $("#" + element).parent();
        let loadingIcon = elementParent.find("i").last(); 

        if (show) {
            if (deleteOrDuplicate) {
                elementParent = $("." + element).parent();
                elementParent.each(function () {
                    $(this).children("i").first().addClass("hidden");
                    $(this).children("i").last().removeClass("hidden");
                });
            } else {
                elementParent.children().addClass("hidden");
                elementParent.addClass("text-center");
                loadingIcon.removeClass("hidden");
            }
        } else {
            if (deleteOrDuplicate) {
                elementParent = $("." + element).parent();
                elementParent.each(function () {
                    $(this).children("i").first().removeclass("hidden");
                    $(this).children("i").last().addclass("hidden");
                });
            } else {
                elementParent.children().removeClass("hidden");
                elementParent.removeClass("text-center");
                loadingIcon.addClass("hidden");
            }
        }
    }
}

function listenForAddedTimeRecordsToDOM() {
    let insertListener = function (event) {
        if (event.animationName == "nodeInserted") {
            focusTimeRecordRow();
        }
    }
    document.addEventListener("animationstart", insertListener, false);
}

function focusTimeRecordRow() {
    let id = $("#time-record-to-focus").val();
    let timeRecordToFocus = $("#DateStart-" + id).parent("tbody").parent("table");

    if (timeRecordToFocus.length) {
        timeRecordToFocus[0].scrollIntoView();
    };
}

function setTypeIcon(anQId, dropdownName) {
    $("#Icon-" + anQId).find("i").remove();
    $("#Icon-" + anQId).append($("#select2-" + dropdownName + "-" + anQId + "-container").find("i"));
    $("#select2-" + dropdownName + "-" + anQId + "-container").find("i").remove();
}

function hoverRow() {
    $('.time-record-row').hover(
        function () {
            $(this).find('.time-record-hidden-icon').addClass('default-icon-color');

            if ($(this).find('.time-record-hidden-icon').hasClass('has-note')) {
                $(this).find('.has-note').removeClass('default-icon-color').addClass('theme-button-color');
            }
        },

        function () {
            $(this).find('.time-record-hidden-icon').removeClass('default-icon-color theme-button-color');
        }
    );
}

hoverRow();

function hoverSaldoAndTotal() {
    if (window.innerWidth > 768) {
        hoverRecordSaldoAndTotalLeaveDays("saldo-dropdown-button", "saldo-button");
        hoverRecordSaldoAndTotalLeaveDays("leave-days-dropdown-button", "leave-days-button");
    }
}

function hoverRecordSaldoAndTotalLeaveDays(dropdownButton, button) {
    $('.' + dropdownButton).hover(
        function () {
            $(this).find('#' + button).click();
            $(this).siblings().find('#' + button).click();
        },

        function () {
            $(this).find('#' + button).click();
            $(this).siblings().find('#' + button).click();
        }
    );
}

hoverSaldoAndTotal();

function fillExportForm() {

    $(".obligation-input").remove();
    $(".department-input").remove();

    var worker = $("#Worker").val();
    var obligations = $("#WorkObligations").val();
    var departments = $("#Department").val();
    var dateFrom = $("#Filter_DateFrom").val();
    var dateTo = $("#Filter_DateTo").val();

    if ($("#isLicenseCM").val() === "True") {
        checkAndOpenEmployeeEntryDateIRIS(worker);
    }

    $("#pdf-worker").val(worker);
    $("#pdf-datestart").val(dateFrom);
    $("#pdf-dateend").val(dateTo);

    if (obligations) {
        for (var i = 0; i < obligations.length; i++) {
            $("#report-form").append("<input class='obligation-input' name='WorkObligations[" + i + "]' value='" + obligations[i] + "' />");
        }
    }

    if (departments) {
        for (var i = 0; i < departments.length; i++) {
            $("#report-form").append("<input class='department-input' name='Departments[" + i + "]' value='" + departments[i] + "' />");
        }
    }
}

//#region SHOW/HIDE TIMERECORDS
function collapseSingleRecord(index, isPlannedHours = false) {
    var smallDevice = isMobile() || isTablet();
    var open = false;
    var plannedHeight = $("#planned-hours-td-" + index).length > 0 ? $("#planned-hours-td-" + index)[0].offsetHeight : 0;
    
    if (isPlannedHours) {
        if ($('#planned-hours-td-' + index).hasClass('hide-table')) {
            $('#planned-hours-td-' + index).removeClass('hide-table');
            $('#planned-hours-td-' + index).addClass('show-table');
            $('#planned-hours-th-' + index).removeClass('collapsed');
            plannedHeight = $("#planned-hours-td-" + index)[0].offsetHeight;
            open = true;
        } else {
            $('#planned-hours-td-' + index).addClass('hide-table');
            $('#planned-hours-td-' + index).removeClass('show-table');
            $('#planned-hours-th-' + index).addClass('collapsed');
        }
    } else {
        if ($('#timerecord-tb-' + index).hasClass('hide-table')) {
            $('#timerecord-tb-' + index).removeClass('hide-table');
            $('#timerecord-tb-' + index).addClass('show-table');
            $('#timerecord-th-' + index).removeClass('collapsed');
        } else {
            $('#timerecord-tb-' + index).addClass('hide-table');
            $('#timerecord-tb-' + index).removeClass('show-table');
            $('#timerecord-th-' + index).addClass('collapsed');
        }
    }

    if (smallDevice && open) {
        var height = $('#timerecord-tb-' + index)[0].offsetHeight + plannedHeight + 25;
        $('#timerecord-tb-' + index).closest("table").css("height", height + "px")
    }
    else if (smallDevice && !open) {
        var height = $('#timerecord-tb-' + index)[0].offsetHeight - plannedHeight - 25;
        $('#timerecord-tb-' + index).closest("table").css("height", height + "px")
    }
}

function collapseAllRecords() {
    if ($("#collapse-all-records").hasClass("collapsed")) {
        $("#collapse-close").show();
        $("#collapse-open").hide();
        $("#collapse-all-records").removeClass('collapsed');
        $('.timerecord-tb').removeClass('hide-table');
        $('.timerecord-tb').addClass('show-table');
    }
    else {
        $("#collapse-all-records").addClass('collapsed');
        $("#collapse-close").hide();
        $("#collapse-open").show();
        $('.timerecord-th').addClass('collapsed');
        $('.timerecord-tb').addClass('hide-table');
    }
}
//#endregion

$("#sortable-body").sortable({
    cursor: "move",
    placeholder: "sortable-placeholder",
    helper: function (e, tr) {
        var $originals = tr.children();
        var $helper = tr.clone();
        $helper.children().each(function (index) {
            $(this).width($originals.eq(index).width());
            $(this).addClass("sortable-color");
        });
        return $helper;
    }
}).disableSelection();

function saveEntryTypeOrder() {
    var data = new Array();
    $('.sortable-row').each(function () {
        var id = $(this).data("id");
        var show = $("#show-type-checkbox-" + id).is(":checked");
        data.push({ Id: id, Show: show });
    });

    $.ajax({
        data: { buttons: data },
        type: 'POST',
        url: $("#SaveOrderUrl").val(),
        success: function (result) {
            if (result.Status === true) {
                location.reload();
            }
        }
    });
}

function applyJsSwitch() {
    var elems = Array.prototype.slice.call(document.querySelectorAll('.timeRecordsSwitch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });
}

function SetWorkFromHome() {
    var isFromHome = $("#work-from-home").is(":checked");

    localStorage.setItem('TrWorkFromHome', isFromHome);

    GetWorkFromHomeState();
    sortEntryTypeButtons();
}

function GetWorkFromHomeState() {
    var workFromHomeKey = localStorage.getItem('TrWorkFromHome');
    $('.check-work-place').each(function () {
        var isFromHome = $(this).data("work-home").toString();

        if (workFromHomeKey && workFromHomeKey.toString() === 'true' && isFromHome === 'False') {
            $(this).addClass("hidden");
        }
        else {
            $(this).removeClass("hidden");
        }
    });
}

function setWorkFromHomeButtonState() {
    var workFromHomeKey = localStorage.getItem('TrWorkFromHome');
    if (workFromHomeKey && workFromHomeKey.toString() === "true")
        $("#work-from-home").prop('checked', true);
}

function sortEntryTypeButtons() {
    let timerecordCol = $("#timerecord-col");
    let timerecordButtons = $("#timerecord-buttons");

    if (timerecordCol.width() > timerecordButtons.width()) {
        timerecordButtons.addClass("work-from-home");
    }
    else {
        timerecordButtons.removeClass("work-from-home");
    }
}

$(document).on('click', '.show-hide-column', function (e) {
    e.stopPropagation();
});

function showHideContent(columnName) {
    var isVisible = $("#" + columnName + "-Id").is(":checked");
    var columns = [];

    $(".show-hide-column > li > label > input").each(function () {
        var isHidden = !$(this).is(":checked");
        var columnId = $(this).attr("id");
        columnId = columnId.slice(0, -3);

        var column = {
            Id: columnId,
            IsHidden: isHidden
        };
        columns.push(column);
    });

    $.ajax({
        data:
        {
            TableName: "TimeRecordsGrid",
            Columns: columns
        },
        type: 'POST',
        url: $("#SetGridSettingsUrl").val(),
        success: function (result) {
            if (result.Status === true) {
                var colToHide = $(".time-record-table").find("." + columnName);

                if (isVisible) {
                    colToHide.removeClass("hidden");
                    if (columnName === 'AcPlannedHours') {
                        $('.time-record-table').addClass('not-future-plan');
                        $(".AcPlannedHours").each(function () {
                            if ($(this).siblings().size() == 0) {
                                $(this).closest("table").removeClass("hidden");
                            }
                        });
                    }

                    if (isMobile()) 
                        colToHide.closest("td").removeClass("hidden");

                } else {
                    colToHide.addClass("hidden");
                    if (columnName === 'AcPlannedHours') {
                        $('.time-record-table').removeClass('not-future-plan');
                        $(".AcPlannedHours").each(function () {
                            if ($(this).siblings().size() == 0) {
                                $(this).closest("table").addClass("hidden");
                            }
                        });
                    }

                    if (isMobile())
                        colToHide.closest("td").addClass("hidden");
                }
            }
        }
    });
}

function openIrisModal() {
    var worker = $("#WorkerIRIS").val();
    if (!worker || worker.length === 0) {
        $('#time-record-iris').modal('show');
    }
}

function openWorkPlanIrisModal() {
    $.ajax({
        type: "GET",
        dataType: 'json',
        url: $('#GetWorkPlansUrl').val(),
        success: function (data) {
            if (!data) {
                $('#time-record-work-plan-iris').modal('show');
            }
        }
    });
}

function redirectToSetWorkHours() {
    window.location.href = "/SetWorkHours?id=2&openSettings";
}

function setNoteLengthForSmallerDevices() {
    var stringLength = 20;

    if (window.innerWidth <= 768) {
        stringLength = 10;
    }

    for (var i = 0; i < $(".timerecord-note").length; i++) {
        var note = $(".timerecord-note")[i].innerText;
        note = note.trim();
        if (note.length > stringLength) {
            $(".timerecord-note")[i].innerText = note.length > stringLength ? note.substring(0, stringLength) + "..." : note;
        }
    }
}

function closeDropdownAfterClear(dropdownName, id) {
    if (dropdownName == null)
        return;

    $("#" + dropdownName + "-" + id).select2("close");
}

//#region Populate absence modal with task variables
function getAbsenceTaskVariables() {
    var WFInstanceKey = url.searchParams.get("WFInstanceKey");
    if (WFInstanceKey) {
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: $('#GetAbsenceTaskVariables').val(),
            data: { workflowInstanceKey: WFInstanceKey },
            success: function (data) {
                openAndPopulateAbsenceForm(data);
            }
        });
    }
}

function openAndPopulateAbsenceForm(data) {
    let calEntryType = data.CalendarEntryType[0];
    let worker = data.Variables.Worker;
    let startDateTimeParts = data.Variables.AbsenceFrom.split(" ");
    let startDate = startDateTimeParts[0];
    let endDateTimeParts = data.Variables.AbsenceTo.split(" ");
    let endDate = endDateTimeParts[0];

    if (startDate.length < 8) {
        startDate = startDateTimeParts[0] + startDateTimeParts[1] + startDateTimeParts[2];
        endDate = endDateTimeParts[0] + endDateTimeParts[1] + endDateTimeParts[2];
    }

    openModal('newrecord-modal', true);
    $("#NewRecordEmployee").val(worker).selectpicker("refresh");
    $("#Type option").attr("value", calEntryType.SetOf).text(`"${calEntryType.Name}"`);
    $("#select2-Type-container .select2-selection__placeholder").remove();
    $("#select2-Type-container").attr("title", `"${calEntryType.Name}"`).append(`${calEntryType.Name}`);
    $("#NewRecordStartDate").val(startDate);
    $("#NewRecordEndDate").val(endDate);

    makeFormElementsDisabled();
}

function makeFormElementsDisabled() {
    $("button[data-id='NewRecordEmployee']").addClass("from-WF-task-disabled");
    $("#NewRecordForm select, #NewRecordForm input:not(.not-disabled), #NewRecordForm .input-group-addon, #NewRecordForm button:not(#newrecord-modal-add)").each(function () {
        $(this).addClass("from-WF-task-disabled");
    })

    $(".from-WF-task-disabled").each(function () {
        $(this).attr("disabled", true);
    });
}
//#endregion Populate absence modal from task variables

function enablePartialView(id) {
    $("#" + id).removeClass("disable-partial-view");
}

function disablePartialView(id) {
    $("#" + id).addClass("disable-partial-view");
}

function recordActionAndReload(anQid, element, url) {
    swapElementLoadingIcon(element, true, true)

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: url,
        data: { anQid: anQid },
        success: function (data) {
            hoverRow();
            hoverSaldoAndTotal();
            showTooltip();
            submitFilterForm();
            select2withAPI();
        },
        error: function (error) {
            swapElementLoadingIcon(element, false, true)
        }
    });
}

function mapPermissionsHelperValues() {
    timeRecordsPermissions.CurrentWorkerCode = $('#CurrentWorkerCode').val();
    timeRecordsPermissions.TimeRecordsEntryUpdateOwn = paw.utils.value.strToBool($('#TimeRecordsEntryUpdateOwn').val());
    timeRecordsPermissions.TimeRecordsEntryUpdateOther = paw.utils.value.strToBool($('#TimeRecordsEntryUpdateOther').val());
    timeRecordsPermissions.WorkRosterGranule = paw.utils.value.strToBool($('#WorkRosterGranule').val());
}

function handleTimeRecordsPermissions() {
    var workerCode = $("#Worker").val();
    var canEdit = workerCode === timeRecordsPermissions.CurrentWorkerCode || timeRecordsPermissions.WorkRosterGranule ? timeRecordsPermissions.TimeRecordsEntryUpdateOwn : timeRecordsPermissions.TimeRecordsEntryUpdateOther;
    var $timeEntryButtons = $('.timerecord-buttons button');
    var $stopRecording = $('#stop-records');
    if (canEdit) {
        $timeEntryButtons.attr('disabled', false);
        $stopRecording.removeClass('hidden');
    }
    else {
        $timeEntryButtons.attr('disabled', true);
        $stopRecording.addClass('hidden');
    }
}