var newMarkersAdded = false;
var openInfoWindow = null;
var globalWorkOrderLoc;
var globalWorkOrderUrls;
var globalWorkOrderParams;
var workersArray;
var _isMobileWO;
var map;
var markers = [];
var mapStyle = [
    {
        "featureType": "poi",
        "elementType": "labels.icon",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    }
];

async function initializeServicesMap() {
    const { Map } = await google.maps.importLibrary("maps");

    var mapOptions = {
        center: { lat: 46.055333112, lng: 14.507831302 },
        zoom: 10,
        mapTypeId: 'roadmap',
        styles: mapStyle
    };

    map = new Map(document.getElementById("services-map"), mapOptions);
}

function getWorkerIcons(workers, acKey, woExQId, itemQId, itemResourceQId, date, anNo) {
    let addNewLoc = globalWorkOrderLoc ? globalWorkOrderLoc.addNew : globalProcessingLoc.addNew;
    let workerIcons = '';
    const hasEmployees = workers && workers.length > 0;
    const maxIconsToShow = 3;

    if (hasEmployees) {
        const matchedWorkers = workersArray.filter(worker => workers.includes(worker.Worker));
        const workersToShow = matchedWorkers.slice(0, maxIconsToShow);
        workerIcons = workersToShow.map(worker => {
            if (worker.Icon) {
                return `<img src="${worker.Icon}" class="map-round-icon" title="${worker.Worker}">`;
            } else {
                return `<i class="fal fa-user-circle text-muted card-worker-icon" title="${worker.Worker}"></i>`;
            }
        }).join('');

        const remainingCount = Math.max(0, matchedWorkers.length - maxIconsToShow);
        const remainingIcon = remainingCount > 0
            ?
            `<div class="map-remaining-workers" onclick="openAddWorkersModal('${acKey}', ${woExQId}, ${itemQId}, ${itemResourceQId}, '${date}', ${anNo})" title="${addNewLoc}">+${remainingCount}</div>`
            :
            `<div class="map-remaining-workers" onclick="openAddWorkersModal('${acKey}', ${woExQId}, ${itemQId}, ${itemResourceQId}, '${date}', ${anNo})" title="${addNewLoc}">+</div>`;
        workerIcons += remainingIcon;
    } else {
        workerIcons += `<div class="map-remaining-workers" onclick="openAddWorkersModal('${acKey}', ${woExQId}, ${itemQId}, ${itemResourceQId}, '${date}', ${anNo})" title="${addNewLoc}">+</div>`;
    }

    return workerIcons;
}

function clearMarkers() {
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
    markers = [];
}

function fitMapBounds() {
    if (($('.divided-content').hasClass('divided-content-side-opened') || $('#map-container').hasClass('active')) && newMarkersAdded) {
        let bounds = new google.maps.LatLngBounds(null);

        for (var i = 0; i < markers.length; i++) {
            bounds.extend(markers[i].getPosition());
        }

        map.fitBounds(bounds);

        google.maps.event.addListenerOnce(map, "idle", function () {
            if (map.getZoom() > 15) {
                map.setZoom(15);
            }
        });

        newMarkersAdded = false;
    }
}

