var newMarkersAdded = false;
var openInfoWindow = null;
var globalWorkOrderLoc;
var globalWorkOrderUrls;
var globalWorkOrderParams;
var workersArray;
var _isMobileWO;
var hasPersonalFolder;
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, status) {
    let addNewLoc = globalWorkOrderLoc ? globalWorkOrderLoc.addNew : globalProcessingLoc.addNew;
    let workerIcons = '';
    const hasEmployees = workers && workers.length > 0;
    const maxIconsToShow = 3;
    let isHidden = status == 'Z' ? 'hidden' : '';

    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 ${isHidden}" onclick="openAddWorkersModal('${acKey}', ${woExQId}, ${itemQId}, ${itemResourceQId}, '${date}', ${anNo})" title="${addNewLoc}">+</div>`;
        workerIcons += remainingIcon;
    } else {
        workerIcons += `<div class="map-remaining-workers ${isHidden}" 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="fal fa-map-marked-alt"></i> ' + markerData.address + '</div>' +
                    '<div class="mb-8"> <i class="fal 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="fal 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 setFromButtonStates() {
    $(".daily-plan-switch").prop('checked', function () {
        return localStorage.getItem('WoFromDailyPlanSVC') === "true"
    });

    $(".active-work-orders-switch").prop('checked', function () {
        return localStorage.getItem('ActiveWorkOrdersSVC') === "true"
    });
}

function initWorkOrdersSvc(localization, urls, params) {

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

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

    if (!_isMobileWO) {

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

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

        $('.d-datepicker').datepicker()
            .on('click', function (e) {
                $(this).select();
            }).on('changeDate', function () {
                $(this).datepicker('hide');
            });

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

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

    $('.active-work-orders-switch').on('change', function () {
        localStorage.setItem('ActiveWorkOrdersSVC', this.checked);
        $.fn.dataTable.reload($mainGridTable);
    });

    $('.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));
    });

    setFromButtonStates();
    loadStatuses();
    getSortType();

    $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();
                d.Product = $("#IdentFilterSearch").val();
                d.Workers = $('#Workers').val();
                d.Keywords = $('.search-input[name="Keywords"]').val();
                d.ProductionType = $("#ProdType").val();
                d.ActiveWorkOrders = localStorage.getItem('ActiveWorkOrdersSVC') === 'true';
                d.EmployeeHasPersonalFolder = hasPersonalFolder;
                d.DataFromDailyPlan = localStorage.getItem('WoFromDailyPlanSVC') === 'true'
                d.DateFrom = _isMobileWO ? $("#mDateFrom").val() : reformatDate($("#dDateFrom").val());
                d.DateTo = _isMobileWO ? $("#mDateTo").val() : reformatDate($("#dDateTo").val());
                d.SortColumn = $('#OrderBy').val();
                d.SortOrder = $("#sortType").attr('data-value');
            }
        },
        columns: [
            {
                render: $.fn.dataTable.render.previewWorkOrderReportTreeOptions()
            },
            {
                class: 'services-card-header',
                orderable: false,
                render: function (data, type, full) {
                    return  `<div style="float:left; height:25px;"><i class="fal fa-indent"></i> <h5 style="display: inline;">${full.Ident}</h5></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, null, full.Status);
                    return type === 'display' ?
                        '<div style="height:70px;word-wrap:break-word;"><span style="font-weight: 600;">' + data + '</span><br/>' +
                        '<i class="fal 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="fal fa-hashtag"></i> <span>' + data + '</span>' +
                        '<div class="pulsating-circle pull-right ' + hidden + '" data-toggle="popover"  data-placement="bottom" ' +
                        '   data-url="' + globalWorkOrderUrls.operRegURL + '" data-original-title="' + globalWorkOrderLoc.workRegistration + '" data-key="' + full.AcKey + '" > ' +
                        '</div > ' : data;
                }
            },
            {
                data: 'Date',
                name: "adDate",
                render: function (data, type, full) {
                    let dateClass = 'label-default';
                    if (isPastDate(data)) {
                        dateClass = 'label-danger';
                    }

                    let percentageText = full.Status === 'O' || full.Status === 'Z' ? full.StatusDisplay : full.CompletedPrc + '%';
                    let percentageClass = full.Status === 'O' ? 'label-success' : full.Status === 'Z' ? 'label-default' : 'label-primary';

                    let title = [full.ServicedItem, full.ServicedItemName].filter(Boolean).join(' - ');

                    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="fal 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 () {                       
                        $.ajax({
                            url: $(this).attr('data-url'),
                            type: 'POST',
                            async: false,
                            data: {
                                Key: $(this).attr('data-key'),
                                No: $(this).attr('data-no'),
                                ItemType: ""
                            },
                            success: function (response) {
                                getOperRegTable(response);
                            }
                        });
                        return $('#operPopover').html();
                    }
                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                }),
                $("[data-toggle=notePopover]").popover({
                    html: true,
                    container: "body",
                    trigger: 'hover',
                    content: function () {

                        $.ajax({
                            cache: false,
                            type: "GET",
                            url: globalWorkOrderUrls.getNoteURL,
                            data: { key: $(this).attr('data-key') },
                            async: false,
                            success: function (response) {
                                $("#notePopover").empty();
                                var noteHTML =
                                    '<div><h3>' + globalWorkOrderLoc.noteCaption + '</h3></div>'+
                                    '<textarea id="note-input" style="resize: vertical; height: 200px; width:400px" class="form-control">' + response.Content + '</textarea>'
                                $('#notePopover').append(noteHTML);
                            },
                            error: function (error) {
                                console.error(error);
                            }
                        });

                        return $('#notePopover').html();
                    }
                }).click(function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                });
                ;
        }
    }).on('click', 'tr', function (e) {
        let $cell = $(e.target).closest('td, th');
        let cellIndex = $cell.index();

        if (cellIndex === 0) {
            return;
        }

        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");
        }
        if ($("#Workers").val()) {
            $("#Workers").val('');
            $("#Workers").trigger("change");
        }

        $('.filter-list-item').each(function () {
            $(this).find('i').removeClass('fa-check');
            $(this).removeClass('active');
        });

        $('.filter-list').each(function () {
            var control = $(this).data('control');
            $(control).val([]);
            $(control).trigger("change");
        });

        handleButtonClick($("#X"));
        localStorage.removeItem('selectedStatuses');

        $("#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);
    });

    $('#save-note-btn').on('click', function () {
        saveWorkOrderNote(globalWorkOrderUrls.saveNoteURL);
    });
};

