var dailyCalendar = $("#DailyCalendarType").val();
var weeklyCalendar = $("#WeeklyCalendarType").val();
var monthlyCalendar = $("#MonthlyCalendarType").val();
var calendarBy = "#CalendarDisplay";
var calendarByEmployees = $("#CalendarByEmployees").val();
var calendarByTools = $("#CalendarByTools").val();
var daily = "daily-calendar-body";
var dailyTools = "daily-calendar-body-tools";
var weekly = "weekly-calendar-body";
var weeklyTools = "weekly-calendar-body-tools";
var monthly = "monthly-calendar-body";
var monthlyTools = "monthly-calendar-body-tools";
var dailyTableId = "#daily-table";
var dailyTableToolsId = "#daily-table-tools";
var weeklyTableId = "#weekly-table";
var weeklyTableToolsId = "#weekly-table-tools";
var monthlyTableId = "#monthly-table";
var monthlyTableToolsId = "#monthly-table-tools";
var calendarTypeId = "#calendar-period";
var sidebarCalendar = "#proforma-invoice-calendar";
var dateFormat = "DD.MM.YYYY";
var compareByWorker = "worker";
var compareByTool = "fixedAsset"; 
var checkTimesForWorker = "worker";
var checkTimesForTool = "tool";
var minutesPerRow = 15;
var startWorkingHoursRow = 8;
var cellHeight = 35;
var cellHeightWM = 55;
var sidebarMonthHeight = 200;
var initCellWidth = 220;
var initMonthCellWidth = 100;
var redirectToCreateOrder = false;
var allWorkers = [];
var allFixedAssets = [];
var ordersGlobal;

$.ajax({
    method: "GET",
    url: $("#GetWorkersAndAssets").val(),
    success: function (response) {
        allWorkers = response.Workers
        allFixedAssets = response.FixedAssets
    }
})

function calendarInit() {
    let sidebarMonthsContainer = $(".tab-content").height() - $("#calendar").height();
    let initMonths = sidebarMonthsContainer / sidebarMonthHeight > 4 ? 4 : 3;

    //If Jquery UI gets updated, rename Datepicker method in script
    $(sidebarCalendar).datepickerJQ({
        numberOfMonths: [initMonths, 1],
        firstDay: 1,
        monthNames: [$("#January").val(), $("#February").val(), $("#March").val(), $("#April").val(), $("#May").val(), $("#June").val(), $("#July").val(), $("#August").val(), $("#September").val(), $("#October").val(), $("#November").val(), $("#December").val()],
        dayNamesMin: [$("#ShortSunday").val(), $("#ShortMonday").val(), $("#ShortTuesday").val(), $("#ShortWednesday").val(), $("#ShortThursday").val(), $("#ShortFriday").val(), $("#ShortSaturday").val()]
    });

    let calDocTypeFilter = $("#calendar-doc-head #DocumentTypes");
    calDocTypeFilter.val($("#main-doc-head #DocTypeSelect").val());

    if (!calDocTypeFilter.val()) {
        calDocTypeFilter.val(calDocTypeFilter.find("option:first").val());
    }

    $(".selectpicker").selectpicker("refresh");

    $(sidebarCalendar).datepickerJQ('option', {
        onSelect: function () {
            hideMainElements();
            showCalendarElements();
            displayCalendarTable();
        }
    });

    miniCalendarNavigation();
}

function getOrdersByDate() {
    let calType = $(calendarTypeId).val();
    let date = $(sidebarCalendar).val();
    let workers = [];
    let depts = [];
    let customers = [];
    let fixedAssets = [];
    let docType = [];
    editmode = true;
    editedItem = false;

    $(".cell-selected").removeClass("cell-selected");
    $(".inactive-link").each(function () {
        $(this).removeClass("inactive-link").click();
    });

    if ($("#DocumentTypes").val()) docType = $("#DocumentTypes").val();
    if ($("#Contractors").val()) workers = $("#Contractors").val();
    if ($("#Departments").val()) depts = $("#Departments").val();
    if ($("#Customers").val()) customers = $("#Customers").val();
    if ($("#FixedAssets").val()) fixedAssets = $("#FixedAssets").val();

    if ($(calendarBy).val() === calendarByTools && fixedAssets.length > 0) {
        filterDataTools(fixedAssets);
    } else if ($(calendarBy).val() === calendarByTools && fixedAssets.length == 0) {
        showAllTools();
    }

    let calendarRequest = {
        Date: date,
        CalendarType: calType,
        DocTypes: docType,
        Workers: workers,
        Departments: depts,
        Customers: customers,
        FixedAssets: fixedAssets
    };

    var d = paw.utils.async.defer();
    $.ajax({
        traditional: true,
        type: "GET",
        url: $("#GetOrdersByDateUrl").val(),
        async: true,
        data: calendarRequest,
        success: function (data) {
            let isTools = $(calendarBy).val() === calendarByTools;
            let activeWeek = $(".ui-state-active").closest("tr");
            let activeMonth = $(".ui-state-active").closest("tbody").children("tr");
            let dailyTableTypeId = isTools ? dailyTableToolsId : dailyTableId;
            let tableIdWM;

            clearTable();
            clearAllEventData(dailyTableTypeId)

            if (calType == weeklyCalendar) {
                setWeekDates(date, isTools);
                tableIdWM = isTools ? weeklyTableToolsId : weeklyTableId;
            } else if (calType == monthlyCalendar) {
                setMonthDates(date, isTools);
                tableIdWM = isTools ? monthlyTableToolsId : monthlyTableId;
            } 

            styleCurrentPeriod(activeWeek, activeMonth);
            
            setAbsences(data.Absences, isTools);
            setCalendarData(data.Orders, isTools, tableIdWM);

            if (calType == weeklyCalendar) {
                if (isTools) {
                    calendarDragAndDrop(weeklyTableToolsId, false, isTools);
                    initScroll(weeklyTableToolsId);
                } else {
                    calendarDragAndDrop(weeklyTableId, false, isTools);
                    initScroll(weeklyTableId);
                }
            } else if (calType == monthlyCalendar) {
                if (isTools) {
                    calendarDragAndDrop(monthlyTableToolsId, false, isTools);
                    initScroll(monthlyTableToolsId);
                } else {
                    calendarDragAndDrop(monthlyTableId, false, isTools);
                    initScroll(monthlyTableId);
                }
            } else {
                if (isTools) {
                    calendarDragAndDrop(dailyTableToolsId, true, isTools);
                    initScroll(dailyTableToolsId);
                } else {
                    calendarDragAndDrop(dailyTableId, true, isTools);
                    initScroll(dailyTableId);
                }

                setAllReservedFields(isTools);
            }

            initTooltipPosition(isTools, true);
            initResizable(isTools);
            checkOverlaping(isTools);
            showHideIcons(dailyTableTypeId);
            enableSelectable(dailyTableTypeId);
            updateDivsHeightWM(isTools);
            //openOrderFormWM();
            doubleClickItem();
            scrollLeftToFirstItem(dailyTableTypeId);
            $(dailyTableTypeId + ' [data-toggle="tooltip"]').tooltip({ trigger: "click" });
            closeTooltipOnClick();
            closeCreateTooltip();

            d.resolve();

            // delay execution because it makes UI sluggish
            setTimeout(function () {
                setWorkShifts(data.WorkShifts);
            });
        },
        error: function (error) {
            console.log(error);
            d.reject(error);
        }
    });
    return d.promise;
}

//#region CREATING RECEIPT FROM CALENDAR
function openReceiptCreateModal(acKey, anNo) {
    let tbodyRows; 
    let selectedOrder = ordersGlobal.filter(i => i.AcKey == acKey)[0];
    let itemsDeepCopy = selectedOrder.Items.slice(0);
    let docType = selectedOrder.DocType;
    $("#calendar-tooltip").closest(".tooltip").remove();

    $.ajax({
        method: "GET",
        url: $("#GetCalendarOrderSettingsByDocType").val(),
        data: { docType: "" },
        success: function (type) {
            $("#DocTypes").val(type);
        }
    }).done(function () {
        if (itemsDeepCopy.length > 1) {
            $("#createReceiptModal").modal("show");
            $("#createReceiptFor").append("<b>" + selectedOrder.ConsigneeId + "</b>");
            $("#AcKeyForReceipt").val(selectedOrder.AcKey);

            // If contractors filter is on, display tasks only for specific worker from column where calendar item is clicked
            if ($("#Contractors").val()) {
                let workerFromColumn = itemsDeepCopy.filter(i => i.AcKey == acKey && i.AnNo == anNo)[0].Worker;
                itemsDeepCopy = itemsDeepCopy.filter(i => i.Worker == workerFromColumn);
            }

            // Display connection number only for order items that have connection
            $.each(itemsDeepCopy, function (i, item) {
                var displayItem = true;
                if (selectedOrder.Connections) {
                    $.each(selectedOrder.Connections, function (index, conn) {
                        if (item.AcKey == conn.Aclnkkey && item.AnNo == conn.Anlnkno) {
                            displayItem = false;
                            return false;
                        }
                    })
                }

                if (displayItem) {
                    let row = `<tr>
                        <td>
                            <label class="custom-checkbox-container">
                                <input type="checkbox" id="checkbox-${item.AnNo}" onchange="setSelectedReceiptIdent(${item.AnNo})" class='modal-checkbox custom-checkbox' /> 
                                <span class="custom-checkbox-checkmark"></span>
                            </label>
                            <input hidden id="selected-${item.AnNo}" name="" value="F" class="selected-checkbox-value">
                        </td>
                        <td>${item.Name}</td>
                        <td><i class="fa fa-clock-o"></i> ${moment(selectedOrder.Date).format(dateFormat)} ${getTime(item.StartTime)}</td>
                        <td><i class="fa fa-clock-o"></i> ${moment(selectedOrder.DateValid).format(dateFormat)} ${getTime(item.EndTime)}</td>
                        <td>${item.Worker ? item.Worker : ""}</td>
                        <td>${item.FixedAssetName ? item.FixedAssetName : ""}</td>
                    </tr>`;
                    tbodyRows += row;
                }
            });

            $("#createReceiptModal table tbody").append(tbodyRows);
        } else {
            $("#DocumentAcKey").val(selectedOrder.AcKey);
            $("#createDocumentModal").modal("show");
        }
    });
}

var selectedReceiptIdents = [];
function setSelectedReceiptIdent(anNo) {
    var index = selectedReceiptIdents.findIndex(x => x === toNumber(anNo));

    if ($("#checkbox-" + anNo).is(":checked")) {
        $("#selected-" + anNo).attr("value", "T");
        selectedReceiptIdents.push(anNo);
    } else {
        $("#selected-" + anNo).attr("value", "F");
        if (index !== -1)
            selectedReceiptIdents.splice(index, 1);
    }
}

function createReceipt() {
    $("#createReceiptModal").modal("hide");
    $("#DocumentAcKey").val($("#AcKeyForReceipt").val());
    $("#createDocumentModal").modal("show");
}

$("#createReceiptModal").on("hide.bs.modal", function () {
    $("#createReceiptModal tbody").empty();
    $("#createReceiptModal #createReceiptFor").text($("#CreateReceiptForSubject").val() + " ");
});
//#endregion CREATING RECEIPT FROM CALENDAR