function addMarker(markerData) {
    let blackPin = {
        path: "M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z",
        fillColor: '#333',
        fillOpacity: 1,
        strokeColor: 'white',
        strokeWeight: 2,
        rotation: 0,
        scale: 2,
        anchor: new google.maps.Point(12, 24),
    };

    let circleIcon = {
        path: google.maps.SymbolPath.CIRCLE,
        fillColor: '#fbae17',
        fillOpacity: 1,
        strokeColor: 'white',
        strokeWeight: 2,
        scale: 18,
    };

    let geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: markerData.address }, function (results, status) {
        if (status === 'OK') {
            let marker;
            if (markerData.isCircle) {
                marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: markerData.title,
                    icon: circleIcon,
                    label: {
                        color: 'white',
                        fontSize: '18px',
                        fontWeight: '400',
                        text: markerData.workers.length.toString()
                    }
                });
            } else {
                marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map,
                    title: markerData.title,
                    icon: blackPin
                });
            }

            markers.push(marker);
            newMarkersAdded = true;

            let infowindow = new google.maps.InfoWindow();
            marker.addListener('click', function () {
                if (openInfoWindow) {
                    openInfoWindow.close();
                }

                let contentString =
                    '<div style="width: 200px;">' +
                    '<div style="border-bottom: 1px solid #ccc;" class="mb-8 model-simple-title p-b-10">' + markerData.title + '</div>' +
                    '<div style="font-weight: 500;">' + markerData.subject + '</div>' +
                    '<div class="mb-8"> <i class="fad fa-map-marked-alt"></i> ' + markerData.address + '</div>' +
                    '<div class="mb-8"> <i class="fas fa-hashtag"></i> ' + markerData.acKeyView + '</div>' +
                    `<div class="mb-8" id="infoWindowWorkers">` + $(`[data-info="${markerData.acKey}"]`).html() + `</div>` +
                    '<div>' +
                    '<div class="services-card-label ' + markerData.dateClass + '"><span style="margin-right:2px"> <i class="far fa-calendar alt"></i> </span> <span>' + markerData.date + '</span></div>' +
                    '<div class="services-card-label pull-right ' + markerData.percentageClass + '"><span>' + markerData.percentageText + '</span></div>' +
                    '</div>' +
                    '</div>';

                infowindow.setContent(contentString);
                infowindow.open(map, marker);

                openInfoWindow = infowindow;
            });
        } else {
            console.error('Geocode was not successful for the following address: ' + markerData.address);
        }
    });
}

function setFromDailyPlanButtonState() {
    $("#data-from-daily-plan").prop('checked', function () {
        return localStorage.getItem('WoFromDailyPlan') === "true"
    });
}