function getOperRegTable(response) {

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

        item.Icon = item.Icon.replace("fa-lg", "fa-2x");

        trHTML +=
            '<tr>' +
            '   <td style="width:50px"> ' +
            '       <i class="' + item.Icon + '" style= "color:' + item.Color + '"></i>' +
            '   </td>' +
            '   <td style="width:200px">' +
            '       <label class="control-label">' + item.EventTypeCaption + ' </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 setSortType(obj) { 
    $(obj).find("i").toggleClass('fa-arrow-down-short-wide').toggleClass('fa-arrow-down-wide-short')
    $(obj).attr('data-value', $(obj).attr('data-value') == 'ASC' ? 'DESC' : 'ASC')
    localStorage.setItem('sortType', $(obj).attr('data-value'));
    $.fn.dataTable.reload($mainGridTable);
}

function getSortType() {
    $("#sortType").attr('data-value', localStorage.getItem('sortType'));
    if (localStorage.getItem('sortType') === 'ASC') {
        $("#sortType").find("i").addClass('fa-arrow-down-short-wide').removeClass('fa-arrow-down-wide-short')
    } else {
        $("#sortType").find("i").removeClass('fa-arrow-down-short-wide').addClass('fa-arrow-down-wide-short')
    }
}

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);

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

    selWorkers == "" ? selWorkers = $("#Workers").attr("title") : selWorkers;
    $("#workers-list").text(selWorkers);
}

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) {
    closeInfoCard();
    if (typeof full === 'string') {
        full = JSON.parse(full);
    }

    var image = full.Picture ? " <img id='info-card-image' src='" + full.Picture + "' />" : "<i class='fal fa-image fa-3x text-muted' style='opacity:0.5'></i>";
    $('.card-image').html(image);

    let title = [full.ServicedItem, full.ServicedItemName].filter(Boolean).join(' - ');
    $('#info-card-title').text(title);
    $('#info-card-acKey').text(full.AcKeyDisplay);
    $('#info-card-date').text(full.Date);

    if (full.AcLnkKey) {
        $('#info-card-acLnkKey').text(full.AcLnkKey);
        $('#info-card-acLnkKey-container').removeClass('hidden');
    }

    if (full.CostDrv) {
        $('#info-card-costDrv').text(full.CostDrv);
        $('#info-card-costDrv-container').removeClass('hidden');
    }

    if (full.Dept) {
        $('#info-card-Dept').text(full.Dept);
        $('#info-card-Dept-container').removeClass('hidden');
    }

    if (full.Receiver) {
        $('#info-card-Rec').text(full.Receiver);
        $('#info-card-Recevier-container').removeClass('hidden');
    }

    if (full.Consignee) {
        $('#info-card-Consig').text(full.Consignee);
        $('#info-card-Consignee-container').removeClass('hidden');
    }

    if (full.Priority) {
        $('#info-card-Priority').text(full.Priority);
        $('#info-card-Priority-container').removeClass('hidden');
    }

    if (full.Status === 'Z') {
        $('#info-card-close-dn').attr('onclick', `openRN('${full.AcKey}','${full.StatusDisplay}','${globalWorkOrderUrls.openWOURL}')`);
        $('#info-card-close-dn').attr('title', globalWorkOrderLoc.openRN);
        $('#info-card-close-dn>i').removeClass('fa-file-xmark').addClass('fa-file-check');
    } else {
        $('#info-card-close-dn').attr('onclick', `closeRN('${globalWorkOrderUrls.closeWOURL}', '${full.AcKey}', '${globalWorkOrderLoc.ok}')`);
        $('#info-card-close-dn').attr('title', globalWorkOrderLoc.closeRN);
        $('#info-card-close-dn>i').removeClass('fa-file-check').addClass('fa-file-xmark');
    }

    if (full.Status == "O") {
        $('#info-card-status').off('click').on('click', function () {
            changeWOStatus(globalWorkOrderUrls.changeWOStatusURL, full.AcKey, 'R');
        });
        $('#info-card-status').attr('title', globalWorkOrderLoc.changeStatusOpenToReleased);
        $('#info-card-status').removeClass('hidden');
    } else if (full.Status == "R") {
        $('#info-card-status').off('click').on('click', function () {
            changeWOStatus(globalWorkOrderUrls.changeWOStatusURL, full.AcKey, 'O');
        });
        $('#info-card-status').attr('title', globalWorkOrderLoc.changeStatusReleasedToOpen);
        $('#info-card-status').removeClass('hidden');
    }

    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').off("click").on("click", function () {
        window.location.href = "Service/WorkOrderMaterials?key=" + full.AcKey;
    });

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

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

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

    $('#info-card-note').off("click").on("click", function () {
        loadWorkOrderNote(globalWorkOrderUrls.getNoteURL, 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-status').addClass('hidden');
    $('#info-card-acLnkKey-container').addClass('hidden');
    $('#info-card-costDrv-container').addClass('hidden');
    $('#info-card-Dept-container').addClass('hidden');

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

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();
}

function openRN(acKey, status, url, continueUrl) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#WOClosedToOpen").val().replace("{0}", status),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#ConfirmLoc").val(),
                action: function () {
                    $.ajax({
                        cache: false,
                        type: "POST",
                        url: url,
                        dataType: 'json',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({
                            key: acKey
                        }),
                        success: function (response) {
                            if (response.Success) {
                                if (continueUrl) {
                                    window.location.href = continueUrl;
                                }
                                else {
                                    $.fn.dataTable.reload($mainGridTable);
                                    closeInfoCard();
                                }
                            }
                        },
                        error: function (error) {
                            console.error(error);
                        }
                    });
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function closeRN(closeWOUrl, acKey, okLoc) {
    $.ajax({
        cache: false,
        type: "POST",
        url: closeWOUrl,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            key: acKey
        }),
        success: function (response) {
            if (response.Success) {
                $.fn.dataTable.reload($mainGridTable);
                closeInfoCard();
            } else {
                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: false,
                    type: "alert",
                    text: response.Message.join('<br>'),
                    closeOtherModals: false,
                    buttons: [
                        {
                            text: okLoc,
                            icon: 'fa fa-check',
                            closeOnAction: true,
                            type: 'primary'
                        },
                    ]
                });
            }
        },
        error: function (error) {
            console.error(error);
        }
    });
}