//#region FILLING CALENDAR WITH DATA
function setCalendarData(orders, isTools, tableIdWM) {
    let year = new Date().getFullYear();
    let cellWidth = $(tableIdWM + " tbody .collapse-items").first().parent().innerWidth();
    let lastDay = 1;
    let itemWidthCorrection = 8;
    ordersGlobal = orders;

    if (cellWidth == -1 && (tableIdWM == weeklyTableToolsId || tableIdWM == weeklyTableId)) {
        cellWidth = cellWidth == -1 ? initCellWidth : cellWidth;
    } else if (cellWidth == -1 && (tableIdWM == monthlyTableToolsId || tableIdWM == monthlyTableId)) {
        cellWidth = cellWidth == -1 ? initMonthCellWidth : cellWidth;
    }

    $.each(orders, function (i, order) {
        let currentWorker = null;
        let date = new Date(parseInt(order.Date.substr(6)));
        let dateValid = order.DateValid ? new Date(parseInt(order.DateValid.substr(6))) : "";

        // Order items loop
        $.each(order.Items, function (index, item) {
            let firstRow;
            let worker = "";
            let tool = "";
            let rangeClass = "";
            let startedBeforePeriodStyle = "";
            let connection = "";
            let draggable = true;
            let orderStartDay = moment(date).dayOfYear();
            let orderEndDay = moment(dateValid).dayOfYear();
            let durationDays = orderEndDay - orderStartDay;
            let dateStart = moment(date).format(dateFormat);
            let dateEnd = moment(dateValid).format(dateFormat);
            let startDay, endDay, startPeriodDate, endPeriodDate, dailyCell, weeklyCell, monthlyCell, itemWidth;

            if (item.Worker) worker = item.Worker.trim();
            if (item.FixedAsset) tool = item.FixedAsset.trim();

            if (worker || tool) {
                let itemStartTime;
                let itemEndTime;
                let prstTime = item.PrstTime;
                let rowSpan = 1;

                if (prstTime && prstTime != 0) {
                    rowSpan = roundDuration(item.PrstTime) / minutesPerRow;
                    rowSpan = rowSpan == 0 ? 1 : rowSpan;
                }

                firstRow = (currentWorker && currentWorker == worker) ? firstRow : startWorkingHoursRow;
                currentWorker = worker;

                if (item.StartTime) {
                    itemStartTime = roundTime(item.StartTime)
                }

                if (item.EndTime) {
                    itemEndTime = roundTime(item.EndTime)
                }

                if (order.Connections) {
                    $.each(order.Connections, function (index, conn) {
                        if (item.AcKey == conn.Aclnkkey && item.AnNo == conn.Anlnkno) {
                            connection = conn;
                            return false;
                        }
                    })
                }

                let itemTooltip = generateItemTooltip(item, order);
                let itemHeight = cellHeight * rowSpan;
                let receiptButtonColor = connection ? "lightslategray" : "inherit";

                if (itemStartTime) {
                    // Set daily calendar values 
                    if ($(calendarTypeId).val() === dailyCalendar) {
                        let receiptOnClick = connection ? "openConnectionFromCalendar(\"" + connection.Ackey + "\", \"" + connection.TypeOfDocument + "\")" : "openReceiptCreateModal(\"" + item.AcKey + "\", \"" + item.AnNo + "\")";
                        let tooltipSelectCheck = tool;
                        dailyCell = $(dailyTableId + " td[data-worker='" + worker + "'][data-time='" + itemStartTime + "']");

                        if (isTools) {
                            tooltipSelectCheck = worker;
                            dailyCell = $(dailyTableToolsId + " td[data-tool='" + tool + "'][data-time='" + itemStartTime + "']");
                        }

                         dailyCell
                             .append("<div class='calendar-events ' id='d-" + item.AcKey + "-" + item.AnNo + "' draggable='true' style='background: " + shade(item.ColorCode, shadeNum) + "; border-left-color: " + item.ColorCode + "; height: " + itemHeight + "px;' rel='tooltip' data-toggle='tooltip' data-html='true' data-placement='top' data-duration='" + rowSpan + "' data-startdate='" + dateStart + "' data-enddate='" + dateEnd + "' data-range='" + durationDays + "' data-title='" + itemTooltip + "'>" + 
                                        "<p class='cal-items-text'>" +
                                            "<span id='cal-items-ident'>" + item.Name + "</span>" +
                                            "<span id='cal-items-icons' class='cal-items-icons hidden'>" +
                                                "<a id='cal-edit-button' onclick='editItem(\"" + item.AcKey + "\", " + item.AnNo + ", \"" + order.ConsigneeId + "\", \"" + order.DocType + "\")' class='a-outline'>" +
                                                    "<i title='" + $("#LocChange").val() + "' class='fas fa-pencil-alt'></i>" +
                                                "</a>" +
                                                "<a onclick='deleteItem(\"" + item.AcKey + "\", " + item.AnNo + ")' class='a-outline m-r-sm'>" +
                                                    "<i title='" + $("#LocDelete").val() + "' class='far fa-trash-alt'></i>" +
                                                "</a>" +
                                                "<a onclick='redirectToOrder(\"" + item.AcKey + "\")' id='redirectToOrder' class='a-outline'>" + 
                                                    "<i title='" + $("#OpenOrder").val() + "' class='fas fa-external-link'></i>" +
                                                "</a>" + 
                                                "<a id='receipt-button' onclick='" + receiptOnClick + "' class='a-outline receipt-button-position' title='" + (connection ? ($("#ReceiptCreated").val() + " " + connection.AcKeyView) : $("#CreateReceipt").val()) + "'>" +
                                                    "<i class='fa fa-shopping-cart' style='color: " + receiptButtonColor + "'></i>" +
                                                "</a>" +
                                            "</span>" +
                                            "<br />" + 
                                            "<span id='cal-items-customer'>(" + order.ConsigneeId + ")</span>" +
                                            "<span class='cal-items-check hidden' data-tooltip-check='" + tooltipSelectCheck + "'></span>" +
                                            "</p>" +
                                            "<p>" + (item.FixedAssetName != null ? $("#Means").val() + ": " + item.FixedAssetName : '') + "</p>" +
                                        "<span class='resize-helper' style='top: 0px'></span>" +
                                        "<span class='resize-helper' style='bottom: 0px'></span>" +
                                 "</div>");
                    }

                    // Set weekly calendar values
                    if ($(calendarTypeId).val() === weeklyCalendar) {
                        startPeriodDate = $(tableIdWM + " thead th:not(:first-child)").first().attr("data-date");
                        endPeriodDate = $(tableIdWM + " thead th:not(:first-child)").last().attr("data-date");
                        let [dayStart, monthStart, yearStart] = startPeriodDate.split(".");
                        let [dayEnd, monthEnd, yearEnd] = endPeriodDate.split(".");
                        startDay = moment(new Date(yearStart, monthStart - 1, dayStart)).dayOfYear(); 
                        endDay = moment(new Date(yearEnd, monthEnd - 1, dayEnd)).dayOfYear(); 

                        if (orderStartDay < startDay && orderEndDay <= endDay) {
                            dateStart = startPeriodDate;
                            durationDays = orderEndDay - startDay + lastDay;
                        } else if (orderStartDay >= startDay && orderEndDay > endDay) {
                            durationDays = endDay - orderStartDay + lastDay;
                        } else if (orderStartDay <= startDay && orderEndDay >= endDay) {
                            dateStart = startPeriodDate;
                            durationDays = 7;
                        } else {
                            durationDays = durationDays == 0 ? 1 : orderEndDay - orderStartDay + lastDay;
                        }

                        if (orderStartDay < startDay) {
                            draggable = false
                            startedBeforePeriodStyle = "cursor: default; border-left-style: none;";
                        }
                        rangeClass = durationDays > 1 ? "events-range" : rangeClass;
                        weeklyCell = $(weeklyTableId + " tbody td[data-worker='" + worker + "'][data-date='" + dateStart + "'] div");
                        itemWidth = durationDays == 1 ? cellWidth : (cellWidth * durationDays) - itemWidthCorrection;

                        if (isTools) {
                            weeklyCell = $(weeklyTableToolsId + " tbody td[data-tool='" + tool + "'][data-date='" + dateStart + "'] div");
                        }

                        weeklyCell
                            .append("<p class='calendar-events " + rangeClass + " ' id='w-" + item.AcKey + "-" + item.AnNo + "' draggable='" + draggable + "' style='background: " + shade(item.ColorCode, shadeNum) + "; border-left-color: " + item.ColorCode + "; width: " + itemWidth + "px; " + startedBeforePeriodStyle + "' rel='tooltip' data-toggle='tooltip' data-html='true' data-placement='top'" +
                                "data-starttime='" + itemStartTime + "' data-endtime='" + itemEndTime + "' data-startdate='" + dateStart + "' data-enddate='" + dateEnd + "' data-range='" + durationDays + "' data-duration='" + rowSpan + "' data-title='" + itemTooltip + "'>" +
                                itemStartTime + " - " + itemEndTime + "<br/>" + item.Name + "</p>");

                        let orderStartDayIterator = orderStartDay;
                        let weeklyCellHelper;
                        let isMonday;
                        for (orderStartDayIterator; orderStartDayIterator <= orderEndDay; orderStartDayIterator++) {
                            isMonday = new Date(year, 0, orderStartDayIterator).getDay() == 1;
                            dateStart = moment(new Date(year, 0, orderStartDayIterator)).format(dateFormat);

                            if (isMonday || orderStartDay == orderStartDayIterator) continue;

                            weeklyCellHelper = $(weeklyTableId + " tbody td[data-worker='" + worker + "'][data-date='" + dateStart + "'] div");

                            if (isTools) {
                                weeklyCellHelper = $(weeklyTableToolsId + " tbody td[data-tool='" + tool + "'][data-date='" + dateStart + "'] div");
                            }

                            weeklyCellHelper
                                .prepend("<p class='calendar-events event-helper w-" + item.AcKey + "-" + item.AnNo + " ' id='w-" + item.AcKey + "-" + item.AnNo + "' data-starttime='" + itemStartTime + "' data-endtime='" + itemEndTime + "'></p>");
                        }
                    }
                    
                    // Set monthly calendar values
                    if ($(calendarTypeId).val() === monthlyCalendar) {
                        startPeriodDate = $(tableIdWM + " thead th:not(:first-child)").first().attr("data-date");
                        endPeriodDate = $(tableIdWM + " thead th:not(:first-child)").last().attr("data-date");
                        let [dayStart, monthStart, yearStart] = startPeriodDate.split(".");
                        let [dayEnd, monthEnd, yearEnd] = endPeriodDate.split(".");
                        startDay = moment(new Date(yearStart, monthStart - 1, dayStart)).dayOfYear(); 
                        endDay = moment(new Date(yearEnd, monthEnd - 1, dayEnd)).dayOfYear(); 

                        if (orderStartDay < startDay && orderEndDay <= endDay) {
                            dateStart = startPeriodDate;
                            durationDays = orderEndDay - startDay + lastDay;
                        } else if (orderStartDay >= startDay && orderEndDay > endDay) {
                            durationDays = endDay - orderStartDay + lastDay;
                        } else if (orderStartDay <= startDay && orderEndDay >= endDay) {
                            dateStart = startPeriodDate;
                            durationDays = 7;
                        } else {
                            durationDays = durationDays == 0 ? 1 : orderEndDay - orderStartDay + lastDay;
                        }

                        if (orderStartDay < startDay) {
                            draggable = false
                            startedBeforePeriodStyle = "cursor: default; border-left-style: none;";
                        }
                        rangeClass = durationDays > 1 ? "events-range" : rangeClass;
                        monthlyCell = $(monthlyTableId + " tbody td[data-worker='" + worker + "'][data-date='" + dateStart + "'] div");
                        itemWidth = durationDays == 1 ? cellWidth : (cellWidth * durationDays) - itemWidthCorrection;

                        if (isTools) {
                            monthlyCell = $(monthlyTableToolsId + " tbody td[data-tool='" + tool + "'][data-date='" + dateStart + "'] div");
                        }

                        monthlyCell
                            .append("<p class='calendar-events " + rangeClass + " ' id='m-" + item.AcKey + "-" + item.AnNo + "' draggable='" + draggable + "' style='background: " + shade(item.ColorCode, shadeNum) + "; border-left-color: " + item.ColorCode + "; width: " + itemWidth + "px; " + startedBeforePeriodStyle + "' rel='tooltip' data-toggle='tooltip' data-html='true' data-placement='top'" +
                                "data-starttime='" + itemStartTime + "' data-endtime='" + itemEndTime + "' data-startdate='" + dateStart + "' data-enddate='" + dateEnd + "' data-range='" + durationDays + "' data-duration='" + rowSpan + "' data-title='" + itemTooltip + "'>" +
                                itemStartTime + " - " + itemEndTime + "<br/>" + item.Name + "</p>");

                        let orderStartDayIterator = orderStartDay;
                        let monthlyCellHelper;
                        let isFirstDayInMonth;
                        for (orderStartDayIterator; orderStartDayIterator <= orderEndDay; orderStartDayIterator++) {
                            isFirstDayInMonth = new Date(year, 0, orderStartDayIterator).getDate() == 1;
                            dateStart = moment(new Date(year, 0, orderStartDayIterator)).format(dateFormat);

                            if (isFirstDayInMonth || orderStartDay == orderStartDayIterator) continue;

                            monthlyCellHelper = $(monthlyTableId + " tbody td[data-worker='" + worker + "'][data-date='" + dateStart + "'] div");

                            if (isTools) {
                                monthlyCellHelper = $(monthlyTableToolsId + " tbody td[data-tool='" + tool + "'][data-date='" + dateStart + "'] div");
                            }

                            monthlyCellHelper
                                .prepend("<p class='calendar-events event-helper m-" + item.AcKey + "-" + item.AnNo + " ' id='m-" + item.AcKey + "-" + item.AnNo + "' data-starttime='" + itemStartTime + "' data-endtime='" + itemEndTime + "'></p>");
                        }
                    }
                }
            }
        });
    });

    // Open row if there is two or more items with date range that overlaps
    $(tableIdWM + " tbody tr").each(function (index) {
        $(this).children("td").each(function () {
            let collapseButton = $(this).closest("tr").find("td:first-child .panel-title a");
            let eventHelperLength = $(this).find(".event-helper").length;
            let events = $(this).find(".events-range");

            if (events.length > 1) {
                setTopEventsPosition(events);
            }

            if ((eventHelperLength > 1 || events.length > 1) && !collapseButton.hasClass("inactive-link")) {
                collapseButton.addClass("inactive-link").click();
                return false;
            }
        });
    });
}

function setAbsences(absences, isTools) {
    let tableId = isTools ? dailyTableToolsId : dailyTableId;

    $.each(absences, function (i, item) {
        let startTimeAbsence = getTime(item.DateStart);
        let endTimeAbsence = getTime(item.DateEnd);
        let duration = (convertTimeToMinutes(endTimeAbsence) - convertTimeToMinutes(startTimeAbsence)) / minutesPerRow;
        let durationAbsence = duration % 1 == 0 ? duration : parseInt(duration) + 1;
        let absenceDate = moment(item.DateStart).format(dateFormat);

        itemHeight = cellHeight * durationAbsence;

        if ($(calendarTypeId).val() === dailyCalendar) {
            let absenceCellD = $(dailyTableId + " tbody td[data-worker='" + item.Worker + "'][data-time='" + startTimeAbsence + "']");

            absenceCellD
                .append("<p class='calendar-absence ' id='d-" + item.AnQId + "' style = 'background: " + shade(item.BackgroundColor, shadeNum) + "; border-left-color: " + item.BackgroundColor + "; height: " + itemHeight + "px;' data-duration='" + durationAbsence + "'><i class='m-r-xs fas " + item.IconName + "'></i>" + item.TypeName + "</p>");
            let trIndex = absenceCellD.closest("tr").index();
            let tdIndex = absenceCellD.index();

            setReservedFields(tableId, trIndex, tdIndex, durationAbsence, "absence");
        }

        if ($(calendarTypeId).val() === weeklyCalendar) {
            let absenceCellW = $(weeklyTableId + " tbody td[data-worker='" + item.Worker + "'][data-date='" + absenceDate + "'] div");
            absenceCellW
                .append("<p class='calendar-absence ' id='w-" + item.AnQId + "' style = 'background: " + shade(item.BackgroundColor, shadeNum) + "; border-left-color: " + item.BackgroundColor + ";'" +
                    " data-duration='" + durationAbsence + "' data-starttime='" + startTimeAbsence + "' data-endtime='" + endTimeAbsence + "'><i class='m-r-xs fas " + item.IconName + "'></i>" + item.TypeName + "</p>");
        }
      
        if ($(calendarTypeId).val() === monthlyCalendar) {
            let absenceCellM = $(monthlyTableId + " tbody td[data-worker='" + item.Worker + "'][data-date='" + absenceDate + "'] div");
            absenceCellM
                .append("<p class='calendar-absence ' id='m-" + item.AnQId + "' style = 'background: " + shade(item.BackgroundColor, shadeNum) + "; border-left-color: " + item.BackgroundColor + ";'" +
                    " data-duration='" + durationAbsence + "' data-starttime='" + startTimeAbsence + "' data-endtime='" + endTimeAbsence + "'><i class='m-r-xs fas " + item.IconName + "'></i>" + item.TypeName + "</p>");
        }
    });
}
//#endregion FILLING CALENDAR WITH DATA

function sortEventsWM(dropcell = "") {
    if ($(calendarTypeId).val() === dailyCalendar) return;

    let parentDiv = $(".collapse-items, .cal-item-full-height");

    if (dropcell) {
        parentDiv = dropcell;
    }

    parentDiv.each(function () {
        $(this).find("p.calendar-events:not(.event-helper, .events-range)").sort(function (a, b) {
            return convertTimeToMinutes($(a).data("starttime")) - convertTimeToMinutes($(b).data("starttime"));
        })
        .appendTo($(this))
    });
}

//#region OVERLAPING
function checkOverlaping(isTools) {
    let calType = $(calendarTypeId).val();
    let daily = isTools ? dailyTableToolsId : dailyTableId;
    let weekly = isTools ? weeklyTableToolsId : weeklyTableId;
    let monthly = isTools ? monthlyTableToolsId : monthlyTableId

    if (calType == weeklyCalendar) {
        checkIfOverlaps(weekly, isTools);
    } else if (calType == monthlyCalendar) {
        checkIfOverlaps(monthly, isTools);
    } else {
        checkIfOverlaps(daily, isTools);
    }
}

function checkIfOverlaps(tableId, isTools) {
    let items = [];
    $(tableId + " .during-absence").removeClass("during-absence");
    $(tableId + " .with-absence").css("margin-left", "");
    $(tableId + " .with-absence").removeClass("with-absence");
    $(tableId + " .absence").removeClass("absence");
    $(tableId + " .absence-ml").removeClass("absence-ml");
    $(tableId + " .fa-exclamation").remove();
    $(tableId + " .icons-under").removeClass("icons-under");
    $(tableId + " #cal-items-icons").addClass("cal-items-icons");
    $(tableId + " .cal-items-icons").find("#cal-edit-button").addClass("m-r-sm");
    $(tableId + " .cal-items-icons").find("#receipt-button").addClass("receipt-button-position");

    $(tableId + " .calendar-events," + tableId + " .calendar-absence").each(function () {
        let worker = $(this).closest("td").data("worker");
        let date = $(this).closest("td").data("date");
        let timeStart = $(this).data("starttime");
        let timeEnd = $(this).data("endtime");
        let id = $(this).attr("id");
        let type = $(this).hasClass("calendar-events") ? "item" : "absence"
        let fixedAsset = $(this).closest("td").data("tool");

        if (tableId === dailyTableId || tableId === dailyTableToolsId) {
            let duration = $(this).data("duration");
            timeStart = $(this).closest("td").data("time");
            timeEnd = getEndTime(timeStart, duration);
        }

        items.push({
            worker: worker,
            date: date,
            timeStart: timeStart,
            timeEnd: timeEnd,
            type: type,
            id: id,
            fixedAsset: fixedAsset
        })
    });

    for (var i = 0; i < items.length; i++) {
        let iterator = (tableId === dailyTableId || tableId === dailyTableToolsId) ? 0 : i + 1;
        for (var j = iterator; j < items.length; j++) {
            let itemI = $("#" + items[i].id);
            let itemJ = $("#" + items[j].id);
            let overlap = checkIfTimeOverlaps(items, i, j, isTools);

            if (overlap && (tableId === weeklyTableId || tableId === weeklyTableToolsId || tableId === monthlyTableId || tableId === monthlyTableToolsId)) {
                if (items[i].type == "item" && items[j].type == "item") {
                    addExclamationIconWM(itemI);
                    addExclamationIconWM(itemJ);
                } else if ((items[i].type == "item" && items[j].type == "absence") || (items[i].type == "absence" && items[j].type == "item")) {
                    addExclamationIconWM(itemJ);
                }
            }

            if (overlap && (tableId === dailyTableId || tableId === dailyTableToolsId)) {
                if (j !== i && itemI.hasClass("calendar-events")) {
                    itemI.addClass("absence absence-ml with-absence");
                    itemI.find(".cal-items-icons").addClass("icons-under").removeClass("cal-items-icons");
                    itemI.find("#cal-edit-button").removeClass("m-r-sm");
                    itemI.find("#receipt-button").removeClass("receipt-button-position");
                    addExclamationIcon(itemI);
                    $(".ui-resizable-handle").css("z-index", "unset");
                }

                if (j !== i && itemI.hasClass("calendar-absence")) {
                    itemI.addClass("absence");
                }
            }
        }
    }
    updateElementsWidth(isTools);
}

function checkIfTimeOverlaps(items, i, j, isTools) {
    let itemToComapre = isTools ? compareByTool : compareByWorker;
    return ((items[i].timeStart >= items[j].timeStart && items[i].timeEnd <= items[j].timeEnd && items[i][itemToComapre] == items[j][itemToComapre] && items[i].date == items[j].date) ||
        (items[i].timeStart >= items[j].timeStart && items[i].timeStart < items[j].timeEnd && items[i][itemToComapre] == items[j][itemToComapre] && items[i].date == items[j].date) ||
        (items[i].timeStart < items[j].timeStart && items[i].timeEnd > items[j].timeEnd && items[i][itemToComapre] == items[j][itemToComapre] && items[i].date == items[j].date) ||
        (items[i].timeEnd > items[j].timeStart && items[i].timeEnd <= items[j].timeEnd && items[i][itemToComapre] == items[j][itemToComapre] && items[i].date == items[j].date))
}
//#endregion OVERLAPING

//#region EXCLAMATION
function addExclamationIcon(element) {
    element.prepend("<i class='fas fa-exclamation'></i> ");
}