function initWorkOrdersSvc(localization, urls, params) {

    globalWorkOrderLoc = localization;
    globalWorkOrderUrls = urls;
    globalWorkOrderParams = params;
    workersArray = JSON.parse(globalWorkOrderParams.workersList);

    _isMobileWO = globalWorkOrderParams.isMobile === 'True' ? true : false;

    setLocalStorageDates();

    if (!_isMobileWO) {

        $("#mainGrid").appendTo(".document-list");

        $('#X').addClass('active').css('border-bottom', '4px solid #faaf14');

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

    }
    else {
        $("#mainGrid").appendTo(".document-list-no-footer");
    }

    $('.js-switch').on('change', function () {
        localStorage.setItem('WoFromDailyPlan', this.checked);
        $.fn.dataTable.reload($mainGridTable);
    });

    $('.localStorageFilter').on('change', function () {
        localStorage.setItem($(this).attr('id'), $(this).val());
    });

    $('.filter-list-item').on("click", function () {
        var selectedValues = [];

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

        var parent = $(this).parent().attr('id');

        $("#" + parent + " .filter-list-item.active").each(function (index) {
            selectedValues.push($(this).data("value"));
        });

        var control = $(this).parent().data('control')
        $(control).val(selectedValues);
        $(control).trigger("change");

        localStorage.setItem('selectedStatuses', JSON.stringify(selectedValues));
    });

    setFromDailyPlanButtonState();
    loadStatuses();
    $mainGridTable = $('#mainGrid');

    var mainTable = $mainGridTable.DataTable({
        initComplete: function (settings, json) {
            $('.menu-open-button').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
                $(this).toggleClass('active');
            });

            $('.menu-item').on("click", function () {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        ajax: {
            url: $mainGridTable.attr('data-url'),
            data: function (d) {
                var selectedDocTypes = $('#DocTypes').val();
                if (!selectedDocTypes || selectedDocTypes.length === 0) {
                    selectedDocTypes = $('#DocTypes option').map(function () { return $(this).val(); }).get();
                }
                d.DocTypes = selectedDocTypes;
                d.Statuses = $('#Status').val() == null ? [] : $('#Status').val();
                d.Product = $("#IdentFilterSearch").val();
                d.Keywords = $('.search-input[name="Keywords"]').val();
                d.ProductionType = $("#ProdType").val();
                d.DataFromDailyPlan = $("#data-from-daily-plan").is(":checked");
                d.DateFrom = _isMobileWO ? $("#mDateFrom").val() : reformatDate($("#dDateFrom").val());
                d.DateTo = _isMobileWO ? $("#mDateTo").val() : reformatDate($("#dDateTo").val());
            }
        },
        columns: [
            {
                class: 'services-card-header',
                orderable: false,
                render: function (data, type, full) {
                    let itemType;
                    switch (full.ServicedItemType) {
                        case 0:
                            itemType = globalWorkOrderLoc.identFilterItem;
                            break;
                        case 1:
                            itemType = globalWorkOrderLoc.resource;
                            break;
                        case 2:
                            itemType = globalWorkOrderLoc.tool;
                            break;
                        case 3:
                            itemType = globalWorkOrderLoc.fixedAsset;
                            break;
                        default:
                            itemType = '';
                            break;
                    }

                    return  `<div style="float:left;"><i class="fas fa-indent"></i> <span>${itemType}</span></div>` +
                            `<div style="float:right; width:25px; height:25px;" onclick='loadInfoCard(${JSON.stringify(full)})'><i class="fal fa-search fa-2x"></i></div>`;
                }
            },
            {
                class: 'border-bottom',
                orderable: false,
                render: function (data, type, full) {
                    let title;
                    if (full.ServicedItem && full.ServicedItemName) {
                        title = full.ServicedItem + ' - ' + full.ServicedItemName;
                    } else if (full.ServicedItem) {
                        title = full.ServicedItem;
                    } else if (full.ServicedItemName) {
                        title = full.ServicedItemName;
                    } else {
                        title = '';
                    }

                    var tooltip = '<span data-toggle="tooltip" class="card-caption" data-original-title = "' + title + '">' + title + ' </span> ';
                    return "<span style = 'width:100rem;position: relative;display: table-cell;height: 50px;'>" + tooltip + " </span>";
                }
            },
            {
                data: "Consignee",
                name: "Consignee",
                className: "dt-body-left",

                render: function (data, type, full) {
                    let workerIcons = getWorkerIcons(full.AcWorkers, full.AcKey, full.QId, null, null, full.Date);
                    return type === 'display' ?
                        '<div style="height:70px;word-wrap:break-word;"><span style="font-weight: 600;">' + data + '</span><br/>' +
                        '<i class="fad fa-map-marked-alt"></i> <span>' + full.Address + '</span></div>' +
                        `<div id="operWorker" data-info="` + full.AcKey + `" style="height:50px">` + workerIcons + `</div>` : data;
                }
            },
            {
                data: "AcKeyDisplay",
                name: "AcKey",
                className: "dt-body-left",

                render: function (data, type, full) {
                    var hidden = full.WoExOperRegCount == "0" ? 'hidden' : '';
                    return type === 'display' ?
                        '<i class="fas fa-hashtag"></i> <span>' + data + '</span>' +
                        '<div class="pulsating-circle pull-right ' + hidden + '"</div >' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    let dateClass = 'label-default';
                    if (isPastDate(data)) {
                        dateClass = 'label-danger';
                    }

                    let percentageText;
                    let percentageClass = 'label-primary';
                    if (full.Status === 'O') {
                        percentageText = full.StatusDisplay
                        percentageClass = 'label-success';
                    } else if (full.Status === 'Z') {
                        percentageText = full.StatusDisplay;
                        percentageClass = 'label-default';
                    } else {
                        percentageText = full.CompletedPrc + '%';
                    }

                    let title;
                    if (full.ServicedItem && full.ServicedItemName) {
                        title = full.ServicedItem + ' - ' + full.ServicedItemName;
                    } else if (full.ServicedItem) {
                        title = full.ServicedItem;
                    } else if (full.ServicedItemName) {
                        title = full.ServicedItemName;
                    } else {
                        title = '';
                    }

                    let markerData = {
                        title: title,
                        subject: full.Consignee,
                        address: full.Address,
                        acKeyView: full.AcKeyDisplay,
                        dateClass: dateClass,
                        date: data,
                        percentageClass: percentageClass,
                        percentageText: percentageText,
                        isCircle: full.AcWorkers.length > 0,
                        acKey: full.AcKey,
                        workers: full.AcWorkers,
                        qId: full.QId
                    };
                    addMarker(markerData);

                    return type === 'display' ?
                        '<div><div class="services-card-label ' + dateClass + '"><span style="margin-right:2px"> <i class="far fa-calendar alt"></i> </span> <span>' + data + '</span></div>' +
                        '<div class="services-card-label pull-right ' + percentageClass + '"><span>' + percentageText + '</span></div></div>' : data;
                }
            }
        ],
        createdRow: function (row, data, dataIndex) {
            $(row).css('cursor', 'pointer');
            $(row).attr('id', 'row-' + dataIndex);
        },
        drawCallback: function (settings) {
            setTimeout(function () {
                fitMapBounds();
            }, 750);

            $('#X > span:last-child').text(settings.json.prop.All);

            $('#P > span:last-child').text(settings.json.prop.Planned);
            $('#O > span:last-child').text(settings.json.prop.Opened);
            $('#I > span:last-child').text(settings.json.prop.Reserved);
            $('#R > span:last-child').text(settings.json.prop.Released);
            $('#D > span:last-child').text(settings.json.prop.InProgress);
            $('#E > span:last-child').text(settings.json.prop.PartialyFinished);
            $('#Z > span:last-child').text(settings.json.prop.Finished);

            $("[data-toggle='tooltip']").tooltip({
                container: 'body'
            }),
                $("[data-toggle=popover]").popover({
                    html: true,
                    container: "body",
                    trigger: 'hover',
                    content: function () {
                        let id = $(this).attr('id');
                        $.ajax({
                            url: $(this).attr('data-url'),
                            type: 'POST',
                            async: false,
                            data: {
                                Key: $(this).attr('data-key'),
                                ItemType: ""
                            },
                            success: function (response) {
                                getWOOperRegTable(response);
                            }
                        });
                        return $('#operPopover').html();
                    }
                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
        }
    }).on('click', 'tr', function () {
        var data = mainTable.row($(this)).data();
        window.location.href = "Service/WorkOrderOperations?key=" + data.AcKey;
    });

    $("select").off("change.tableReload");
    $("select").on("change.tableReload", function (e) {
        setFiltersMobile();
        $.fn.dataTable.reload($mainGridTable);
    });
    
    $(".btn-toolbar > button.btn").on("click", function () {
        handleButtonClick($(this));
        saveStatuses();
        $.fn.dataTable.reload($mainGridTable);
    });

    setFiltersMobile();

    $('.btn-back').on("click", function () {
        if ($("#filter-container").hasClass("active")) {
            $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
        } else {
            $('#filtersTabs>.tab-pane').removeClass("active");
            $('#filtersTabs>#filter-container').addClass("fade").addClass("in").addClass("active");
        }
    });

    $('#filter').on("click", function () {
        $('#map-tab').removeClass("active");
        $('#filter-tab').addClass("active");

        $('.tab-buttons').show();
        $('#map-container').hide();

        $('#map-tab').hide();
        $('#filter-tab').show();

        $('#filtersTabs>.tab-pane').removeClass("active");
        $('#filtersTabs>#filter-container').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");
    });

    $('#map').on("click", function () {
        $('#filtersTabs>.tab-pane').removeClass("active");
        $('#filter-tab').removeClass("active");

        $('.tab-buttons').hide();
        $('#map-container').show();

        $('#map-tab').show();
        $('#filter-tab').hide();

        $('#map-tab').addClass("active");
        $('#map-container').addClass("fade").addClass("in").addClass("active");
        $(".divided-content").addClass("divided-content-side-opened").removeClass("divided-content-side-closed");

        setTimeout(function () {
            fitMapBounds();
        }, 750);
    });

    $('#close-map').on("click", function () {
        $('#map-tab').removeClass("active");
        $('#map-container').removeClass("active");
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    });

    $('#apply').on("click", function () {
        $.fn.dataTable.reload($mainGridTable);
        clearMarkers();
        $(".divided-content").addClass("divided-content-side-closed").removeClass("divided-content-side-opened");
    })

    $('.menu-open-button').on("click", function () {
        $('.menu-open-button').toggleClass('active');

    });

    $('.clear-filters').on("click", function () {
        if ($("#DocTypes").val()) {
            $("#DocTypes").val('');
            $("#DocTypes").trigger("change");
        }
        if ($("#Status").val()) {
            $("#Status").val('');
            $("#Status").trigger("change");
        }

        $("#Keywords").val('');
        $("#Keywords").trigger("change");
    });

    var typingTimer;
    var doneTypingInterval = 300;

    $('.search-input[name="Keywords"]').off('keyup');
    $('.search-input[name="Keywords"]').on('keyup', function () {

        if ($('.search-input[name="Keywords"]').val().length > 0 && $('.search-input[name="Keywords"]').val().length < 3)
            return;

        clearTimeout(typingTimer);
        typingTimer = setTimeout(function () { $.fn.dataTable.reload($mainGridTable); }, doneTypingInterval);
    });
};

function getWOOperRegTable(response) {

    var icon = '';
    var color = '';
    var caption = '';

    $("#popoverTable").empty();
    var trHTML = '';
    $.each(response.data, function (i, item) {

        switch (item.EventType) {
            case 'OB':
                icon = "fad fa-2x fa-play";
                color = "#7EAF3F";
                caption = globalWorkOrderLoc.operationStart;
                break;
            case 'OP':
                icon = "fad fa-2x fa-pause-circle";
                color = "goldenrod";
                caption = globalWorkOrderLoc.operationPause;
                break;
            case 'OC':
                icon = "fad fa-2x fa-play-circle";
                color = "#7EAF3F";
                caption = globalWorkOrderLoc.operationContinue;
                break;
            case 'OE':
                icon = "fad fa-2x fa-stop-circle";
                color = "#BB5534";
                caption = globalWorkOrderLoc.operationEnd;
                break;

            default:
                icon = "fa fa-clock-o";
                break;
        }

        trHTML +=
            '<tr>' +
            '   <td style="width:50px"> ' +
            '       <i class="' + icon + '" style= "color:' + color + '"></i>' +
            '   </td>' +
            '   <td style="width:200px">' +
            '       <label class="control-label">' + caption + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.EventTimeStr + '</span>' +
            '       </div >' +
            '   </td>' +
            '   <td style="width:300px">' +
            '       <label class="control-label">' + item.ResursID.trim() + ' </label>' +
            '       <div>' +
            '           <span style="font-size: 14px; display: inline-block; overflow:hidden; text-overflow: ellipsis;">' + item.Ident.trim() + " - " + item.Descr.trim() + '</span>' +
            '       </div >' +
            '       <span>' + item.Worker + '</span>' +
            '   </td>' +
            '</tr>';
    });
    $('#popoverTable').append(trHTML);
}

function setFiltersMobile() {
    var selDocs = $("#DocTypes option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selDocs == "" ? selDocs = $("#DocTypes").attr("title") : selDocs;
    $("#doc-type-list").text(selDocs);

    var selStatus = $("#Status option:selected").map(function () {
        return $(this).text();
    }).get().join(',');

    selStatus == "" ? selStatus = $("#Status").attr("title") : selStatus;
    $("#status-list").text(selStatus);
}

function customModalForMobile(isMobile) {
    if (_isMobileWO) {
        $(".custom-modal-footer>div>button").addClass("btn-rounded");
        $(".custom-modal-body-content>span").addClass("h4");
        $(".custom-modal-title").css("font-size", 24);
    }
}

function isPastDate(dateString) {
    var date = moment(dateString, ["DD.MM.YYYY", "MM-DD-YYYY", "YYYY/MM/DD"]);

    var today = moment().startOf('day');
    return date.isBefore(today);
}

async function getWorkersByAcKey(acKey) {
    try {
        const response = await $.ajax({
            url: globalWorkOrderUrls.getDailyPlanWorkersURL,
            method: 'POST',
            data: {
                Key: acKey
            },
            dataType: 'json'
        });

        return response;
    } catch (error) {
        console.error(error);
    }
}

function loadInfoCard(full) {
    event.preventDefault();
    event.stopPropagation();
    if (typeof full === 'string') {
        full = JSON.parse(full);
    }

    $('#info-card-image').attr('src', full.Picture);
    $('#info-card-title').text(full.Consignee);
    $('#info-card-acKey').text(full.AcKeyDisplay);
    $('#info-card-date').text(full.Date);
    $('#info-card-close-dn').attr('onclick', `closeDN('${globalWorkOrderUrls.closeWOURL}', '${full.AcKey}', '${globalWorkOrderUrls.indexURL}', '${globalWorkOrderLoc.ok}')`);    

    let percentageText = full.StatusDisplay;
    if (full.Status !== 'O' && full.Status !== 'Z') {
        percentageText += ` (${full.CompletedPrc}%)`;
    }

    let color = full.StatusMF == 'Z' ? "bg-c-red" : (full.CompletedPrc < 100 ? "bg-c-yellow" : "bg-c-green")
    let value = full.CompletedPrc > 100 ? 100 : full.CompletedPrc
    let progress =
        '<div class="progress-card">' +
        '<div class="progress">' +
        '    <div class="progress-bar ' + color + '" style="width:' + value + '%" aria-valuenow="' + full.CompletedPrc + '" aria-valuemin="0" aria-valuemax="100"></div>' +
        '</div>' +
        '</div>' +

        '<div class="cardStatus">' +
        '   <div class="cardStatus" style="justify-content: normal;">' +
        '       <span>' + percentageText + '</span>' +
        '   </div>' +
        '   <span>' + round(full.ProducedQty, 2).toString().replace('.', ',') + '/' + round(full.PlanQty, 2).toString().replace('.', ',') + '</span>' +
        '</div>';

    $('#info-card-progress').html(progress);

    $('#info-card-materials').on("click", function () {
        window.location.href = "Service/WorkOrderMaterials?key=" + full.AcKey;
    });

    $('#info-card-operations').on("click", function () {
        window.location.href = "Service/WorkOrderOperations?key=" + full.AcKey;
    });

    $('#info-card-tools').on("click", function () {
        window.location.href = "Service/ServicesTools?key=" + full.AcKey;
    });

    let parent = $('.divided-content-main');
    let parentHeight = parent.height();
    let child;
    if (_isMobileWO) {
        child = $('.document-list-no-footer');
    } else {
        child = $('.services-table');
    }
    let newHeight;
    if (_isMobileWO) {
        newHeight = parentHeight - 220;
    } else {
        newHeight = parentHeight - 261;
    }
    child.height(newHeight);

    $('#info-card').show();
}

function closeInfoCard() {
    let parent = $('.divided-content-main');
    let child;
    let parentHeight = parent.height();
    if (_isMobileWO) {
        child = $('.document-list-no-footer');
    } else {
        child = $('.services-table');
    }
    let newHeight;
    if (_isMobileWO) {
        newHeight = parentHeight - 5;
    } else {
        newHeight = parentHeight - 46;
    }
    child.height(newHeight);

    $('#info-card').hide();
}

function setLocalStorageDates() {
    $("#mDateFrom").val(localStorage.getItem('mDateFrom') ?? $("#mDateFrom").val());
    $("#mDateTo").val(localStorage.getItem('mDateTo') ?? $("#mDateTo").val());

    $("#dDateFrom").val(localStorage.getItem('dDateFrom') ?? $("#dDateFrom").val());
    $("#dDateTo").val(localStorage.getItem('dDateTo') ?? $("#dDateTo").val());
}


function saveStatuses() {
    let selectedStatuses = [];
    $('.btn-toolbar > button.btn.active').each(function () {
        selectedStatuses.push($(this).attr('id'));
    });
    localStorage.setItem('selectedStatuses', JSON.stringify(selectedStatuses));
}

function loadStatuses() {
    let selectedStatuses = JSON.parse(localStorage.getItem('selectedStatuses'));
    if (selectedStatuses && selectedStatuses.length > 0) {
        selectedStatuses.forEach(function (filterId) {
            handleButtonClick($("#" + filterId));

            if (_isMobileWO) {
                let item = $(".filter-list-item[data-value='" + filterId + "']");
                item.trigger('click');
            }
        });
    }
}

function handleButtonClick(button) {
    var buttonId = button.attr('id');
    var color = button.css("color");

    if (buttonId != 'X') {
        $('#X').removeClass('font-bold').removeClass('active').css("border-bottom", "");
    } else {
        color = "#faaf14";
        $(".btn-toolbar > button.btn").each(function () {
            $(this).removeClass('font-bold').removeClass('active').css("border-bottom", "");
        });
    }

    button.toggleClass('active').toggleClass('font-bold');

    if (button.hasClass('active')) {
        button.css("border-bottom", "4px solid " + color);
    } else {
        button.css("border-bottom", "")
    }

    let text = [""];
    $(".btn-toolbar > button.btn").each(function () {
        if ($(this).hasClass('active') && buttonId != 'X') {
            text.push($(this).attr('id'));
        }
    });

    if (text.length === 1) {
        $('#X').addClass('font-bold').addClass('active').css("border-bottom", "4px solid #faaf14");
    }

    $('#Status').val(text);
    clearMarkers();
}