var clientSignature;
function openSignatureForm(onAfterSigned) {
    openCustomSignature(globalWorkOrderLoc.signature,
        globalWorkOrderUrls.signatureHelpURL,
        { signAgain: globalWorkOrderLoc.signAgain, cancel: globalWorkOrderLoc.cancelText, confirm: globalWorkOrderLoc.confirmText },
        (signature) => { clientSignature = signature; onAfterSigned(); }
    );
}

$.fn.dataTable.render.previewWorkOrderReportTreeOptions = function () { 
    var reportClass = globalWorkOrderParams.isReportVisible === "True" ? "" : "hidden";
    return function (data, type, row, meta) {
        if (type === 'display') {
            let func = `openPdfPreview('${globalWorkOrderUrls.printReport}?fiscalize=false&preview=false&acKey=${row.AcKey}&type=40O', 
                                        ${globalWorkOrderParams.isReportSignable.toLowerCase()})`;
            
            let response = `
            <span onclick="${func}" title="${globalWorkOrderLoc.labelPrinting}" class="${reportClass}">
                <i class="fal fa-eye fa-2x text-muted m-r-xs"></i>
            </span>
            <div style="float:right;padding-left:5px" onclick='loadInfoCard(${JSON.stringify(row)})'>
                <i class="fal fa-search fa-2x"></i>
            </div>
            <a class="text-default" style="float:right" data-toggle="notePopover" data-placement="auto" data-key="${row.AcKey}"  '>
                <i class="fal fa-comment-alt-lines fa-2x"></i>
            </a>`;

            return response;
        }

        return data;
    };
};