function addExclamationIconWM(element) {
    element.addClass("during-absence").prepend("<i class='fas fa-exclamation'></i> ");
}
//#endregion EXCLAMATION

//#region RESERVED FIELDS
function setReservedFields(tableId, trIndex, tdIndex, duration, type) {
    for (var i = 0; i < duration; i++) {
        $(tableId + " tr:nth-child(" + (trIndex + 1 + i) + ") td:nth-child(" + (tdIndex + 1) + ")")
            .attr("data-" + type, true);
    }
}

function setAllReservedFields(isTools) {
    let tableId = isTools ? dailyTableToolsId : dailyTableId;

    $(tableId + " .calendar-events").each(function () {
        let trIndex = $(this).closest("tr").index();
        let tdIndex = $(this).parent("td").index();
        let duration = $(this).data("duration");

        setReservedFields(tableId, trIndex, tdIndex, duration, "item");
    });
}

function clearEventData(tableId, trIndex, tdIndex, duration) {
    for (let i = 0; i < duration; i++) {
        $(tableId + " tr:nth-child(" + (trIndex + 1 + i) + ") td:nth-child(" + (tdIndex + 1) + ")")
            .removeAttr("data-item");
    }
}

function clearAllEventData(tableId) {
    $(tableId + " td").removeAttr("data-item data-reserved");
    $(".reserved-field").removeClass("reserved-field");
}
//#endregion RESERVED FIELDS

function showHideIcons(tableId) {
    $(tableId + " .calendar-events").on("mouseenter", function (event) {
        if (!openTooltip) {
            $(this).find(".cal-items-icons").removeClass("hidden");
            $(this).find(".icons-under").removeClass("hidden");
        }
    });

    $(tableId + " .calendar-events").on("mouseleave", function (event) {
        if (!openTooltip) {
            $(this).find(".cal-items-icons").addClass("hidden");
            $(this).find(".icons-under").addClass("hidden");
        }
    });
}

//#region SELECTABLE
var identDuration = true;

function enableSelectable(dailyTableTypeId) {
    $(dailyTableTypeId + " td.cell-width")
        .mousedown(function (event) {
            if ($(event.target).hasClass("cell-width") && $(this).children().length == 0 && !openTooltip) {
                initSelectable(dailyTableTypeId);
            }
        })

    $(dailyTableTypeId + " tbody").mouseup(function (event) {
        if (($(event.target).prop("tagName") == "DIV"
            && !$(event.target).hasClass("calendar-events")
            && !$(event.target).hasClass("filter-option")
            && !$(event.target).hasClass("filter-option-inner-inner"))
            || $(event.target).hasClass("cell-width"))
        {
            identDuration = false;
        }
    });
}

function initSelectable(tableId) {
    let isTools = $(calendarBy).val() === calendarByTools;
    let cellsSelected = 0;
    let startCell;
    let startCellIndex;

    $(tableId).selectable({
        filter: "td:empty:not(.hidden)",
        cancel: "th, td:first-child, p.calendar-absence, td.hidden, td[data-item='true']",
        start: function (event, ui) {
            if ($("#calendar-tooltip").length > 0) {
                cancelCreateOrderItem();
            }

            startCell = $(event.toElement);
            startCellIndex = startCell.index();
        },
        stop: function (event, ui) {
            let dropdownDocType = $("#DocumentTypes").val();
            let docType = dropdownDocType.length > 1 ? "" : dropdownDocType[0];

            generateCreateTooltip(startCell.data("time"), convertMinutesToTime(cellsSelected * minutesPerRow), convertMinutesToTime(convertTimeToMinutes(startCell.data("time")) + (cellsSelected * minutesPerRow)), startCell);
            initTooltipTypeahead($("td #IdentSearchTInput"), { noResults: $("#NoResults").val(), name: $("#LocName").val(), ident: $("#LocItem").val() }, startCell, true);
            
            $("#tooltipCreateHelper #documentTypesTInput").val(docType);
            if (isTools) {
                $("#tooltipCreateHelper #toolTInput").val(startCell.data("tool"));
            } else {
                $("#tooltipCreateHelper #workerTInput").val(startCell.data("worker"));
            }

            $("#dateTInput").datepicker();
            $("#dateValidTInput").datepicker();
            $(".selectpicker").selectpicker("refresh");
            selectpickerAPI();
            startCell.css("position", "relative");
            startCell.find("#tooltipCreateHelper").css({ "display": "block", "position": "absolute", "z-index": 9, "left": "40px" });
            $(".ui-selected").addClass("cell-selected")
            $(tableId).selectable("destroy");
            $("#IdentSearchTInput").focus()
        },
        selected: function (event, ui) {
            cellsSelected++;
        },
        selecting: function (event, ui) {
            if (startCellIndex !== $(ui.selecting).index()) {
                $(tableId).selectable("destroy");
            }
        }
    });
}
//#endregion SELECTABLE

function cancelCreateOrderItem() {
    $("#tooltipCreateHelper .tooltip-inner #calendar-tooltip").remove();
    $("td #tooltipCreateHelper").remove();
    $("#tooltipCreateHelper").css("display", "none");
    $(".cell-selected").css("position", "unset");
    $(".cell-selected").removeClass("cell-selected");
    if (editmode) identDuration = true;
}

function createOrderItem() {
    let item = {
        AcKey: $("#AcKey").val(),
        Ident: $("#IdentTInput").val(),
        AnNo: 0,
        Name: $("#IdentSearchTInput").val(),
        Quantity: formatDisplay($("#DefaultDecimalPlacesQuantity").val(), $("#QuantityTInput").val(), true),
        Price: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#PriceTInput").val(), true),
        Rebate: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#RebateTInput").val(), true),
        VAT: formatDisplay($("#DefaultDecimalPlacesPrice").val(), $("#VATTInput").val(), true),
        VATCode: $("#VATCodeTInput").val(),
        Note: $("#noteTInput").val(),
        UM: $("#UMTInput").val(),
        Value: 0,
        OriginalValue: 0,//
        QtyDispDoc: 0,
        DeliveryDeadline: moment(new Date()).toISOString(),
        CostDrv: "",
        Department: "",
        TotalPrice: 0,
        //LastPrice: 0,
        ColorCode: $("#itemColorCode").val() ? $("#itemColorCode").val() : rgbToHex($(".set-wh-hours").css("background-color")),
        Worker: $("#workerTInput").val(),
        FixedAsset: $("#toolTInput").val(),
        PrstTime: convertTimeToMinutes($("#durationTInput").val()),
        PrstUMTime: "M",
        StartTime: $("#startTimeTInput").val(),
        EndTime: $("#endTimeTInput").val(),
        Customer: $("#customerTInput").val(),
        Date: moment(new Date($("#dateTInput").datepicker('getDate'))).toISOString(),
        DateValid: moment(new Date($("#dateValidTInput").datepicker('getDate'))).toISOString(),
    };

    if (item.UM === $("#MeusurementUnitDay").val()) {
        var dateDiff = new Date(item.DateValid).getTime() - new Date(item.Date).getTime();
        if (dateDiff === 0) {
            item.Quantity = 1;
        } else {
            item.Quantity = Math.ceil(dateDiff / (1000 * 3600 * 24));
        }
    }
    $('#tooltip-create-btn').attr('disabled', true).children(".fa-spinner").removeClass('hidden').next().addClass('hidden');
    createOrder(item).then(function () {
        $('#tooltip-create-btn').attr('disabled', false).children(".fa-spinner").addClass('hidden').next().removeClass('hidden');
    });
    editedItemFromOpenedOrder = true;
    identDuration = true;
}

function generateCreateTooltip(startTime, duration, endTime, startCell) {
    // Close opened tooltip
    if ($("#calendar-tooltip").length > 0) {
        $("#calendar-tooltip").closest(".tooltip").siblings().click();
    }

    let currentDate = moment($(sidebarCalendar).val()).format(dateFormat);
    let tooltipCreate = `
        <div id="calendar-tooltip">
            <h5 class="tooltip-header" style="background: lightgray;border-bottom:1px solid black">
                <input style="width: 90%" type="text" class="form-control typeahead_3" id="IdentSearchTInput"
                    dataUrl="${$("#IdentUrl").val()}"
                    placeholder="${$("#ChooseItemOrService").val()}" autocomplete="off" />
                <span class="cal-tooltip-icons" style="top: 22px; right: 8px;">
                    <a id="pickColor" class="a-outline m-r-md">
                        <span class="dropdown color-picker-dropdown" data-toggle="dropdown">
                            <p class="dropdown-toggle fa fa-solid fa-palette" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <input type="hidden" id="itemColorCode" />
                            </p>
                            <span class="dropdown-menu dropdown-menu-right rounded-0 box-shadow">
                                <span class="row">${$("#tooltipColors").html()}</span>
                            </span>
                        </span>
                    </a>
                </span>
            </h5>
            <table class="tooltip-table">
                <tbody>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#DocTypeLoc").val()}</b></td>
                        <td class="tooltip-cell edit-row">
                            <select id="documentTypesTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    title="" >
                                ${$("#DocumentTypesEdit").html()}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#Customer").val()}</b></td>
                        <td class="tooltip-cell edit-row partner-cell">
                            <select id="customerTInput"
                                    class="form-control selectpicker selectpickerAPI calendar-dropdown-btn"
                                    data-live-search="true"
                                    data-api-url="${$("#BuyerDropdownValues").val()}"
                                    title="" >
                                ${$("#CustomersEdit").html()}
                            </select>
                            <div class="addable-button">
                                <button type="button" title="${$("#AddingNewPartner").val()}" class="btn createNewButton" onclick="openSubjectModal(\`customerTInput\`, \`${true}\`)">
                                    <i class="fas fa-building"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#TaBegin").val()}</b></td>
                        <td class="tooltip-cell edit-row tooltip-times" style="white-space: nowrap;">
                            <input id="dateTInput" type="text" value=${currentDate} class="form-control datepicker" autocomplete="off">
                            <input id="startTimeTInput" onblur="handleTooltipTimeInputs(true);" type="time" value="${startTime}" class="form-control" autocomplete="off">
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#TaEnd").val()}</b></td>
                        <td class="tooltip-cell edit-row tooltip-times">
                            <input id="dateValidTInput" type="text" value=${currentDate} class="form-control datepicker" autocomplete="off">
                            <input id="endTimeTInput" onblur="handleTooltipTimeInputs();" type="time" value="${endTime}" class="form-control" autocomplete="off">
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#ContractorLoc").val()}</b></td>
                        <td class="tooltip-cell edit-row">
                            <select id="workerTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    data-live-search="true"
                                    title="" >
                                ${$("#ContractorsEdit").html()}
                            </select>        
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#Means").val()}</b></td>
                        <td class="tooltip-cell edit-row">
                                <select id="toolTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    data-live-search="true"
                                    title="" >
                                ${$("#FixedAssetsEdit").html()}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#CalendarNote").val()}</b></td>
                        <td class="tooltip-cell edit-row">
                            <textarea id="noteTInput" type="text" class="form-control" style="resize: none;"></textarea>
                        </td>
                    </tr>
                    <tr style="display: none">
                        <td>
                            <input id="DeliveryDeadlineTInput" hidden value="">
                            <input id="durationTInput" hidden value="${duration}">
                            <input id="IdentTInput" hidden value="">
                            <input id="PriceTInput" hidden value="">
                            <input id="RebateTInput" hidden value="">
                            <input id="QuantityTInput" hidden value="">
                            <input id="SetItemRTPriceTInput" hidden value="">
                            <input id="SetItemWSPriceTInput" hidden value="">
                            <input id="SetItemWSPrice2TInput" hidden value="">
                            <input id="TotalPriceTInput" hidden value="">
                            <input id="UMTInput" hidden value="">
                            <input id="ValueTInput" hidden value="">
                            <input id="VATTInput" hidden value="">
                            <input id="VATCodeTInput" hidden value="">
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td class="tooltip-cell tooltip-buttons">
                            <a onclick="cancelCreateOrderItem();" class="btn btn-outline tooltip-cancel"><i class="fa fa-times text-primary"></i> ${$("#Cancel").val()}</a>
                            <a onclick="createOrderItem();" id="tooltip-create-btn" class="btn btn-success tooltip-create"><i class="fa fa-spinner fa-spin hidden" style="margin-right: 6px;"></i><i class="fa fa-check"></i> ${$("#Add").val()}</a>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="tooltip-input-typeahead custom-typeahead-wrapper" style="position:absolute;height:80%;width:323px;left:11px;top:50px"></div>
        </div>`

    $("#tooltipCreateHelper .tooltip-inner").append(tooltipCreate);
    startCell.append($("#tooltipCreateHelper").clone());
    $("#tooltipCreateHelper .tooltip-inner").first().empty();
}

function openOrderFormWM() {
    $(".cal-item-full-height, .collapse-items").on("click", function () {
        if ($(this).children().length !== 0) return;

        let worker = $(this).parent().data("worker");
        let tool = $(this).parent().data("tool");
        addNewOrderItemWM(worker, tool);
    });
}

function initResizable(isTools) {
    let initCell;
    let initCellIndex;
    let initRowIndex;
    let addedHeight;
    let addedRowsNum;
    let subtractedHeight;
    let subtractedRowsNum;
    let currentMinutes;
    let newNthRow;
    let newMinutesStart;
    let newDuration;
    let newMinutesEnd;
    let newPrstTime;
    let newStartTime;
    let newEndTime;
    let tableId = isTools ? dailyTableToolsId : dailyTableId;

    $(tableId + " .calendar-events").resizable({
        handles: "n, s",
        snap: "td",
        snapTolerance: 35,
        minHeight: 35,
        start: function (event, ui) {
            table = $(this).closest("table").attr("id");
            initCell = $(this).parent();
            initCellIndex = initCell.index();
            initRowIndex = $(this).closest("tr").index();
            clearAllEventData(tableId);
        },
        stop: function (event, ui) {
            let initTime = $(this).parent().attr("data-time");
            let resizableSide = $(this).data('ui-resizable').axis;
            let id = $(this).attr("id");
            let duration = parseInt($(this).data("duration"));

            if (resizableSide === "n") {
                // North resize up
                if (ui.originalSize.height < ui.size.height) {
                    addedHeight = Math.trunc(ui.size.height) - ui.originalSize.height;
                    addedRowsNum = Math.round(addedHeight / cellHeight);
                    newMinutesStart = convertTimeToMinutes(initTime) - (addedRowsNum * minutesPerRow);
                    newDuration = duration + addedRowsNum;
                    newNthRow = (initRowIndex - addedRowsNum + 1);
                    newPrstTime = newDuration * minutesPerRow;
                    newStartTime = convertMinutesToTime(newMinutesStart);

                    changePositionAfterNorthResize(tableId, $(this), newDuration, newNthRow, initCellIndex, initCell);

                    newEndTime = convertMinutesToTime(newMinutesStart + (newDuration * minutesPerRow));
                    updateCalendarEntry(id, initCell.data("worker"), newStartTime, $(this).data("startdate"), newEndTime, $(this).data("enddate"), newPrstTime, true, "");

                // North resize down
                } else {
                    subtractedHeight = ui.originalSize.height - Math.trunc(ui.size.height);
                    subtractedRowsNum = Math.round(subtractedHeight / cellHeight);
                    newMinutesStart = convertTimeToMinutes(initTime) + (subtractedRowsNum * minutesPerRow);
                    newDuration = duration - subtractedRowsNum;
                    newNthRow = (initRowIndex + subtractedRowsNum + 1);
                    newPrstTime = newDuration * minutesPerRow;
                    newStartTime = convertMinutesToTime(newMinutesStart);

                    changePositionAfterNorthResize(tableId, $(this), newDuration, newNthRow, initCellIndex, initCell);

                    newEndTime = convertMinutesToTime(newMinutesStart + (newDuration * minutesPerRow));
                    updateCalendarEntry(id, initCell.data("worker"), newStartTime, $(this).data("startdate"), newEndTime, $(this).data("enddate"), newPrstTime, true, "");
                }
            } else {
                // South resize down
                if (ui.originalSize.height < ui.size.height) {
                    addedHeight = Math.trunc(ui.size.height) - ui.originalSize.height;
                    addedRowsNum = Math.round(addedHeight / cellHeight);
                    addedMinutes = addedRowsNum * minutesPerRow;
                    currentMinutes = duration * minutesPerRow;
                    newMinutesEnd = convertTimeToMinutes(initTime) + currentMinutes + (addedRowsNum * minutesPerRow);
                    newDuration = duration + addedRowsNum;
                    newEndTime = convertMinutesToTime(newMinutesEnd);
                    newPrstTime = newDuration * minutesPerRow;

                    $(this).data("duration", newDuration);

                    updateCalendarEntry(id, initCell.data("worker"), initCell.data("time"), $(this).data("startdate"), newEndTime, $(this).data("enddate"), newPrstTime, true, "");

                // South resize up
                } else {
                    subtractedHeight = ui.originalSize.height - Math.trunc(ui.size.height);
                    subtractedRowsNum = Math.round(subtractedHeight / cellHeight);
                    currentMinutes = duration * minutesPerRow;
                    newMinutesEnd = convertTimeToMinutes(initTime) + currentMinutes - (subtractedRowsNum * minutesPerRow);
                    newDuration = duration - subtractedRowsNum;
                    newEndTime = convertMinutesToTime(newMinutesEnd);
                    newPrstTime = newDuration * minutesPerRow;

                    $(this).data("duration", newDuration);

                    updateCalendarEntry(id, initCell.data("worker"), initCell.data("time"), $(this).data("startdate"), newEndTime, $(this).data("enddate"), newPrstTime, true, "");
                }
            }

            let startTime = newStartTime ? newStartTime : initCell.data("time");
            $(this).css("top", "unset");
            $(this).height(newDuration * cellHeight);
            changeTooltipPosition(tableId, $("#" + id), true, false);
            updateItemTooltip($(this), startTime, newEndTime, $(this).data("startdate"), $(this).data("enddate"), initCell.data("worker"), initCell.data("tool"), isTools);
            setAllReservedFields(isTools);
        }
    });
}

//#region SCROLL TO 08:00/FIRST ITEM
function initScroll(tableId) {
    let startWorkingHour = $(tableId + " td.scroll-to-hour:not(.hidden)")[0];
    let activeDay = $(tableId + " .activeDay");

    if (startWorkingHour && ($(calendarTypeId).val() === dailyCalendar || tableId === miniCalendarTableWorkersId || tableId === miniCalendarTableToolsId)) {
        startWorkingHour.scrollIntoView();
        $(tableId + " td.scroll-to-hour").removeClass("scroll-to-hour");
    }

    if (activeDay.length > 0) {
        let cellWidth = $(tableId + " .cell-width")[0].getBoundingClientRect().width;
        let scrollToActiveDay = activeDay.position().left - cellWidth;
        $('.calendar-wrapper:not(.hidden)').animate({ scrollLeft: scrollToActiveDay });
    }
}

var firstLoad = true;
function scrollLeftToFirstItem(tableId) {
    if (firstLoad) {
        let cellsIndex = [];
        let hourCellWidth = $(".set-wh-hours")[0].getBoundingClientRect().width;

        $(tableId + " .calendar-events").closest("td").each(function () {
            cellsIndex.push($(this).index());
        });

        if (cellsIndex.length > 0) {
            let smallestArrayNum = Math.min(...cellsIndex);
            let firstItem = $(tableId + " .calendar-events").closest("td")[cellsIndex.indexOf(smallestArrayNum)];
            let cellWidth = firstItem.getBoundingClientRect().width;
            let scrollToFirstItem = $(firstItem).position().left - cellWidth + hourCellWidth;
            $(".calendar-wrapper").scrollLeft(scrollToFirstItem);
        }

        firstLoad = false;
    }
}
//#endregion SCROLL TO 08:00/FIRST ITEM

function changePositionAfterNorthResize(tableId, element, duration, nthRow, cellIndex, initCell) {
    element.data("duration", duration);
    $(tableId + " tbody tr:nth-child(" + nthRow + ") td:nth-child(" + (cellIndex + 1) + ")")
        .removeClass("ui-selectee")
        .append(element);
    //initCell.addClass("ui-selectee").empty();
}

function addNewOrderItemWM(worker, tool) {
    $("#calendar-buttons-tabbed .close-btn").click();
    $(".order-calendar-th").removeClass("hidden");
    $(".order-calendar-td").removeClass("hidden");

    if (tool) $("#Tools").val(tool);

    $("#Contractor").val(worker);
    $("#Contractor").selectpicker("refresh");
    $("#Tools").selectpicker("refresh");
}

function redirectToOrder(acKey) {
    window.location.href = $("#RedirectUrl").val() + "?id=" + acKey;
}

function setWeekDates(date, isTools) {
    // Set thead dates
    let tableId = isTools ? weeklyTableToolsId : weeklyTableId;
    let dayOfWeek = [$("#Monday").val(), $("#Tuesday").val(), $("#Wednesday").val(), $("#Thursday").val(), $("#Friday").val(), $("#Saturday").val(), $("#Sunday").val()];

    $(tableId + " thead th:not(:first-child)").each(function (index) {
        let monday = getMonday(date);
        let currentDay = monday;
        let activeDay = new Date(date);
        activeDay = moment(activeDay).format("DD.MM.");
        currentDay.setDate(monday.getDate() + index);
        $(this).attr("data-date", moment(currentDay).format(dateFormat));
        currentDay = moment(currentDay).format("DD.MM.");

        if (currentDay == activeDay) {
            $(this).addClass("activeDay");
        }

        $(this).append(dayOfWeek[index].substr(0, 3) + ", " + currentDay);
    });

    // Set data-date attribute
    let currentWorker = "";
    let currentTool = "";
    let i;

    $(tableId + " > tbody > tr > td:not(:first-child)").each(function () {
        let worker = $(this).data("worker");
        let tool = $(this).data("tool");
        let monday = getMonday(date);
        let currentDay = monday;

        if (worker != currentWorker || tool != currentTool) {
            currentWorker = worker;
            currentTool = tool;
            i = 0;
        }

        if (worker == currentWorker || tool == currentTool) {
            currentDay.setDate(monday.getDate() + i);
            $(this).attr("data-date", moment(currentDay).format(dateFormat));
            i = i + 1;
        }
    });
}

function setMonthDates(monthDate, isTools) {
    let tableId = isTools ? monthlyTableToolsId : monthlyTableId;
    let dayOfWeek = [$("#Sunday").val(), $("#Monday").val(), $("#Tuesday").val(), $("#Wednesday").val(), $("#Thursday").val(), $("#Friday").val(), $("#Saturday").val()];
    let activeDay = new Date(monthDate);
    activeDay = moment(activeDay).format(dateFormat);
    let date = new Date(monthDate); 
    let month = date.getMonth();

    date.setDate(1);
    while (date.getMonth() == month) {
        let d = date.getDate().toString().padStart(2, '0') + ". " + dayOfWeek[date.getDay()].substr(0, 3);
        let currentDay = moment(date).format(dateFormat);
        let activeClass = currentDay == activeDay ? "activeDay" : "";

        $(tableId + " thead tr").append("<th class='" + activeClass + "' data-date='" + currentDay + "'>" + d + "</th>");
        $(tableId + " tbody tr:not(:last-child)").append("<td class='cell-width' data-date='" + currentDay + "'><div class='collapse-helper '></div></td>");

        date.setDate(date.getDate() + 1);
    }

    $(tableId + " tbody tr").each(function () {
        let collapseClass = $(this).find("td:first-child a").hasClass("collapsed");
        let itemsContainer = $(this).find("td:not(:first-child) div");
        let worker = $(this).find("td:first-child").data("worker");
        let tool = $(this).find("td:first-child").data("tool");

        if (worker) {
            $(this).find("td:not(:first-child)").attr("data-worker", worker);
        } else if (tool) {
            $(this).find("td:not(:first-child)").attr("data-tool", tool);
        }

        if (collapseClass) {
            itemsContainer.addClass("collapse-items");
        } else {
            itemsContainer.removeClass("collapse-items");
            itemsContainer.addClass("cal-item-full-height");
        }
    });

    if (isTools) {
        showSelectedCalendar(monthlyTools);
    } else {
        showSelectedCalendar(monthly);
    }
}

function clearTable() {
    $(dailyTableId + " tr td:not(:first-child)").empty().removeAttr("rowspan");
    $(weeklyTableId + " thead th:not(:first-child)").empty();
    $(weeklyTableId + " tbody td:not(:first-child) div").empty();
    $(monthlyTableId + " thead th:not(:first-child)").remove();
    $(monthlyTableId + " tbody td:not(:first-child)").remove();

    $(dailyTableToolsId + " tr td:not(:first-child)").empty().removeAttr("rowspan");
    $(weeklyTableToolsId + " thead th:not(:first-child)").empty();
    $(weeklyTableToolsId + " tbody td:not(:first-child) div").empty();
    $(monthlyTableToolsId + " thead th:not(:first-child)").remove();
    $(monthlyTableToolsId + " tbody td:not(:first-child)").remove();
}

function toggleCalItems(index, calType, tableId) {
    $("#" + tableId + " tbody tr:nth-child(" + (index + 1) + ") td:not(:first-child) div.collapse-helper").toggleClass("collapse-items").toggleClass("cal-item-full-height");
    $("#collapse-" + calType + "-" + index).toggleClass("collapsed");
}

function addTempAbsence(tableId, duration, currentTr, currentTd, isDaily) {
    if (isDaily) {
        $(tableId + " div, p").each(function () {
            let trIndex = $(this).closest("tr").index();
            let tdIndex = $(this).parent("td").index();

            if (currentTr == trIndex && currentTd == tdIndex) {
                return true;
            }

            for (var i = 1; i < duration; i++) {
                let rowIndex = trIndex + 1 - i;
                let cellIndex = tdIndex + 1;

                $(tableId + " tr:nth-child(" + rowIndex + ") td:nth-child(" + cellIndex + ")")
                    .attr("data-reserved", true);
            }
        });

        $(tableId + " td[data-absence], td[data-item], td[data-reserved]")
            .addClass("reserved-field");
    }
}

function calendarDragAndDrop(tableId, isDaily, isTools) {
    var childDiv = isDaily ? "" : "div:first-child";
    var id, dragCell, dropCell, dropCellWorker, dropCellTool, trIndexOld, tdIndexOld, cellsInRow, parentRow, eventsWithRange, dragCellParentRow; 
    var startDate, endDate, startTime, endTime, duration, durationMinutes, daysRange;

    sortEventsWM();

    $(".calendar-events").on("dragstart", function (event) {
        var dt = event.originalEvent.dataTransfer;
        dt.setData("Text", $(this).attr("id"));
        dragCell = $(this).closest("td");
        duration = $(this).data("duration");
        trIndexOld = dragCell.closest("tr").index();
        tdIndexOld = dragCell.index();
        id = $(this).attr("id");

        $("#calendar-tooltip").remove();
        clearEventData(tableId, trIndexOld, tdIndexOld, duration);

        if (isDaily) {
            $(this).addClass("one-row-event");
        } else {
            $("." + id).remove();
            $(this).addClass("one-cell-event");
        }
        
        addTempAbsence(tableId, duration, trIndexOld, tdIndexOld, isDaily);
    });

    $(`${tableId} td ${childDiv}`).on("dragenter dragover drop", function (event) {
        event.preventDefault();
        if (event.type === "drop") {
            if (($(this).data("absence") || $(this).data("item") || $(this).data("reserved")) && (tableId === dailyTableId || tableId === dailyTableToolsId)) {
                return;
            }
            var data = event.originalEvent.dataTransfer.getData("Text", $(this).attr("id"));
            de = $("#" + data).detach();
            de.prependTo($(this));
        };
    });

    $(".calendar-events").on("dragend", function (event) {
        dropCell = $(this).closest("td");
        dropCellWorker = dropCell.data("worker");
        dropCellTool = dropCell.data("tool");
        trIndexNew = dropCell.closest("tr").index();
        tdIndexNew = dropCell.index();
        durationMinutes = duration * minutesPerRow;

        if (isDaily) {
            $(this).removeClass("one-row-event");
            startTime = dropCell.data("time");
            endTime = convertMinutesToTime(convertTimeToMinutes(startTime) + durationMinutes);
            startDate = $(this).data("startdate"); 
            endDate = $(this).data("enddate"); 
        } else {
            $(this).removeClass("one-cell-event");
            startTime = $(this).data("starttime");
            endTime = $(this).data("endtime");
            startDate = dropCell.data("date");
            endDate = getEndDate(startDate, $(this).data("range"));
            eventsWithRange = dropCell.find(".events-range");
            parentRow = $(this).closest("tr");
            dragCellParentRow = dragCell.closest("tr");

            // Recreate event helpers for items with date range
            daysRange = $(this).data("range"); 
            cellsInRow = parentRow.find("td.cell-width").length;
            let itemAdded = 1;
            for (tdIndexNew; tdIndexNew < cellsInRow; tdIndexNew++) {
                if (itemAdded < daysRange && daysRange > 1) {
                    let cell = parentRow.find("td.cell-width")[tdIndexNew + 1];
                    $(cell).find("div.collapse-helper").prepend("<p class='calendar-events event-helper " + id + " ' id='" + id + "' data-starttime='" + startTime + "' data-endtime='" + endTime + "'></p>")
                    itemAdded++
                }
            }

            // If items with date range start at the same date
            if (eventsWithRange.length > 1) {
                setTopEventsPosition(eventsWithRange);
            } else {
                eventsWithRange.css("top", "auto");
            }

            // Open row if in cell are two or more items with date range that overlaps
            parentRow.find("td.cell-width").each(function () {
                let collapseRowButton = parentRow.find("td:first-child .panel-title a");
                if ($(this).find(".event-helper").length > 1 && !collapseRowButton.hasClass("inactive-link")) {
                    collapseRowButton.addClass("inactive-link").click();
                    return false;
                }
            });

            // Collapse row if there is no more than one items with date range that overlaps
            let collapseRowButton = dragCellParentRow.find("td:first-child .panel-title a");
            let rowCollapsed = true;
            dragCellParentRow.find("td.cell-width").each(function () {
                if ($(this).find(".event-helper").length > 1) {
                    rowCollapsed = false;
                    return false;
                }
            });
            if (rowCollapsed && collapseRowButton.hasClass("inactive-link")) {
                dragCell.find(".events-range").css("top", "auto");
                collapseRowButton.removeClass("inactive-link").click();
            }
        }

        updateCalendarEntry(id, dropCellWorker, startTime, startDate, endTime, endDate, durationMinutes, isDaily, dropCellTool);
        updateItemTooltip($(this), startTime, endTime, startDate, endDate, dropCellWorker, dropCellTool, isTools);

        if (isDaily) {
            clearAllEventData(tableId);
            setAllReservedFields(isTools);
        }

        sortEventsWM($(this).parent());
        checkOverlaping(isTools);
        changeTooltipPosition(tableId, $(this), isDaily, false);
    });
}

function updateCalendarEntry(id, worker, startTime, startDate, endTime, endDate, durationTime, isDaily, tool = "", customer = "", color = "", note = "") {
    let acKey = id.split("-")[1];
    let anNo = parseInt(id.split("-")[2]);
    let [dayStart, monthStart, yearStart] = startDate.split(".");
    let [dayEnd, monthEnd, yearEnd] = endDate.split(".");
    let date = moment(new Date(yearStart, monthStart - 1, dayStart)).toISOString();
    let dateValid = moment(new Date(yearEnd, monthEnd - 1, dayEnd)).toISOString(); 

    let calendarData = {
        Worker: worker,
        AcKey: acKey,
        AnNo: anNo,
        Date: date,
        DateValid: dateValid,
        StartTime: startTime,
        EndTime: endTime,
        PrstTime: durationTime,
        Tool: tool,
        Customer: customer,
        Color: color,
        Note: note,
        IsDaily: isDaily
    }

    return $.ajax({
        url: $("#UpdateCalendarUrl").val(),
        method: "POST",
        data: calendarData,
        success: function (data) {
        },
        error: function (error) {
            console.log(error);
        }
    });
}

function setTopEventsPosition(events) {
    let topPosition = 58;
    events.each(function (index) {
        if (index === 0) return;
        $(this).css("top", topPosition + "px");
        topPosition = topPosition + 58;
    });
}

//#region TOOLTIP
var editmode = true;
var openTooltip = false;
var editedItemFromOpenedOrder = false;
var editedItem = false;
var editData; 
var hoverTooltipPosition;

function editItem(acKey, anNo, customer, docType) {
    if (editmode) {
        $.ajax({
            url: $("#GetIdentByIdUrl").val(),
            method: "GET",
            data: {
                acKey: acKey,
                anNo: anNo
            },
            success: function (data) {
                editData = data;
                changeData(data, customer, docType);
            },
            error: function (err) {
                console.log(err);
            }
        });
    } else {
        changeData(editData, customer, docType);
    }
}

function changeData(item, customer, docType) {
    let worker = item.Worker.trim();
    let tool = "";
    let startTime = "";
    let endTime = "";
    let durationTime = item.PrstTime ? convertMinutesToTime(item.PrstTime) : "";
    let id = "d-" + item.AcKey + "-" + item.AnNo;
    let element = $("#" + id);
    let note = item.Note;
    let tooltipElement = $(".tooltip:not(.createT)");

    if (item.StartTime) startTime = roundTime(item.StartTime);
    if (item.EndTime) endTime = roundTime(item.EndTime);
    if (item.FixedAsset) tool = item.FixedAsset.trim();

    $("#" + id).find(".cal-items-icons").removeClass("hidden");
    $("#" + id).find(".icons-under").removeClass("hidden");
    element.tooltip("toggleEnabled");
    toggleTooltipClasses();

    if (editmode) {
        $("#dateTInput").datepicker();
        $("#dateValidTInput").datepicker();
        if (element.attr("data-placement") === "top") {
            hoverTooltipPosition = tooltipElement.position().top;
            let openTooltipPosition = element.position().top - tooltipElement.height() - 35;
            tooltipElement.css("top", openTooltipPosition);
        }
        $(".ui-resizable-handle").css("z-index", "unset");
        cancelCreateOrderItem();
        $("#customerTInput").val(customer);
        $("#workerTInput").val(worker);
        $("#toolTInput").val(tool);
        $("#startTimeTInput").val(startTime);
        $("#endTimeTInput").val(endTime);
        $("#durationTInput").val(durationTime);
        $("#noteTInput").val(note);
        $("#documentTypesTInput").val(docType);

        initTooltipTypeahead($("#IdentSearchTInput"), { noResults: $("#NoResults").val(), name: $("#LocName").val(), ident: $("#LocItem").val() }, element);
        $("#IdentSearchTInput").closest("div.tooltip").css("z-index", 20);

        $(".selectpicker").selectpicker("refresh");
        selectpickerAPI();
        editmode = false;
        openTooltip = true;
        identDuration = false;

        tooltipSelectOnChange(dailyTableId, "#toolTInput");
        tooltipSelectOnChange(dailyTableToolsId, "#workerTInput");
    } else {
        if (element.attr("data-placement") === "top") {
            tooltipElement.css("top", hoverTooltipPosition);
        }
        $(".ui-resizable-handle").css("z-index", 90);
        let customerInput = $("#customerTInput").val();
        let docTypeInput = $("#documentTypesTInput").val();
        let docTypeText = $("#documentTypesTInput").siblings("button").attr("title");
        let workerInput = $("#workerTInput").val();
        let toolInput = $("#toolTInput").val();
        let toolInputText = $("#toolTInput").siblings("button").attr("title");
        let startTimeInput = $("#startTimeTInput").val();
        let endTimeInput = $("#endTimeTInput").val();
        let durationTimeInput = $("#durationTInput").val();
        let color = $("#itemColorCode").val();
        let identId = $("#IdentTInput").val();
        let identName = $("#IdentSearchTInput").val();
        let price = $("#PriceTInput").val();
        let totalPrice = $("#TotalPriceTInput").val();
        let rebate = $("#RebateTInput").val();
        let quantity = $("#QuantityTInput").val();
        let um = $("#UMTInput").val();
        let value = $("#ValueTInput").val();
        let vat = $("#VATTInput").val();
        let vatCode = $("#VATCodeTInput").val();
        let noteInput = $("#noteTInput").val();
        let deliveryDeadline = $("#DeliveryDeadlineTInput").val();
        let setItemRTPrice = $("#SetItemRTPriceTInput").val();
        let setItemWSPrice = $("#SetItemWSPriceTInput").val();
        let setItemWSPrice2 = $("#SetItemWSPrice2TInput").val();
        let lastPrice = $("#LastPriceTInput").val();
        let date = moment(new Date($("#dateTInput").datepicker('getDate'))).toISOString();
        let dateValid = moment(new Date($("#dateValidTInput").datepicker('getDate'))).toISOString();

        // Set item values for update
        item.ColorCode = color;
        item.Customer = customerInput;
        item.DeliveryDeadline = getTime(deliveryDeadline); //
        item.EndTime = endTimeInput;
        item.FixedAsset = toolInput;
        item.Ident = identId;
        item.Name = identName;
        item.Note = noteInput;
        item.Price = parseFloat(toStandardDecimalString(price));
        item.PrstTime = convertTimeToMinutes(durationTimeInput);
        item.Quantity = quantity;
        item.SetItemRTPrice = parseFloat(toStandardDecimalString(setItemRTPrice)); //
        item.SetItemWSPrice = parseFloat(toStandardDecimalString(setItemWSPrice)); //
        item.SetItemWSPrice2 = parseFloat(toStandardDecimalString(setItemWSPrice2)); //
        item.StartTime = startTimeInput;
        item.TotalPrice = parseFloat(toStandardDecimalString(totalPrice)); //
        item.UM = um;
        item.Value = parseFloat(toStandardDecimalString(value)); //
        item.VAT = toDecimalWithComma(vat);
        item.VATCode = vatCode;
        item.Worker = workerInput;
        item.DocType = docTypeInput;
        item.LastPrice = parseFloat(toStandardDecimalString(lastPrice));
        item.Rebate = formatDisplay($("#DefaultDecimalPlacesPrice").val(), rebate, true);
        item.Date = date;
        item.DateValid = dateValid;
        item.RetailPrice = item.RetailPrice.toString().replace('.', ','); //Edit from calendar fix

        $(element).find("#cal-edit-button")
            .attr("onclick", "editItem(\"" + item.AcKey + "\", " + item.AnNo + ", \"" + customerInput + "\", \"" + docTypeInput + "\")");

        if (editedItem) {
            updateTooltipAfterEdit(item, element, toolInputText, durationTimeInput, docTypeText);
            saveIdentCalendar(item);
        }

        editmode = true;
        openTooltip = false;
        identDuration = true;
    }
}

function tooltipSelectOnChange(tableId, selectId) {
    let selectedItem = $(tableId + " " + selectId);
    let startTimeMinutes = convertTimeToMinutes($("#startTimeTInput").val());
    let endTimeMinutes = convertTimeToMinutes($("#endTimeTInput").val());

    selectedItem.on("change", function () {
        let timesWhenSelectedItemIsUsed = getItemsTimes(tableId, "", "", selectedItem.val());
        let enableToChangeSelectedItem = checkIfSelectedItemIsUsed(timesWhenSelectedItemIsUsed, startTimeMinutes, endTimeMinutes);
        if (!enableToChangeSelectedItem) {
            editmode = false;
        }
    });
}

function checkIfSelectedItemIsUsed(itemTimes, startTimeMinutes, endTimeMinutes) {
    let enableToChangeSelect = true;

    for (let i = 0; i < itemTimes.length; i++) {
        if ((startTimeMinutes >= itemTimes[i].StartTimeMinutes && endTimeMinutes <= itemTimes[i].EndTimeMinutes) ||
            (startTimeMinutes >= itemTimes[i].StartTimeMinutes && startTimeMinutes < itemTimes[i].EndTimeMinutes) ||
            (startTimeMinutes < itemTimes[i].StartTimeMinutes && endTimeMinutes > itemTimes[i].EndTimeMinutes) ||
            (endTimeMinutes > itemTimes[i].StartTimeMinutes && endTimeMinutes <= itemTimes[i].EndTimeMinutes)) {
            editedItem = false;
            enableToChangeSelect = false;
        }
    }

    return enableToChangeSelect;
}

function invalidDataWarning() {
    let identInput = $("#IdentSearchTInput").val();
    let customerInput = $("#customerTInput").val();
    let docTypeInput = $("#documentTypesTInput").val();

    let identText = identInput ? "" : $("#ChooseItemOrService").val() + ".<br />";
    let customerText = customerInput ? "" : $("#ChooseCustomer").val() + "<br />";
    let docTypeText = docTypeInput ? "" : $("#ChooseDocType").val() + "<br />";
    let timeText = handleTooltipTimeInputs() ? "" : $("#TimeStartGreaterThanTimeEnd").val() + ".";
    let warningText = identText + docTypeText + customerText + timeText;

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: warningText,
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#Confirm").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function fixedAssetInUseWarning() {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#FixedAssetAlreadyInUse").val(),
        buttons: [
            {
                icon: 'fa fa-check',
                text: $("#Confirm").val(),
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function createOrder(item) {
    let newAcKey;
    let identInput = $("#IdentSearchTInput").val();
    let customerInput = $("#customerTInput").val();
    let docTypeInput = $("#documentTypesTInput").val();
    let validTime = handleTooltipTimeInputs();

    if (!identInput || !customerInput || !docTypeInput || !validTime) {
        invalidDataWarning();
        return paw.utils.async.promise();
    }
    var d = paw.utils.async.defer();
    $.ajax({
        url: $("#SaveOrderInCalendarUrl").val(),
        method: "POST",
        data: {
            model: {
                ConsigneeId: item.Customer,
                Date: item.Date,
                DateValid: item.DateValid,
                DocType: docTypeInput,
                Department: $("#Department").val(),
                IsMadeByCalendar: true,
                ReceiverId: item.Customer,
                Items: [item]
            }
        },
        success: function (response) {
            if (response.Success) {
                newAcKey = response.data.AcKey;
                saveIdentCalendar(item, newAcKey).then(function () {
                    d.resolve();
                });
            }

            if (paw.utils.value.isSet(response.result) && response.result.Error) {
                fixedAssetInUseWarning();
                d.resolve();
            }
        }
    });
    return d.promise;
}

function saveIdentCalendar(item, acKey = "") {
    let docTypeInput = $("#documentTypesTInput").val();
    item.DocType = docTypeInput;
    item.IsMadeByCalendar = true;
    if (acKey) item.AcKey = acKey;
    
    var d = paw.utils.async.defer();
    $.ajax({
        url: $("#SaveIdentUrl").val(),
        method: "POST",
        data: {
            model: item
        },
        success: function (response) {
            if (response.success) {
                getOrdersByDate().then(function () {
                    d.resolve()
                });
            }

            if (paw.utils.value.isSet(response.result) && response.result.Error) {
                fixedAssetInUseWarning();
                d.resolve();
            }
        }
    });
    return d.promise;
}

function toggleTooltipClasses() {
    $("#calendar-tooltip .read-row").toggleClass("hidden");
    $("#calendar-tooltip .edit-row").toggleClass("hidden");
    $(".cal-tooltip-icons #pickColor").toggleClass("hidden");
    $(".cal-tooltip-icons #redirectToOrder").toggleClass("hidden");
    $(".tooltip-table #NewCustomer").toggleClass("hidden");
}

function closeCreateTooltip() {
    $(".calendar-events").click(function () {
        if ($("#tooltipCreateHelper").length > 0) {
            cancelCreateOrderItem()
        }
    });
}

function changeItemValue(acKey) {
    let url = new URL(window.location.href);
    let orderAcKey = decodeURI(url.searchParams.get("id"));

    if (acKey == orderAcKey) {
        editedItemFromOpenedOrder = true;
    }
    editedItem = true;
}

function updateCalendarItemCustomer(dropdownId, itemId) {
    let newValue = $("#" + dropdownId).val();
    let element = $("#" + itemId);

    $(element).find("#cal-items-customer").text("(" + newValue + ")");
}

function deleteItem(acKey, anNo) {
    let item = $("#d-" + acKey + "-" + anNo);
    let parentCell = item.parent("td");
    let isTools = $(calendarBy).val() === calendarByTools;

    $().customModal({
        title: "",
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteItemMessage").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost',
                action: async function () {
                    // Removes open tooltip
                    item.click();
                } 
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: async function () {
                    item.siblings("div.tooltip").remove();
                    item.remove();
                    if (parentCell.is(":empty")) parentCell.removeAttr("data-item");
                    checkOverlaping(isTools);
                    deletePosition(anNo, acKey, true);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function handleTooltipTimeInputs(durationChange = false) {
    let startTime = $("#startTimeTInput").val();
    let startTimeMinutes = convertTimeToMinutes(startTime);
    let duration = $("#durationTInput").val();
    let endTime = $("#endTimeTInput").val();
    let endTimeMinutes = convertTimeToMinutes(endTime);
    let startMinutes = 0;
    let durationMinutes = 0;
    let itemsTimes;

    if (durationChange && startTime && duration) {
        startMinutes = convertTimeToMinutes(startTime);
        durationMinutes = convertTimeToMinutes(duration);
        endTime = convertMinutesToTime(startMinutes + durationMinutes);
        $("#endTimeTInput").val(endTime);
    } else if (!durationChange && startTime && endTime) {
        startMinutes = convertTimeToMinutes(startTime);
        endMinutes = convertTimeToMinutes(endTime);
        duration = convertMinutesToTime(endMinutes - startMinutes);
        $("#durationTInput").val(duration);
    }

    if ($(calendarBy).val() === calendarByTools) {
        let tool = $("#toolTInput").val();
        itemsTimes = getItemsTimes(dailyTableToolsId, checkTimesForTool, tool);
    } else {
        let worker = $("#workerTInput").val();
        itemsTimes = getItemsTimes(dailyTableId, checkTimesForWorker, worker);
    }

    let enableToChangeTime = checkTimeWithItemsTimes(itemsTimes, startTimeMinutes, endTimeMinutes);
    if (!enableToChangeTime) return;

    if (endTime < startTime) {
        editedItem = false;
        return false;
    } else {
        editedItem = true;
        return true;
    }
}

function getItemsTimes(tableId, dataAttr = "", dataAttrVal = "", selected = "") {
    let openTooltipAcKey = $("td .tooltip").siblings("div.calendar-events").attr("id");
    let itemsTimes = [];
    let itemStartTime;
    let itemEndTime;

    if (!selected) {
        // Check is there other order items per worker/tool 
        $(tableId + " td[data-" + dataAttr + "='" + dataAttrVal + "'] div.calendar-events").each(function () {
            if ($(this).attr("id") == openTooltipAcKey) return;
            itemStartTime = convertTimeToMinutes($(this).closest("td").data("time"));
            itemEndTime = itemStartTime + ($(this).data("duration") * minutesPerRow);
            itemsTimes.push({ StartTimeMinutes: itemStartTime, EndTimeMinutes: itemEndTime });
        });
    } else {
        // Check when selected worker/tool from tooltip is used on whole calendar 
        $(tableId + " .cal-items-check").each(function () {
            if ($(this).data("tooltip-check") == selected) {
                itemStartTime = convertTimeToMinutes($(this).closest("td").data("time"));
                itemEndTime = itemStartTime + ($(this).closest(".calendar-events").data("duration") * minutesPerRow);
                itemsTimes.push({ StartTimeMinutes: itemStartTime, EndTimeMinutes: itemEndTime });
            }
        });
    }

    return itemsTimes;
}

function checkTimeWithItemsTimes(itemsTimes, startTimeMinutes, endTimeMinutes) {
    let enableToChangeTime = true;

    for (let i = 0; i < itemsTimes.length; i++) {
        if ((startTimeMinutes >= itemsTimes[i].StartTimeMinutes && startTimeMinutes < itemsTimes[i].EndTimeMinutes)
            || (endTimeMinutes > itemsTimes[i].StartTimeMinutes && endTimeMinutes <= itemsTimes[i].EndTimeMinutes)) {
            editedItem = false;
            enableToChangeTime = false;
        }
    }

    return enableToChangeTime;
}

var tooltipBottomDailyTableRows = 4;
var tooltipBottomTableRows = 2;
var tooltipBottomDateRangeTableRows = 4;
var tooltipTopDailyTableRows = 6;
var tooltipTopTableRows = 2;

function initTooltipTypeahead($element, localization, element, isCreate = false) {
    let url = $element.attr('dataUrl');
    let selector = isCreate ? "td #tooltipCreateHelper" : "#calendarTooltipHelper"

    $element.customTypeahead({
        value: "Id",
        display: "Name",
        minSearchLength: 0,
        focusOpen: true,
        parentElement: $element.closest("#calendar-tooltip").find(".tooltip-input-typeahead"),
        columns: [
            { name: localization.ident, value: "Ident", width: "35%", headerClass: "calendar-typeahead-th", cellClass: "calendar-typeahead-td" },
            { name: localization.name, value: "Name", width: "65%", headerClass: "calendar-typeahead-th", cellClass: "calendar-typeahead-td" }
        ],
        localization: { noResults: localization.noResults },
        url: url,
        urlRequestMethod: "POST",
        onSelect: function (item) {
            item = {
                id: item.Ident, name: item.Name, name_only: item.Name, price: item.SuppliersPrice, sellingPrice: item.SellingPrice, retailPrice: item.RetailPrice,
                quantity: 1, discount: item.Discount, rabate: item.Rebate, vat: item.VAT, vatCode: item.VATCode,
                measurementUnit: item.Unit, taxPrice: 0, basisForTax: item.SuppliersPrice - (item.SuppliersPrice / 100 * 10),
                priceForValue: 0, stock: item.Stock, wsPrice: item.WSPrice, wsPrice2: item.WSPrice2, prStPrice: item.PrStPrice,
                contractPrice: item.ContractPrice, contractPriceRabate: item.ContractPriceRabate,
                department: item.Department, costDrv: item.CostDrv, isActive: item.Active === "T",
                priceRate: item.PriceRate, setItemType: item.SetItemType, colorCode: item.ColorCode,
                prstTime: item.PrstTime, prstUMTime: item.PrstUMTime
            };

            if (item.colorCode == "#000000") {
                $("td #tooltipCreateHelper .cal-tooltip-icons").css("color", "white");
            }

            if (identDuration) {
                $(selector + " #durationTInput").val(convertMinutesToTime(item.prstTime));
                handleTooltipTimeInputs(true);
            } 

            $(".tooltip-header .custom-typeahead-display").removeClass("invalid-input");

            /* Update title on dropdown change */

            // Dropdown/input edit
            $(selector).append(element.data("title"));
            $(selector + " #ItemTitleT").text(item.name);
            $(selector + " #IdentSearchTInput").val(item.name);
            $(selector + " #IdentTInput").val(item.id);
            $(selector + " #PriceTInput").val(item.sellingPrice);
            $(selector + " #RebateTInput").val(item.rabate);
            $(selector + " #QuantityTInput").val(item.quantity);
            $(selector + " #UMTInput").val(item.measurementUnit);
            $(selector + " #VATTInput").val(item.vat);
            $(selector + " #VATCodeTInput").val(item.vatCode);
            $(selector + " #itemColorCode").val(item.colorCode);

            setAttributesOnIdentChange(selector, item);

            // Hover tooltip
            $("#calendar-tooltip #ItemTitleT").text(item.name);
            $("#calendar-tooltip #IdentSearchTInput").val(item.name);
            $("#calendar-tooltip #IdentTInput").val(item.id);
            $("#calendar-tooltip #PriceTInput").val(item.sellingPrice);
            $("#calendar-tooltip #RebateTInput").val(item.rabate);
            $("#calendar-tooltip #QuantityTInput").val(item.quantity);
            $("#calendar-tooltip #UMTInput").val(item.measurementUnit);
            $("#calendar-tooltip #VATTInput").val(item.vat);
            $("#calendar-tooltip #VATCodeTInput").val(item.vatCode);
            $("#calendar-tooltip #itemColorCode").val(item.colorCode);

            $(element).find("#cal-items-ident").text(item.name);

            $($element).closest(".tooltip-header").css("background", item.colorCode);

            element.attr("data-original-title", $("#calendarTooltipHelper")[0].innerHTML);
            element.removeAttr("data-title");
            $("#calendarTooltipHelper").empty();
            editedItem = true;
        }
    });
}

function setAttributesOnIdentChange(selector, item) {
    $(selector + " #IdentSearchTInput").attr("value", item.name);
    $(selector + " #IdentTInput").attr("value", item.id);
    $(selector + " #PriceTInput").attr("value", item.sellingPrice);
    $(selector + " #RebateTInput").attr("value", item.rabate);
    $(selector + " #QuantityTInput").attr("value", item.quantity);
    $(selector + " #UMTInput").attr("value", item.measurementUnit);
    $(selector + " #VATTInput").attr("value", item.vat);
    $(selector + " #VATCodeTInput").attr("value", item.vatCode);
    $(selector + " #itemColorCode").attr("value", item.colorCode);
}

function generateItemTooltip(item, order) {
    let itemHeaderStyle = item.ColorCode ? "background-color: " + item.ColorCode : "border-bottom: 1px solid black";
    let startTime = item.StartTime ? moment(item.StartTime).format("HH:mm") : "";
    let endTimePerRow = getEndTime(startTime, (item.PrstTime / minutesPerRow))
    let endTimeDuration = endTimePerRow ? endTimePerRow : "";
    let endTime = item.EndTime ? moment(item.EndTime).format("HH:mm") : endTimeDuration;
    let duration = convertMinutesToTime(item.PrstTime);
    let itemId = 'd-' + item.AcKey + '-' + item.AnNo;
    let headerColor = item.ColorCode == "#000000" ? "white" : "black";
    let fixedAsset = item.FixedAssetName ? item.FixedAssetName.trim() : "";
    fixedAsset = fixedAsset.length > 30 ? fixedAsset.substring(0, 30) + "..." : fixedAsset;
    let docType = order.DocTypeFullName.length > 30 ? order.DocTypeFullName.substring(0, 30) + "..." : order.DocTypeFullName;
    let customer = order.ConsigneeId.length > 20 ? order.ConsigneeId.substring(0, 20) + "..." : order.ConsigneeId;
    let note = "";
    let workerFullName = "";
    let date = moment(order.Date).format(dateFormat);
    let dateValid = moment(order.DateValid).format(dateFormat);
    let nameWithoutQuote = item.Name.replace(/'/g, "") // Signle quote will break itemTooltip string

    if (item.Note) note = item.Note.trim();
    if (item.DeliveryDeadline == null) item.DeliveryDeadline = "";
    if (item.Worker.trim()) {
        workerFullName = getFullName(item.Worker.trim(), allWorkers);
        workerFullName = workerFullName.length > 30 ? workerFullName.substring(0, 30) + "..." : workerFullName;
    } 

    let itemTooltip = `
        <div id="calendar-tooltip">
            <h5 class="tooltip-header" style="${itemHeaderStyle}">
            <span class="read-row" id="ItemTitleT" style="color: ${headerColor};">${nameWithoutQuote}</span>
            <div class="hidden edit-row">
                <input style="width: 85%" type="text" class="form-control typeahead_3" id="IdentSearchTInput"
                       value="${nameWithoutQuote}"
                       dataUrl="${$("#IdentUrl").val()}"
                       placeholder="${$("#ChooseItemOrService").val()}" autocomplete="off" />
            </div>
            <span class="cal-tooltip-icons" style="top: 22px; color: ${headerColor};">
                <a id="pickColor" class="a-outline m-r-md hidden">
                    <span class="dropdown color-picker-dropdown" data-toggle="dropdown" title="${$("#PickColor").val()}">
                        <p class="dropdown-toggle fa fa-solid fa-palette" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <input type="hidden" id="itemColorCode" value="${item.ColorCode}" />
                        </p>
                        <span class="dropdown-menu dropdown-menu-right rounded-0 box-shadow">
                            <span class="row">${$("#tooltipColors").html()}</span>
                        </span>
                    </span>
                </a>
                <a onclick="redirectToOrder(\`${item.AcKey}\`)" id="redirectToOrder" class="a-outline m-r-sm hidden"><i title="${$("#OpenOrder").val()}" class="fas fa-external-link"></i></a>
            </span>
            </h5>
            <table class="tooltip-table">
                <tbody>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#DocTypeLoc").val()}</b></td>
                        <td class="tooltip-cell read-row" id="docTypeT">${docType}</td>
                        <td class="tooltip-cell hidden edit-row">
                            <select id="documentTypesTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    title="" 
                                    onchange="changeItemValue(\`${item.AcKey}\`);" >
                                ${$("#DocumentTypesEdit").html()}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#Customer").val()}</b></td>
                        <td class="tooltip-cell read-row" id="customerT">${customer}</td>
                        <td class="tooltip-cell hidden edit-row partner-cell">
                            <select id="customerTInput"
                                    class="form-control selectpicker selectpickerAPI calendar-dropdown-btn"
                                    data-live-search="true"
                                    data-api-url="${$("#BuyerDropdownValues").val()}"
                                    title=""
                                    onchange="changeItemValue(\`${item.AcKey}\`); updateCalendarItemCustomer(\`customerTInput\`, \`${itemId}\`);">
                                <option value="${order.ConsigneeId}">${order.ConsigneeId}</option>
                                ${$("#CustomersEdit").html()}
                            </select>
                            <div id="NewCustomer" class="addable-button hidden">
                                <button type="button" title="${$("#AddingNewPartner").val()}" class="btn createNewButton" onclick="openSubjectModal(\`customerTInput\`, \`${true}\`)">
                                    <i class="fas fa-building"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#TaBegin").val()}</b></td>
                        <td class="tooltip-cell read-row" id="dateT">${date} (<span id="startTimeT">${startTime}</span>)</td>
                        <td class="tooltip-cell hidden edit-row tooltip-times" style="white-space: nowrap;">
                            <input id="dateTInput" onblur="changeItemValue(\`${item.AcKey}\`);" type="text" value="${date}" class="form-control datepicker" autocomplete="off">
                            <input id="startTimeTInput" onblur="changeItemValue(\`${item.AcKey}\`); handleTooltipTimeInputs(true);" type="time" value="${startTime}" class="form-control" autocomplete="off">
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#TaEnd").val()}</b></td>
                        <td class="tooltip-cell read-row" id="dateValidT">${dateValid} (<span id="endTimeT">${endTime}</span>)</td>
                        <td class="tooltip-cell hidden edit-row tooltip-times">
                            <input id="dateValidTInput" onblur="changeItemValue(\`${item.AcKey}\`);" type="text" value="${dateValid}" class="form-control datepicker" autocomplete="off">
                            <input id="endTimeTInput" onblur="changeItemValue(\`${item.AcKey}\`); handleTooltipTimeInputs();" type="time" value="${endTime}" class="form-control" autocomplete="off">
                        </td>
                    </tr>
                    <tr style="height: 20px;"></tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#ContractorLoc").val()}</b></td>
                        <td class="tooltip-cell read-row" id="workerT">${workerFullName}</td>
                        <td class="tooltip-cell hidden edit-row">
                            <select id="workerTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    data-live-search="true"
                                    title=""
                                    onchange="changeItemValue(\`${item.AcKey}\`);">
                                ${$("#ContractorsEdit").html()}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#Means").val()}</b></td>
                        <td class="tooltip-cell read-row" id="toolT">${fixedAsset}</td>
                        <td class="tooltip-cell hidden edit-row">
                            <select id="toolTInput"
                                    class="form-control selectpicker calendar-tooltip-dropdown"
                                    data-live-search="true"
                                    title=""
                                    onchange="changeItemValue(\`${item.AcKey}\`);">
                                ${$("#FixedAssetsEdit").html()}
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell"><b>${$("#CalendarNote").val()}</b></td>
                        <td class="tooltip-cell read-row" id="noteT">${note}</td>
                        <td class="tooltip-cell hidden edit-row">
                            <textarea id="noteTInput" onchange="changeItemValue(\`${item.AcKey}\`);" type="text" value="${note}" class="form-control" style="resize: none;"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td class="tooltip-cell" style="border-bottom-left-radius: 4px;"><b>${$("#OrderSupplierCode").val()}</b></td>
                        <td class="tooltip-cell" id="AcKeyDisplayT">${order.AcKeyDisplay}</td>
                    </tr>
                    <tr style="display: none">
                        <td>
                            <input id="DeliveryDeadlineTInput" hidden value="${item.DeliveryDeadline}">
                            <input id="durationTInput" hidden value="${duration}">
                            <input id="IdentTInput" hidden value="${item.Ident}">
                            <input id="LastPriceTInput" hidden value="${item.LastPrice}">
                            <input id="PriceTInput" hidden value="${item.Price}">
                            <input id="RebateTInput" hidden value="${item.Rebate}">
                            <input id="QuantityTInput" hidden value="${item.Quantity}">
                            <input id="SetItemRTPriceTInput" hidden value="${item.SetItemRTPrice}">
                            <input id="SetItemWSPriceTInput" hidden value="${item.SetItemWSPrice}">
                            <input id="SetItemWSPrice2TInput" hidden value="${item.SetItemWSPrice2}">
                            <input id="TotalPriceTInput" hidden value="${item.TotalPrice}">
                            <input id="UMTInput" hidden value="${item.UM}">
                            <input id="ValueTInput" hidden value="${item.Value}">
                            <input id="VATTInput" hidden value="${item.VAT}">
                            <input id="VATCodeTInput" hidden value="${item.VATCode}">
                        </td>                        
                    </tr>
                </tbody>
            </table>
            <div class="tooltip-input-typeahead custom-typeahead-wrapper" style="position:absolute;height:80%;width:323px;left:11px;top:50px"></div>
        </div>`;

    return itemTooltip;
}

// Drag and drop/resize update
function updateItemTooltip(element, startTime, endTime, startDate, endDate, worker, tool, isTools) {
    let workerFullName = ""
    let startDateTime = `${startDate} (${startTime})`;
    let endDateTime = `${endDate} (${endTime})`;

    $("#calendarTooltipHelper").append(element.data("title"));
    $("#calendarTooltipHelper .tooltip-table tbody tr #dateT").text(startDateTime);
    $("#calendarTooltipHelper .tooltip-table tbody tr #dateValidT").text(endDateTime);

    if (worker) workerFullName = getFullName(worker, allWorkers);

    if (isTools) {
        $("#calendarTooltipHelper .tooltip-table tbody tr #toolT").text(tool);
    } else {
        $("#calendarTooltipHelper .tooltip-table tbody tr #workerT").text(workerFullName);
    }

    element.attr("data-original-title", $("#calendarTooltipHelper")[0].innerHTML);
    element.removeAttr("data-title");
    $("#calendarTooltipHelper").empty();
}

// Item edit update
function updateTooltipAfterEdit(item, element, tool, durationTime, docTypeFullName) {
    let workerFullName = "";
    let startDateTime = `${moment(item.Date).format(dateFormat)} (${item.StartTime})`;
    let endDateTime = `${moment(item.DateValid).format(dateFormat)} (${item.EndTime})`;

    if (item.Worker) workerFullName = getFullName(item.Worker, allWorkers);

    $("#calendarTooltipHelper").append(element.data("title"));
    $("#calendarTooltipHelper .tooltip-table tbody tr #customerT").text(item.Customer);
    $("#calendarTooltipHelper .tooltip-table tbody tr #workerT").text(workerFullName);
    $("#calendarTooltipHelper .tooltip-table tbody tr #toolT").text(tool);
    $("#calendarTooltipHelper .tooltip-table tbody tr #dateT").val(startDateTime);
    $("#calendarTooltipHelper .tooltip-table tbody tr #dateValidT").val(endDateTime);
    $("#calendarTooltipHelper .tooltip-table tbody tr #durationTInput").val(durationTime);
    $("#calendarTooltipHelper .tooltip-table tbody tr #noteT").val(item.Note);
    $("#calendarTooltipHelper .tooltip-table tbody tr #docTypeT").val(item.DocType);

    $("#calendar-tooltip .tooltip-table tbody tr #customerT").text(item.Customer);
    $("#calendar-tooltip .tooltip-table tbody tr #workerT").text(workerFullName);
    $("#calendar-tooltip .tooltip-table tbody tr #toolT").text(tool);
    $("#calendar-tooltip .tooltip-table tbody tr #dateT").text(startDateTime);
    $("#calendar-tooltip .tooltip-table tbody tr #dateValidT").text(endDateTime);
    $("#calendar-tooltip .tooltip-table tbody tr #noteT").text(item.Note);
    $("#calendar-tooltip .tooltip-table tbody tr #docTypeT").text(docTypeFullName);

    element.attr("data-original-title", $("#calendarTooltipHelper")[0].innerHTML);
    element.removeAttr("data-title");
    $("#calendarTooltipHelper").empty();
}

function initTooltipPosition(isTools, isInit) {
    let daily = isTools ? dailyTableToolsId : dailyTableId;
    let weekly = isTools ? weeklyTableToolsId : weeklyTableId;
    let monthly = isTools ? monthlyTableToolsId : monthlyTableId;
    let calType = $(calendarTypeId).val();

    if (calType === dailyCalendar) {
        setTooltipPosition(daily, isInit, true);
    } else if (calType === weeklyCalendar) {
        setTooltipPosition(weekly, isInit, false);
    } else if (calType === monthlyCalendar) {
        setTooltipPosition(monthly, isInit, false);
    }
}

function setTooltipPosition(tableId, isInit, isDaily) {
    $(tableId + " tbody td:not(.hidden) .calendar-events").each(function () {
        changeTooltipPosition(tableId, $(this), isDaily, isInit);
    });
}

function changeTooltipPosition(tableId, element, isDaily, isInit) {
    let rowsNum = $(tableId + " tbody tr:not(.hidden)").length;
    let cellsNum = $(tableId + " tbody tr:first-child td:not(.set-wh-hours, .hidden)").length;

    let rowPositionDaily = element.closest("tr").index() + 1;
    let rowPositionWM = element.closest("tr").siblings(":visible").addBack().index(element.closest("tr")) + 1;
    let rowPosition = isDaily ? rowPositionDaily : rowPositionWM;

    let cellPositionDaily = element.closest("td").siblings(":visible").addBack().index(element.closest("td"));
    let cellPositionWM = element.closest("td").index() + 1;
    let cellPosition = isDaily ? cellPositionDaily : cellPositionWM;

    let tooltipBottomRows = (tableId === dailyTableId || tableId === dailyTableToolsId) ? tooltipBottomDailyTableRows : tooltipBottomTableRows;
    let tooltipTopRows = (tableId === dailyTableId || tableId === dailyTableToolsId) ? tooltipTopDailyTableRows : tooltipTopTableRows;
    let isOneColumn = false;

    if (isDaily) {
        isOneColumn = $(tableId + " thead tr th.cell-width:not(.hidden)").length > 1 ? false : true;
    } 

    // Weekly and monthly tooltip position for item that last more than 1 day
    if (rowPosition < tooltipBottomDateRangeTableRows && element.hasClass("events-range")) {
        setTooltipPlacement(element, "bottom", isInit);
        return;
    }
    if (element.hasClass("events-range")) {
        setTooltipPlacement(element, "top", isInit);
        return;
    }

    if (rowPosition < tooltipBottomRows || isOneColumn) {
        setTooltipPlacement(element, "bottom", isInit);
    } else if (rowsNum - rowPosition < tooltipTopRows) {
        if (isDaily) {
            setTooltipPlacement(element, "top", isInit);
        } else if (!isDaily && rowsNum >= tooltipTopTableRows) {
            setTooltipPlacement(element, "top", isInit);
        }
    } else if (cellsNum == cellPosition) {
        setTooltipPlacement(element, "left", isInit);
    } else {
        if (tableId == dailyTableId && tableId == dailyTableToolsId) {
            setTooltipPlacement(element, "top", isInit);
        } else {
            setTooltipPlacement(element, "right", isInit);
        }
    }
}
 
function setTooltipPlacement(element, placement, isInit) {
    if (element.hasClass("calendar-events")) {
        if (isInit) {
            element.attr("data-placement", placement);
        } else {
            element.attr("data-placement", placement);
            $('[data-toggle="tooltip"]').tooltip();
            if (element.data("bs.tooltip")) {
                element.data("bs.tooltip").options.placement = placement;
            }
        }
    }
}
//#endregion TOOLTIP

//#region FILTERS
function filterTables() {
    let workers = $("#Contractors");
    let depts = $("#Departments");
    let tools = $("#FixedAssets");
    let isTools = $(calendarBy).val() === calendarByTools;

    if (isTools) {
        workers.attr("onchange", "getOrdersByDate()");
        depts.attr("onchange", "getOrdersByDate()");
        tools.attr("onchange", "filterTools()");
    } else {
        workers.attr("onchange", "filterWorkers()");
        depts.attr("onchange", "filterWorkers()");
        tools.attr("onchange", "getOrdersByDate()");
    }
}

function filterWorkers() {
    let workers = $("#Contractors").val();
    let depts = $("#Departments").val();
    let isTools = $(calendarBy).val() === calendarByTools;

    hideAll();

    if (!workers && !depts || (workers.length == 0 && depts.length == 0)) { // No filters selected
        showAll();
        showHiddenDaily();

    } else if (workers && (!depts || depts.length == 0)) { // Only workers filters selected
        $.each(workers, function (index, item) {
            filterDataWorkers(item);
            showHiddenDaily();
        });

    } else { // Departments (and workers) filters selected
        deptWorkers = [];

        $.each(depts, function (index, item) {
            filterDataDepts(item);
        });

        $("#daily-table thead th:not(.hidden, .set-wh-hours)").each(function () {
            worker = $(this).data("worker");
            if (worker) {
                deptWorkers.push(worker.toString());
            }
        });

        if (deptWorkers && workers) {
            hideAll();
            deptWorkers = deptWorkers.filter(element => workers.includes(element));

            $.each(deptWorkers, function (index, item) {
                filterDataWorkers(item);
            });
        }

        // Handling empty table
        if (deptWorkers.length == 0) {
            hideEmpty();
        } else {
            showHiddenDaily();
        }
    }

    getOrdersByDate();
    updateElementsWidth(isTools);
    updateDivsHeightWM(isTools);
    initTooltipPosition(isTools, false, false);
}

function filterTools() {
    let fixedAssets = $("#FixedAssets").val();
    let isTools = $(calendarBy).val() === calendarByTools;

    hideAllTools();

    if (!fixedAssets) {
        showAllTools();
    }

    if (fixedAssets) {
        filterDataTools(fixedAssets);
    }

    getOrdersByDate();
    updateElementsWidth(isTools);
    updateDivsHeightWM(isTools);
    initTooltipPosition(isTools, false, false);
}

function filterDataWorkers(worker) {
    $(dailyTableId + " thead th[data-worker='" + worker + "']").removeClass("hidden");
    $(dailyTableId + " tbody tr td[data-worker='" + worker + "']").removeClass("hidden");
    $(weeklyTableId + " tbody tr td[data-worker='" + worker + "']").parent("tr").removeClass("hidden");
    $(monthlyTableId + " tbody tr td[data-worker='" + worker + "']").parent("tr").removeClass("hidden");
}

function filterDataTools(fixedAssets) {
    $.each(fixedAssets, function (index, tool) {
        $(dailyTableToolsId + " thead th[data-tool='" + tool.trim() + "']").removeClass("hidden");
        $(dailyTableToolsId + " tbody tr td[data-tool='" + tool.trim() + "']").removeClass("hidden");
        $(weeklyTableToolsId + " tbody tr td[data-tool='" + tool.trim() + "']").parent("tr").removeClass("hidden");
        $(monthlyTableToolsId + " tbody tr td[data-tool='" + tool.trim() + "']").parent("tr").removeClass("hidden");
    });
}

function filterDataDepts(dept) {
    $(dailyTableId + " thead th[data-dept='" + dept + "']").removeClass("hidden");
    $(dailyTableId + " tbody tr td[data-dept='" + dept + "']").removeClass("hidden");
    $(weeklyTableId + " tbody tr td[data-dept='" + dept + "']").parent("tr").removeClass("hidden");
    $(monthlyTableId + " tbody tr td[data-dept='" + dept + "']").parent("tr").removeClass("hidden");
}

function hideAll() {
    $(dailyTableId + " thead th:not(:first-child)").addClass("hidden");
    $(dailyTableId + " tbody tr td:not(:first-child)").addClass("hidden");
    $(weeklyTableId + " tbody tr").addClass("hidden");
    $(monthlyTableId + " tbody tr").addClass("hidden");
}

function hideAllTools() {
    $(dailyTableToolsId + " thead th:not(:first-child)").addClass("hidden");
    $(dailyTableToolsId + " tbody tr td:not(:first-child)").addClass("hidden");
    $(weeklyTableToolsId + " tbody tr").addClass("hidden");
    $(monthlyTableToolsId + " tbody tr").addClass("hidden");
}

function showAll() {
    $(dailyTableId + " thead th:not(:first-child)").removeClass("hidden");
    $(dailyTableId + " tbody tr td:not(:first-child)").removeClass("hidden");
    $(weeklyTableId + " tbody tr").removeClass("hidden");
    $(monthlyTableId + " tbody tr").removeClass("hidden");
}

function showAllTools() {
    $(dailyTableToolsId + " thead th:not(:first-child)").removeClass("hidden");
    $(dailyTableToolsId + " tbody tr td:not(:first-child, .tooltip-cell)").removeClass("hidden");
    $(weeklyTableToolsId + " tbody tr").removeClass("hidden");
    $(monthlyTableToolsId + " tbody tr").removeClass("hidden");

    $(dailyTableToolsId + " tbody tr:last-child").last().addClass("hidden"); 
    $(weeklyTableToolsId + " tbody tr:last-child").addClass("hidden");
    $(monthlyTableToolsId + " tbody tr:last-child").addClass("hidden");
}

function hideEmpty() {
    $(dailyTableId + " tbody tr").addClass("hidden");
    $(dailyTableId + " tbody tr:last-child").removeClass("hidden");

    $(weeklyTableId + " tbody tr").addClass("hidden");
    $(weeklyTableId + " tbody tr:last-child").removeClass("hidden");

    $(monthlyTableId + " tbody tr").addClass("hidden");
    $(monthlyTableId + " tbody tr:last-child").removeClass("hidden");
}

function showHiddenDaily() {
    $(dailyTableId + " tbody tr").removeClass("hidden");
    $(dailyTableId + " tbody tr:last-child").addClass("hidden");
}

function updateElementsWidth(isTools) {
    if (!$(calendarTypeId).val() === dailyCalendar) return;

    let tableId = isTools ? dailyTableToolsId : dailyTableId;
    let cellWidth = $(tableId + " td.cell-width:not(.hidden)").first().width();
    let itemWidth = cellWidth - 4;
    let elements = $(tableId + " td:not(.hidden) .calendar-events," + tableId + " td:not(.hidden) .calendar-absence");

    if (cellWidth > initCellWidth) {
        elements.each(function () {
            $(this).css("width", "-webkit-fill-available");
            $(this).css("z-index", "1");
            if ($(this).is(".absence.calendar-events")) {
                $(this).css("margin-left", (itemWidth / 3 - 10) + "px");
            }
        });
    } else {
        elements.each(function () {
            $(this).css("width", "");
            $(this).css("margin-left", "");
            $(this).css("z-index", "1");
        });
    }
}

function updateDivsHeightWM(isTools) {
    let tableId;
    let weekly = isTools ? weeklyTableToolsId : weeklyTableId;;
    let monthly = isTools ? monthlyTableToolsId : monthlyTableId;;
    let calType = $(calendarTypeId).val();

    if (calType === dailyCalendar) {
        return;
    } else if (calType === weeklyCalendar) {
        tableId = weekly;
    } else if (calType === monthlyCalendar) {
        tableId = monthly;
    }

    $(tableId + " tbody tr:not(.hidden) td.cell-width > div:not(.order-cal-header)").css("height", cellHeightWM + "px");
    let divHeight = $(tableId + " tr:not(.hidden) td.cell-width").first().height();

    if (divHeight > cellHeightWM) {
        $(tableId + " tbody tr:not(.hidden) td.cell-width > div:not(.order-cal-header)").css("height", divHeight + "px");
    }
}

function displayCalendarTable() {
    let displayBy = $(calendarBy).val();
    let calType = $(calendarTypeId).val();

    if (displayBy == calendarByEmployees) {
        if (calType == dailyCalendar) {
            showSelectedCalendar(daily);
        }

        if (calType == weeklyCalendar) {
            showSelectedCalendar(weekly);
        }

        if (calType == monthlyCalendar) {
            getOrdersByDate();
            return;
        }

        filterWorkers();

    } else if (displayBy == calendarByTools) {
        if (calType == dailyCalendar) {
            showSelectedCalendar(dailyTools);
        }

        if (calType == weeklyCalendar) {
            showSelectedCalendar(weeklyTools);
        }

        if (calType == monthlyCalendar) {
            getOrdersByDate();
            return;
        }

        filterTools();
    }
}

function showSelectedCalendar(id) {
    $(".calendar-wrapper").addClass("hidden");
    $("#" + id).removeClass("hidden");
}


function saveCalendarFilters() {
    let filters = {
        CalendarDisplay: $("#CalendarDisplay").val(),
        Contractors: $("#Contractors").val(),
        FixedAssets: $("#FixedAssets").val(),
        Customers: $("#Customers").val(),
        Departments: $("#Departments").val()
    };
    localStorage.setItem('CalendarFilters', JSON.stringify(filters));
}


function getCalendarFilters() {
    let filtersObject = localStorage.getItem('CalendarFilters');

    if (filtersObject !== null) {
        let filters = JSON.parse(filtersObject);
        for (filter in filters) {
            if (filters[filter]) 
                $("#" + filter).val(filters[filter]);
        }

        $(".selectpicker").selectpicker("refresh");
        filterTables();

        if ($(".custom-scrollable-tabs").children("#" + $("#Calendar").val()).hasClass("active")) {
            displayCalendarTable();
        }
    }
}

window.onbeforeunload = function () {
    if ($(".custom-scrollable-tabs").children("#" + $("#Calendar").val()).hasClass("active")) {
        saveCalendarFilters();
    }
}
//#endregion FILTERS

$(".close-btn").on("click", function () {
    if (redirectToCreateOrder) {
        window.location.href = $("#RedirectToCreateOrderURL").val();
        return;
    }

    hideCalendarElements();
    showMainElements();
    $(".order-sidebar-tabs").removeClass("hidden");
    $(".calendar-display-tab").addClass("hidden");
    $(".custom-scrollable-tabs li").first().addClass("active");
    $(".custom-scrollable-tabs").children("#" + $("#Calendar").val()).removeClass("active");
    $(".calendar-header-border").addClass("hidden");
    $("#calendar #select2-calendar-period-container").removeClass("select2-calendar-period");
    $("#tabsListDropdown").removeClass("hidden");
    $(".scroller").removeClass("hidden");

    if ($("#AcKey").val()) {
        let miniCalendarWrapperId = $(miniCalendarTypeId).val() == calendarByEmployees ? miniCalendarWrapperWorkers : miniCalendarWrapperTools;
        $("#" + miniCalendarWrapperId).removeClass("hidden");
        $("#calendar").removeClass("active in");
        $("#mini-calendar").addClass("active in");
        $("a[href='#home']").parent().removeClass("active");
        $("a[href='#mini-calendar']").parent().addClass("active");
    } else {
        $("#calendar").addClass("active in");
        $("#mini-calendar").removeClass("active in");
        $("a[href='#home']").parent().removeClass("active");
        $("a[href='#calendar']").parent().addClass("active");
        $(".calendar-period-wrapper").addClass("m-t-sm");
    }

    // If edited item from order or created new one
    if (editedItemFromOpenedOrder) {
        $("table#invoice > tbody").empty();
        loadInvoiceItems();
        editedItemFromOpenedOrder = false;
    }

    setGlobalHelpUrl($("#BuyerOrderPositionsUrlHelp").val());
});

$(calendarTypeId).on('change', function (e) {
    var activeWeek = $(".ui-state-active").closest("tr");
    var activeMonth = $(".ui-state-active").closest("tbody").children("tr");

    hideMainElements();
    showCalendarElements();
    $(".activeDay").removeClass("activeDay");

    if ($(this).val() === dailyCalendar) {
        displayCalendarTable();
        setClassesForActiveDay(activeWeek, activeMonth);

    } else if ($(this).val() === weeklyCalendar) {
        displayCalendarTable();
        setClassesForActiveWeek(activeWeek, activeMonth);

    } else if ($(this).val() === monthlyCalendar) {
        setClassesForActiveMonth(activeWeek, activeMonth);
        getOrdersByDate();
        return;
    }
});

function closeTooltipOnClick() {
    $(".calendar-events").on("mouseenter", function (event) {
        $("html:not(.tooltip)").on('click', function (e) {
            if (openTooltip && $(e.target).closest("div.tooltip").length == 0) {
                let id = $(".tooltip:not(.createT)").siblings(".calendar-events").attr("id");
                $("#" + id).find("#cal-edit-button").click();
                $("#" + id).find(".cal-items-icons").addClass("hidden");
                $("#" + id).find(".icons-under").addClass("hidden");
            }
        });
    });
}

function doubleClickItem() {
    $(".calendar-events").dblclick(function (event) {
        if ($(event.target).hasClass("fa-pencil-alt")) return;
        redirectToOrder($(this).attr("id").split("-")[1]);
    });
}

//#region COLORS
var shadeNum = 0.5;

function hex2(c) {
    c = Math.round(c);
    if (c < 0) c = 0;
    if (c > 255) c = 255;

    var s = c.toString(16);
    if (s.length < 2) s = "0" + s;

    return s;
}

function color(r, g, b) {
    return "#" + hex2(r) + hex2(g) + hex2(b);
}

function shade(col, light) {
    var r = parseInt(col.substr(1, 2), 16);
    var g = parseInt(col.substr(3, 2), 16);
    var b = parseInt(col.substr(5, 2), 16);

    if (light < 0) {
        r = (1 + light) * r;
        g = (1 + light) * g;
        b = (1 + light) * b;
    } else {
        r = (1 - light) * r + light * 255;
        g = (1 - light) * g + light * 255;
        b = (1 - light) * b + light * 255;
    }

    return color(r, g, b);
}

function rgbToHex(rgbCSS) {
    let rgb = rgbCSS.split("(")[1].split(")")[0];
    rgb = rgb.split(",");

    return color(rgb[0], rgb[1], rgb[2]);
}

function changeItemColor(item) {
    let color = rgbToHex($(item).css("background-color"));
    $(item).closest(".tooltip-header").css("background", color);
    $(item).closest(".tooltip").siblings(".calendar-events").css({ "background": shade(color, shadeNum), "border-left-color": color });
    $("#itemColorCode").val(color);
    editedItem = true;
}
//#endregion COLORS

//#region SIDE CALENDAR STYLING
function styleCurrentPeriod(activeWeek, activeMonth) {
    let calType = $(calendarTypeId).val();

    if (calType == dailyCalendar) {
        setClassesForActiveDay(activeWeek, activeMonth)
    }

    if (calType == weeklyCalendar) {
        setClassesForActiveWeek(activeWeek, activeMonth);
    }

    if (calType == monthlyCalendar) {
        setClassesForActiveMonth(activeWeek, activeMonth);
    }
}

function setClassesForActiveDay(activeWeek, activeMonth) {
    activeWeek.addClass("calendar-bcg-trasnp");
    activeWeek.removeClass("calendar-bcg");
    activeMonth.addClass("calendar-bcg-trasnp");
    activeMonth.removeClass("calendar-bcg");
}

function setClassesForActiveWeek(activeWeek, activeMonth) {
    activeMonth.removeClass("calendar-bcg-trasnp");
    activeMonth.removeClass("calendar-bcg");
    activeWeek.addClass("calendar-bcg");
}

function setClassesForActiveMonth(activeWeek, activeMonth) {
    activeWeek.removeClass("calendar-bcg-trasnp");
    activeWeek.removeClass("calendar-bcg");
    activeMonth.removeClass("calendar-bcg-trasnp");
    activeMonth.addClass("calendar-bcg");
}
//#endregion SIDE CALENDAR STYLING

//#region DATETIME HELPERS
function getMonday(d) {
    d = new Date(d);
    var day = d.getDay(),
        diff = d.getDate() - day + (day == 0 ? -6 : 1);
    return new Date(d.setDate(diff));
}

function roundDuration(time) {
    return (Math.round(time / minutesPerRow) * minutesPerRow);
}

function roundTime(time) {
    if (!time) return;

    const [hoursStr, minutesStr] = getTime(time).split(":");
    let hours = Number(hoursStr);
    const minutes = Number(minutesStr);
    const roundedMinutes = Math.round(minutes / minutesPerRow) * minutesPerRow % 60;

    if (minutes > 45 && roundedMinutes === 0) {
        hours++;
    }

    return `${formatTimeForCell(hours)}:${formatTimeForCell(roundedMinutes)}`;
}

function formatTimeForCell(time) {
    return time.toString().padStart(2, '0')
}

function setWorkShifts(shifts) {
    $(dailyTableId + " td").removeClass("has-planned-time");
    $.each(shifts, function (i, item) {
        let worker = item.Worker;
        let timeStart = getTime(item.TimeStart);
        let timeEnd = getTime(item.TimeEnd);
        let duration = (convertTimeToMinutes(timeEnd) - convertTimeToMinutes(timeStart)) / minutesPerRow;
        let workCells = $(dailyTableId + " td[data-worker='" + worker + "'][data-time='" + timeStart + "']")
        let trIndex = workCells.closest("tr").index();
        let tdIndex = workCells.index();

        for (var i = 0; i < duration; i++) {
            $(dailyTableId + " tr:nth-child(" + (trIndex + 1 + i) + ") td:nth-child(" + (tdIndex + 1) + ")")
                .addClass("has-planned-time");
        }
    });
}

function getEndTime(time, rowIterator) {
    if (time) {
        let startHours = time.split(":")[0] * 60;
        let startMinutes = time.split(":")[1];
        let durationMinutes = minutesPerRow * rowIterator;
        let totalMinutes = parseInt(startHours) + parseInt(parseInt(startMinutes) + durationMinutes);
        let d = new Date();
        d.setHours(0, 0, 0, 0);
        d.setMinutes(d.getMinutes() + (parseFloat(totalMinutes)));
        let endTime = moment(d.getTime()).format("HH:mm");

        return endTime;
    }
}

function getEndDate(startDate, dateRange) {
    if (dateRange > 1) {
        let [dayStart, monthStart, yearStart] = startDate.split(".");
        dayStart = parseInt(dayStart) + parseInt(dateRange - 1);
        return moment(new Date(yearStart, monthStart - 1, dayStart)).format(dateFormat);
    } else {
        return startDate;
    }
}
//#endregion DATETIME HELPERS

//#region NAME HELPERS
function getFullName(worker, allWorkers) {
    for (let i = 0; i < allWorkers.length; i++) {
        if (worker == allWorkers[i].Worker) {
            return workerFullName = allWorkers[i].FullName;
        }
    }
}

function getFixedAssetName(fixedAsset, allFixedAssets) {
    for (let i = 0; i < allFixedAssets.length; i++) {
        if (fixedAsset == allFixedAssets[i].InventNum) {
            return fixedAssetName = allFixedAssets[i].Name;
        }
    }
}
//#endregion NAME HELPERS

//#region SHOW/HIDE CALENDAR BODY
function hideCalendarElements() {
    $("#calendar-buttons-tabbed").addClass("hidden");
    $("#calendar-doc-head").addClass("hidden");
    $("#daily-calendar-body").addClass("hidden");
    $("#daily-calendar-body-tools").addClass("hidden");
    $("#monthly-calendar-body").addClass("hidden");
    $("#monthly-calendar-body-tools").addClass("hidden");
    $("#weekly-calendar-body").addClass("hidden");
    $("#weekly-calendar-body-tools").addClass("hidden");
}

function showCalendarElements() {
    $("#calendar-buttons-tabbed").removeClass("hidden");
    $("#calendar-doc-head").removeClass("hidden");
}

function hideMainElements() {
    $("#main-buttons-tabbed").addClass("hidden");
    $("#main-doc-head").addClass("hidden");
    $("#main-doc-body").addClass("hidden");
    $("#main-doc-footer").addClass("hidden");
}

function showMainElements() {
    $("#main-buttons-tabbed").removeClass("hidden");
    $("#main-doc-head").removeClass("hidden");
    $("#main-doc-body").removeClass("hidden");
    $("#main-doc-footer").removeClass("hidden");
}
//#endregion SHOW/HIDE CALENDAR BODY

//#region MINI CALENDAR
var miniCalendarWrapperWorkers = "mini-calendar-workers";
var miniCalendarWrapperTools = "mini-calendar-tools";
var miniCalendarTableWorkersId = "#mini-table-workers";
var miniCalendarTableToolsId = "#mini-table-tools";
var miniCalendarTypeId = "#mini-calendar-dropdown";
var workersFilterMini = [];
var toolsFilterMini = [];

function getOrdersByDateMini() {
    let acKey = $("#AcKey").val();
    let calType = $("#DocTypeSelect").val();
    let date = moment($("#cal-datepicker").val(), "DD.MM.YYYY").toISOString();
    let workers = [];
    let depts = [];
    let customers = [];
    let tools = [];
    let docType = [];
    workersFilterMini = [];
    toolsFilterMini = [];

    if (invoiceItems.length > 0) {
        $.each(invoiceItems, function (i, item) {
            if (item.Worker && item.Worker !== "") {
                workersFilterMini.push(item.Worker);
            }
            if (item.FixedAsset && item.FixedAsset !== "") {
                toolsFilterMini.push(item.FixedAsset);
            }
            workersFilterMini = [...new Set(workersFilterMini)];
            toolsFilterMini = [...new Set(toolsFilterMini)];
        });
    }

    let calendarRequest = {
        Date: date,
        CalendarType: calType,
        DocTypes: docType,
        Workers: workers,
        Departments: depts,
        Customers: customers,
        FixedAssets: tools
    };

    $.ajax({
        traditional: true,
        type: "GET",
        url: $("#GetOrdersByDateUrl").val(),
        async: true,
        data: calendarRequest,
        success: function (data) {
            clearTableMini();
            hideAllWorkersMini();
            hideAllToolsMini();

            showWorkersMini(workersFilterMini);
            showToolsMini(toolsFilterMini);

            setAbsencesMini(data.Absences);
            setCalendarDataMini(data.Orders);

            unblurActiveItems(acKey);

            checkOverlapingMiniCalendar();
        },
        error: function (error) {
            console.log(error)
        }
    });
}

function displayCalendarMini() {
    if ($(miniCalendarTypeId).val() == calendarByEmployees) {
        showSelectedMiniCalendar(miniCalendarWrapperWorkers, miniCalendarTableWorkersId);
        getOrdersByDateMini();
    } else if ($(miniCalendarTypeId).val() == calendarByTools) {
        showSelectedMiniCalendar(miniCalendarWrapperTools, miniCalendarTableToolsId);
        getOrdersByDateMini();
    }
}

function showSelectedMiniCalendar(id, tableId) {
    $(".mini-calendar-wrapper").addClass("hidden");
    $("#" + id).removeClass("hidden");
    initScroll(tableId);
}

function miniCalendarNavigation() {
    var calendarDatepickerMini = $("#cal-datepicker")
    calendarDatepickerMini.val($("#Date").val());
    calendarDatepickerMini.datepicker();
    var date = calendarDatepickerMini.datepicker("getDate");

    $(".next-day, .prev-day").on("click", function () {
        let dayAdvanced = 1;
        if ($(this).hasClass("prev-day")) dayAdvanced = -1;

        date.setDate(date.getDate() + dayAdvanced);
        calendarDatepickerMini.datepicker("setDate", date);
    });

    $("#cal-datepicker").on("change", function () {
        getOrdersByDateMini();
    });
}

function clearTableMini() {
    $("#" + miniCalendarWrapperWorkers + " tr td:not(:first-child)").empty().removeAttr("rowspan");
    $("#" + miniCalendarWrapperTools + " tr td:not(:first-child)").empty().removeAttr("rowspan");
}

function hideAllWorkersMini() {
    $("#" + miniCalendarWrapperWorkers + " thead th:not(:first-child)").addClass("hidden");
    $("#" + miniCalendarWrapperWorkers + " tbody tr td:not(:first-child)").addClass("hidden");

    if (workersFilterMini.length === 0) {
        displayEmptyMiniCalendar(miniCalendarTableWorkersId);
    }
}

function hideAllToolsMini() {
    $("#" + miniCalendarWrapperTools + " thead th:not(:first-child)").addClass("hidden");
    $("#" + miniCalendarWrapperTools + " tbody tr td:not(:first-child)").addClass("hidden");

    if (toolsFilterMini.length === 0) {
        displayEmptyMiniCalendar(miniCalendarTableToolsId);
    }
}

function showWorkersMini(workers) {
    $.each(workers, function (index, worker) {
        $("#" + miniCalendarWrapperWorkers + " thead th[data-worker='" + worker + "']").removeClass("hidden");
        $("#" + miniCalendarWrapperWorkers + " tbody tr td[data-worker='" + worker + "']").removeClass("hidden");
    });
}

function showToolsMini(tools) {
    $.each(tools, function (index, tool) {
        $("#" + miniCalendarWrapperTools + " thead th[data-tool='" + tool.trim() + "']").removeClass("hidden");
        $("#" + miniCalendarWrapperTools + " tbody tr td[data-tool='" + tool.trim() + "']").removeClass("hidden");
    });
}

function displayEmptyMiniCalendar(tableId) {
    $(tableId + " thead tr th.set-wh-hours").css("height", "50px");
    $(tableId + " thead tr th.cell-width").first().removeClass("hidden");
    $(tableId + " thead tr th .order-cal-header").first().addClass("hidden");
    $(tableId + " tbody tr").each(function () {
        $(this).find(".cell-width").first().removeClass("hidden");
    });
}

function setAbsencesMini(absences) {
    $.each(absences, function (i, item) {
        let startTimeAbsence = getTime(item.DateStart);
        let endTimeAbsence = getTime(item.DateEnd);
        let duration = (convertTimeToMinutes(endTimeAbsence) - convertTimeToMinutes(startTimeAbsence)) / minutesPerRow;
        let durationAbsence = duration % 1 == 0 ? duration : parseInt(duration) + 1;

        itemHeight = cellHeight * durationAbsence;

        let absenceCellD = $("#" + miniCalendarWrapperWorkers + " tbody td[data-worker='" + item.Worker + "'][data-time='" + startTimeAbsence + "']");
        absenceCellD
            .append("<p class='calendar-absence ' id='d-" + item.AnQId + "' style = 'background: " + shade(item.BackgroundColor, shadeNum) + "; border-left-color: " + item.BackgroundColor + "; height: " + itemHeight + "px;' data-duration='" + durationAbsence + "'><i class='m-r-xs fas " + item.IconName + "'></i>" + item.TypeName + "</p>");
    });
}

function setCalendarDataMini(orders) {
    $.each(orders, function (i, item) {
        let order = item;
        let date = new Date(parseInt(item.Date.substr(6)));
        date = moment(date).format(dateFormat);
        let currentWorker = null;

        // Order items loop
        $.each(item.Items, function (index, item) {
            let firstRow;
            let worker = "";
            let tool = "";
            if (item.Worker) worker = item.Worker.trim();
            if (item.FixedAsset) tool = item.FixedAsset.trim();

            if (worker || tool) {
                let itemStartTime;
                let prstTime = item.PrstTime;
                let rowSpan = 1;

                if (prstTime && prstTime != 0) {
                    rowSpan = roundDuration(item.PrstTime) / minutesPerRow;
                    rowSpan = rowSpan == 0 ? 1 : rowSpan;
                }

                firstRow = (currentWorker && currentWorker == worker) ? firstRow : startWorkingHoursRow;
                currentWorker = worker;

                if (item.StartTime) {
                    itemStartTime = roundTime(item.StartTime)
                }

                let itemHeight = cellHeight * rowSpan;

                // Set daily calendar values
                if (itemStartTime) {
                    let dailyCell = $("#" + miniCalendarWrapperWorkers + " td[data-worker='" + worker + "'][data-time='" + itemStartTime + "']");
                    let dailyCellTools = $("#" + miniCalendarWrapperTools + " td[data-tool='" + tool + "'][data-time='" + itemStartTime + "']");

                    // Set daily calendar values 
                    let appendData =
                        "<div class='calendar-events blurred-elements ' id='d-" + item.AcKey + "-" + item.AnNo + "' style='background: " + shade(item.ColorCode, shadeNum) + "; border-left-color: " + item.ColorCode + "; height: " + itemHeight + "px;' data-duration='" + rowSpan + "' title='" + item.Name + "'>" +
                            "<p class='cal-items-text'>" +
                                "<span id='cal-items-ident'>" + item.Name + "</span>" +
                                "<br />" +
                                "<span id='cal-items-customer'>(" + order.ConsigneeId + ")</span>" +
                            "</p>" +
                        "</div>";

                    dailyCell.append(appendData);
                    dailyCellTools.append(appendData);
                }
            }
        });
    });
}

function unblurActiveItems(acKey) {
    $("div[id*=d-" + acKey + "]").removeClass("blurred-elements");
}

function checkOverlapingMiniCalendar() {
    let isTools = $(miniCalendarTypeId).val() === calendarByTools ? true : false;
    let tableId = isTools ? miniCalendarTableToolsId : miniCalendarTableWorkersId;
    checkIfOverlapsMini(tableId, isTools);
}

function checkIfOverlapsMini(tableId, isTools) {
    let items = [];
    $(tableId + " .during-absence").removeClass("during-absence");
    $(tableId + " .with-absence").css("margin-left", "");
    $(tableId + " .with-absence").removeClass("with-absence");
    $(tableId + " .absence").removeClass("absence");
    $(tableId + " .absence-ml").removeClass("absence-ml");
    $(tableId + " .fa-exclamation").remove();
    $(tableId + " .icons-under").removeClass("icons-under");
    $(tableId + " #cal-items-icons").addClass("cal-items-icons");
    $(tableId + " .cal-items-icons").find("#cal-edit-button").addClass("m-r-sm");

    $(tableId + " .calendar-events," + tableId + " .calendar-absence").each(function () {
        let worker = $(this).closest("td").data("worker");
        let date = $(this).closest("td").data("date");
        let timeStart = $(this).data("starttime");
        let timeEnd = $(this).data("endtime");
        let id = $(this).attr("id");
        let type = $(this).hasClass("calendar-events") ? "item" : "absence"
        let fixedAsset = $(this).closest("td").data("tool");

        if (tableId === miniCalendarTableWorkersId || tableId === miniCalendarTableToolsId) {
            let duration = $(this).data("duration");
            timeStart = $(this).closest("td").data("time");
            timeEnd = getEndTime(timeStart, duration);
        }

        items.push({
            worker: worker,
            date: date,
            timeStart: timeStart,
            timeEnd: timeEnd,
            type: type,
            id: id,
            fixedAsset: fixedAsset
        });
    });

    for (var i = 0; i < items.length; i++) {
        let iterator = (tableId === miniCalendarTableWorkersId || tableId === miniCalendarTableToolsId) ? 0 : i + 1;
        for (var j = iterator; j < items.length; j++) {
            let itemI = $(" #" + items[i].id);
            let overlap = checkIfTimeOverlaps(items, i, j, isTools);

            if (overlap && (tableId === miniCalendarTableWorkersId || tableId === miniCalendarTableToolsId)) {
                if (j !== i && itemI.hasClass("calendar-events")) {
                    itemI.addClass("absence absence-ml with-absence");
                    itemI.find(".cal-items-icons").addClass("icons-under").removeClass("cal-items-icons");
                    itemI.find("#cal-edit-button").removeClass("m-r-sm");
                    addExclamationIcon(itemI);
                    $(".ui-resizable-handle").css("z-index", "unset");
                }

                if (j !== i && itemI.hasClass("calendar-absence")) {
                    itemI.addClass("absence");
                }
            }
        }
    }

    updateElementsWidthMini(isTools);
}

function updateElementsWidthMini(isTools) {
    let tableId = isTools ? miniCalendarTableToolsId : miniCalendarTableWorkersId;
    let cellWidth = $(tableId + " td.cell-width:not(.hidden)").first().width();
    let itemWidth = cellWidth - 4;
    let elements = $(tableId + " td:not(.hidden) .calendar-events," + tableId + " td:not(.hidden) .calendar-absence");

    if (cellWidth > initCellWidth) {
        elements.each(function () {
            if ($(this).is(".absence.calendar-events")) {
                $(this).css("width", (itemWidth / 2 - 10) + "px");
                $(this).css("margin-left", (itemWidth / 2 + 10) + "px");
            } else if ($(this).is(".absence.calendar-absence")) {
                $(this).css("width", (itemWidth / 2 - 10) + "px");
            } else {
                $(this).css("width", itemWidth + "px");
            }
        });
    } else {
        elements.each(function () {
            $(this).css("width", "");
            $(this).css("margin-left", "");
        });
    }
}

$("#mini-calendar-icon").on("click", function () {
    $('#cal-datepicker').click();
});

//#endregion MINI CALENDAR