let lastRowSelector = '#DistancesTable tbody tr:last-child td:first';
let nodeInRowSelector = 'input[name$="Node"]';
let nodeSelector = '#Node';
let subjectUrlSelector = 'GetSubjectUrl';
let dailyAllows = "DailyAllows";
let expenses = "Expenses";
let distances = "Distances";
let editAction = "Edit";
let timeRecordIRISShown = false;
let confirmText = $("#Confirm").val();
let headerWorkerSelector = "HeaderWorker";
var selectedKeys = [];
var isGoogleSearchEnabled = false; // needed for AT - google search setting is not cached in local storage but relies upon this
let insertingPosition = false;
let lastClickedAccordion = null;

//#region DATATABLE INITIALIZATION

function initializeTravelOrders() {
    var urlString = window.location.href;
    var url = new URL(urlString);
    var acKey = decodeURI(url.searchParams.get("acKey"));
    var date = decodeURI(url.searchParams.get("date"));
    let isLicenseCM = $("#isLicenseCM").val();

    date === "null" ? date = null : date = fromISOToStandardDateFormatString(date);

    var showWorkerColumn = true;
    if ($("#ShowWorkerColumn").val() != "True")
        showWorkerColumn = false;

    var columns = [
        {
            data: function (data) {
                return data.AcKey;
            },
            orderable: false,
            className: 'dt-body-center',
            render: function (data) { return '<input class="ackey" name="TravelOrderAcKey" onclick=CheckBoxClicked("' + data + '") value="' + data + '" type="checkbox"/>'; }
        },
        { data: "", name: "", className: 'dt-body-center dt-head-center', render: $.fn.dataTable.render.previewReportTreeOptions("AcKey", null, null) },
        { data: "AcKeyDisplay", name: "AcKeyDisplay", filtertype: "text", render: $.fn.dataTable.render.link("AcKey") },
        {
            data: "AdDate", name: "AdDate", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY');
                }
            }
        },
        { data: "FullName", name: "FullName", filtertype: "text", visible: showWorkerColumn },
        {
            data: "AdDateHourFromMin", name: "AdDateHourFromMin", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY HH:mm');
                }
            }
        },
        {
            data: "AdDateHourFromMax", name: "AdDateHourFromMax", filtertype: "text", render: function (data) {
                if (data === null) {
                    return "";
                } else {
                    return moment(data).format('DD.MM.YYYY HH:mm');
                }
            }
        },
        { data: "AnValue", name: "AnValue", filtertype: "text", render: $.fn.dataTable.render.number('.', ',', 2, '') },
        { data: "AcVehicle", name: "AcVehicle", filtertype: "text" },
        { data: "AcPayer", name: "AcPayer", filtertype: "text" },
        { data: "AcVerifyStatusName", name: "AcVerifyStatusName", filtertype: "text" }
    ];

    if (isLicenseCM === 'False') {
        columns.splice(9, 0, { data: "AcDept", name: "AcDept", filtertype: "text" });
    }

    initializeDataTables('travelorders', 'Keywords', columns, acKey, 2, null, true, date, function () {
        selectedKeys = [];
        selectedKeysBehavior();
    });
}

//#endregion DATATABLE INITIALIZATION

//#region DATATABLE CHECKBOX

function CheckBoxClicked(acKey) {
    if (!selectedKeys.includes(acKey)) {
        selectedKeys.push(acKey);
    }
    else {
        let index = selectedKeys.indexOf(acKey);
        selectedKeys.splice(index, 1);
    }

    selectedKeysBehavior();
}

function selectedKeysBehavior() {
    if (selectedKeys.length > 0) {
        $('#deleteButton').removeClass('disabled');
    }
    else {
        $('#deleteButton').addClass('disabled');
    }

    if (selectedKeys.length > 0) {
        $('#duplicateButton').removeClass('disabled');
    }
    else {
        $('#duplicateButton').addClass('disabled');
    }
}
//#endregion DATATABLE CHECKBOX

//#region DELETE TRAVEL ORDER

//#region SINGLE DELETE
function deleteSingleTravelOrder() {
    var deleteText = $("#DeleteTravelOrder").val();
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: deleteText,
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    getSingleDeleteStatus();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function getSingleDeleteStatus() {
    var url = $("#DeleteStatus").val();
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    $.ajax({
        cache: false,
        type: "get",
        url: url,
        success: function (data) {
            if (data.CanBeDeleted === true) {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: data.Message,
                    buttons: [
                        {
                            icon: 'fa fa-times',
                            text: cancelText,
                            closeOnAction: true,
                            type: 'ghost'
                        },
                        {
                            icon: 'fa fa-check',
                            text: confirmText,
                            action: async function () {
                                deleteOneTravelOrder();
                            },
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            } else {

                $().customModal({
                    destroyOnClose: true,
                    showCloseButton: true,
                    type: "alert",
                    text: data.Message,
                    buttons: [
                        {
                            icon: 'fa fa-check',
                            text: confirmText,
                            closeOnAction: true,
                            type: 'primary'
                        }
                    ]
                });
            }
        },
        error: function () {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#GeneralErrorMessage").val() + error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function deleteOneTravelOrder() {
    location.href = $("#DeleteOne").val();
}

function checkDeleteStatus() {
    let deleteStatus = url.searchParams.get("deleteStatus");
    let deleteError = url.searchParams.get("deleteError");
    let errorText;

    if (deleteError === "TrvlOrderLinkedDoc") {
        errorText = $("#TrvlOrderLinkedDoc").val();
    } else {
        errorText = $("#CannotDeleteTrvlOrder").val();
    }

    if (deleteStatus === "False") {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: errorText,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

//#endregion SINGLE DELETE

//#region MULTI DELETE

var items = [];
var allowedAcKeys = [];

function deleteMultipleTravelOrders() {
    var deleteText = $("#DeleteTravelOrder").val();
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    if (selectedKeys.length > 1) {
        deleteText = $("#DeleteTravelOrders").val();
    }

    getMultipleDeleteStatuses();

    var closeOnConfirm = true;
    if (items.length > 0) {
        closeOnConfirm = false;
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: deleteText,
        buttons: [
            {
                icon: 'fa fa-times',
                text: cancelText,
                action: async function () {
                    isDeleteConfirmed(false);
                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    if (closeOnConfirm === false) {
                        showDeleteMessages();
                    }
                    else {
                        isDeleteConfirmed(true);
                    }
                },
                closeOnAction: closeOnConfirm,
                type: 'primary'
            }
        ]
    });
}

function getMultipleDeleteStatuses() {
    var url = $("#DeleteStatus").val();

    $.ajax({
        cache: false,
        type: "get",
        url: url,
        async: false,
        data: {
            acKeys: JSON.stringify(selectedKeys)
        },
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].DisplayMessage === true) {
                    items.push({ ackey: data[i].AcKeyDisplay, message: data[i].Message });
                }

                if (data[i].CanBeDeleted === true) {
                    allowedAcKeys.push(data[i].AcKey);
                }
            }
        }
    });
}

function showDeleteMessages() {
    var confirmText = $("#Confirm").val();
    var cancelText = $("#Cancel").val();

    var output = "";
    for (var i = 0; i < items.length; i++) {
        output += "<p>" + items[i].message + "</p>";
    }

    var buttons = [
        {
            icon: 'fa fa-times',
            text: cancelText,
            closeOnAction: true,
            action: async function () {
                isDeleteConfirmed(false);
            },
            type: 'ghost'
        }
    ];
    if (allowedAcKeys.length > 0) {
        buttons.push(
            {
                icon: 'fa fa-check',
                text: confirmText,
                action: async function () {
                    isDeleteConfirmed(true);
                },
                closeOnAction: true,
                type: 'primary'
            }
        );
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: output,
        buttons: buttons
    });
}

function isDeleteConfirmed(inputValue) {
    if (inputValue === false) {
        items = [];
        allowedAcKeys = [];
    } else {
        deleteManyTravelOrders(allowedAcKeys);
        items = [];
        allowedAcKeys = [];
    }
}

function deleteManyTravelOrders(allowedAcKeys) {
    let url = $("#Delete").val();
    $.ajax({
        cache: false,
        type: "post",
        url: url,
        data: {
            acKeys: allowedAcKeys
        },
        success: function (result) {
            location.reload();
        },
        error: function (error) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#GeneralErrorMessage").val() + error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function checkDeleteStatusMultiple() {
    let tempDataString = $("#TempData").val();
    let stringArray = tempDataString.replace(/\(/g, '').replace(/\)/g, '').split(",");
    let trvlOrder = $("#TrvlOrderLoc").val();
    let trvlOrderHasDoc = $("#TrvlOrderHasDocumentLoc").val();
    let trvlOrderCannotDelete = $("#TrvlOrderCannotDeleteLoc").val();

    let tupleArray = [];
    for (let i = 0; i < stringArray.length; i += 2) {
        let tuple = [stringArray[i], stringArray[i + 1]];
        tupleArray.push(tuple);
    }

    let errorMessage = "";
    let secondElement;

    for (let i = 0; i < tupleArray.length; i++) {
        secondElement = tupleArray[i][1].trim();
        if (secondElement == "TrvlOrderLinkedDoc") {
            errorMessage += trvlOrder + " " + tupleArray[i][0] + " " + trvlOrderHasDoc + "<br>";
        }
        else {
            errorMessage += trvlOrder + " " + tupleArray[i][0] + " " + trvlOrderCannotDelete + "<br>";
        }
    }

    if (errorMessage.length > 0) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: errorMessage,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

//#endregion MULTI DELETE

//#endregion DELETE TRAVEL ORDER

//#region COPY
var copyNotAllowedAcKeys = [];
var copyAllowedAcKeys = [];

function copyTravelOrder() {
    getMultipleCopyStatuses();

    if (copyNotAllowedAcKeys.length > 0) {
        showCopyMessages();
    }
    if (copyAllowedAcKeys.length > 0) {
        selectedKeys = copyAllowedAcKeys;
        performAction($("#Copy").val());
    }

    copyNotAllowedAcKeys = [];
    copyAllowedAcKeys = [];
}

function getMultipleCopyStatuses() {
    $.ajax({
        cache: false,
        type: "GET",
        url: $("#CopyStatus").val(),
        async: false,
        data: {
            acKeys: JSON.stringify(selectedKeys)
        },
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].DisplayMessage === true) {
                    copyNotAllowedAcKeys.push({ ackey: data[i].AcKeyDisplay, message: data[i].Message });
                }

                if (data[i].CanBeCopied === true) {
                    copyAllowedAcKeys.push(data[i].AcKey);
                }
            }
        }
    });
}

function showCopyMessages() {
    let output = "";
    for (var i = 0; i < copyNotAllowedAcKeys.length; i++) {
        output += "<p>" + copyNotAllowedAcKeys[i].message + "</p>";
    }

    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: output,
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#Cancel").val(),
                closeOnAction: true,
                type: 'ghost'
            }
        ]
    });
}

//#endregion COPY

//#region PRINT PDF
$(document).ready(function () {
    $("#printButton.disabled").prop("disabled", true);

    $("#street-search").on('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
        }
    });
});

function printTravelOrder(loc) {
    var url = $("#Print").val();

    var params = JSON.stringify(selectedKeys);
    var finalUrl = url + "?acKeys=" + params;
    if (loc) {
        finalUrl = finalUrl + "&loc=" + loc;
    }

    window.open(finalUrl, '_blank');
}

//#endregion PRINT PDF

//#region SUBJECT MODAL

function openSubjectModal() {
    $("#subjectModal").modal('show');
}

function saveSubjectInDistances() {
    var formData = $("#subjectForm").serializeArray();

    $.post($("#CreateSubjectUrl").val(), formData)
        .done(function (response) {

            if (response.Success) {
                $("#PartnerId").val(response.subject.Id);
                handleSubjectSelection(response.subject.Id);
                clearValidationErrors();
                $("#subjectModal").modal("hide");
            }
            else {
                clearValidationErrors();

                if (response.errors)
                    displayResponseValidationErrors(response);
            }
        });
}

function handleSubjectSelection(subjectId) {

    $.getJSON($("#searchSubjectsUrl").val(), { subjectId: subjectId },
        function (data) {
            var node = $("#NewNode");

            if ($(node).hasClass("select2-hidden-accessible")) {
                var newOption = new Option(data.Key, data.Value, true, true);
                $('#NewNode').append(newOption).trigger('change');
            }
            else {
                node.val(data.Value);
            }

            $("#subjectModal").modal('hide');
        });
}

//#endregion SUBJECT MODAL

//#region DISTANCE KILOMETERS

function setDistanceKilometers(subjectField, fieldId, fromTypeahead = false, isUpdate = false, distanceNum = 0) {
    if (checkIfWorkerIsEmpty()) return;

    let subjectId;
    let subjectText;
    var whichRouteInKmField = $("#whichRouteInKmField").val();
    var oneWay = $("#oneWay").val();
    var returnWay = $("#returnWay").val();
    let url = getFieldValue(subjectUrlSelector);

    if (fromTypeahead) {
        subjectId = $("#" + subjectField).data("Id");
        subjectText = $("#" + subjectField).data("Text");
    } else {
        subjectId = subjectField.val();
        subjectText = subjectField.text();
    }

    if (!subjectId && fromTypeahead) {
        subjectId = getFieldValue(subjectField);
    }

    var interval = 600;
    $.ajax({
        cache: false,
        type: 'GET',
        url: url,
        contentType: "application/json",
        data: { subjectId: subjectId },
        success: function (data) {
            data = JSON.parse(data);

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "question",
                text: whichRouteInKmField,
                buttons: [
                    {
                        icon: 'fa fa-times',
                        text: oneWay,
                        action: async function () {
                            if (data && data.Km && data.Km > 0) {
                                setFieldValue(fieldId, data.Km);
                                setTimeout(function () {
                                    if (isUpdate) {
                                        updateDistance("#DistancesTable-" + distanceNum, "#" + distanceNum, distances, false, $(subjectField).val());
                                    }
                                    else if (insertingPosition === true) {
                                        insertPosition();
                                    }
                                    else {
                                        addNewDistance();
                                    }
                                }, interval);
                            }
                            else {
                                searchDistanceFromGoogle(getDistanceStartPoint(), subjectText, fieldId, false);
                                setTimeout(function () {
                                    if (isUpdate) {
                                        updateDistance("#DistancesTable-" + distanceNum, "#" + distanceNum, distances, false, $(subjectField).val());
                                    }
                                    else if (insertingPosition === true) {
                                        insertPosition();
                                    }
                                    else {
                                        addNewDistance();
                                    }
                                }, interval);
                            }
                        },
                        closeOnAction: true,
                        type: 'ghost'
                    },
                    {
                        icon: 'fa fa-check',
                        text: returnWay,
                        action: async function () {
                            if (data && data.Km && data.Km > 0) {
                                var twoWay = data.Km * 2;
                                setFieldValue(fieldId, twoWay);
                                setTimeout(function () {
                                    if (isUpdate) {
                                        updateDistance("#DistancesTable-" + distanceNum, "#" + distanceNum, distances, false, $(subjectField).val());
                                    }
                                    else if (insertingPosition === true) {
                                        insertPosition();
                                    }
                                    else {
                                        addNewDistance();
                                    }
                                }, interval);
                            }
                            else {
                                searchDistanceFromGoogle(getDistanceStartPoint(), subjectText, fieldId, true);
                                setTimeout(function () {
                                    if (isUpdate) {
                                        updateDistance("#DistancesTable-" + distanceNum, "#" + distanceNum, distances, false, $(subjectField).val());
                                    }
                                    else if (insertingPosition === true) {
                                        insertPosition();
                                    }
                                    else {
                                        addNewDistance();
                                    }
                                }, interval);
                            }
                        },
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        },
        error: function (error) {
            searchDistanceFromGoogle(getDistanceStartPoint(), subjectText, fieldId, isConfirm);
        }
    });
}

function initializeDistancePlaceChange() {
    var whichRouteInKmField = $("#whichRouteInKmField").val();
    var oneWay = $("#oneWay").val();
    var returnWay = $("#returnWay").val();

    var input = document.getElementById('street-search');
    var autocomplete = new google.maps.places.Autocomplete(input);
    selectFirstOnEnter(input);

    var interval = 1000;
    autocomplete.addListener('place_changed', function () {
        if (checkIfWorkerIsEmpty()) return;

        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "question",
            text: whichRouteInKmField,
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: oneWay,
                    action: async function () {
                        searchDistanceFromGoogle(getDistanceStartPoint(), input.value, 'Km', false);

                        if (insertingPosition === true) {
                            setTimeout(function () { insertPosition(); }, interval);
                        }
                        else {
                            setTimeout(function () { addNewDistance(); }, interval);
                        }
                    },
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: returnWay,
                    action: async function () {
                        searchDistanceFromGoogle(getDistanceStartPoint(), input.value, 'Km', true);

                        if (insertingPosition === true) {
                            setTimeout(function () { insertPosition(); }, interval);
                        }
                        else {
                            setTimeout(function () { addNewDistance(); }, interval);
                        }
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    });
}

if (typeof google === 'object' && typeof google.maps === 'object') {
    google.maps.event.addDomListener(window, 'load', initializeDistancePlaceChange);
}

function searchDistanceFromGoogle(source, destination, fieldId, twoWayTrip) {

    let request = prepareGoogleSearchRequest(source, destination);

    var directionsService = new google.maps.DirectionsService();

    directionsService.route(request, function (response, status) {

        if (status === google.maps.DirectionsStatus.OK) {

            var directionsData = response.routes[0].legs[0];
            if (directionsData) {
                var distance = directionsData.distance.text;
                var roundKm = parseAndRoundKilometers(distance);
                kilometers = parseInt(roundKm);
                if (twoWayTrip === true) {
                    var doubleKm = kilometers * 2;
                    setFieldValue(fieldId, doubleKm);
                } else {
                    setFieldValue(fieldId, kilometers);
                }
            }
        }
        else {
            console.log('directions failed');
        }
    });

    return true;
}

function parseAndRoundKilometers(distance) {
    const currentLocalization = $("#CurrentUserLocalization").val();
    let cleanedDistance;

    if (currentLocalization == $("#LocalizationEU").val() || currentLocalization == $("#LocalizationEN").val()) {
        cleanedDistance = distance.replace(/[^\d.-]/g, "");
    } else {
        cleanedDistance = distance.replace(/\./g, "").replace(",", ".").replace(/[^\d.-]/g, "");
    }

    return Math.round(parseFloat(cleanedDistance));
}

function prepareGoogleSearchRequest(source, destination) {
    return request = {
        origin: source,
        destination: destination,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
}

function getDistanceStartPoint() {
    var startingPoint = $("#startLocationAddress").val();
    return startingPoint;
}

function getDistanceEndPoint() {
    let node = $(nodeInRowSelector);

    if (node.hasClass('select2-hidden-accessible')) {
        var selectedValue = node.select2('data');
        if (selectedValue.length > 0) {
            return selectedValue[0].text;
        }
    }
    else {
        //TODO:Handle google search textbox
    }
}

function toggleNodeSelection() {
    $("#node-db-search").toggle();
    $("#node-google-search").toggle();

    var node = $("#NewNode");
    var streetSearch = $("#street-search");

    node.attr("id", "street-search");
    node.attr("name", "street-search");
    node.removeAttr("required");

    streetSearch.attr("id", "NewNode");
    streetSearch.attr("name", "NewDistance.Node");
    streetSearch.attr("required", "required");
}

//#endregion DISTANCE KILOMETERS

//#region HEADER DEFAULTS
function workerDropDownChange(sourceElementId, targetElementId, callBackFunction) {
    let workerId;
    const docType = $("#HeaderDocumentType").val();

    if ($("#TravelOrdersUserCanWrite").val() === "True") {
        workerId = $("#" + sourceElementId).val();
    } else {
        const sourceElement = getDropDownSelection(sourceElementId);
        workerId = sourceElement.id;
    }
    docTypePermissionCtrl.loadPermissions(docType, null, workerId);
    $.ajax({
        type: "POST",
        url: $("#GetEmployeesTrvl").val(),
        contentType: "application/json",
        data: JSON.stringify({ id: workerId, docType: docType }),
        success: function (data) {
            data = JSON.parse(data);
            callBackFunction[0](data, targetElementId[0]);
            callBackFunction[1](data, targetElementId[1]);

            if (data) {
                checkWorkerLegislation(data.Localization);
                setLegislation(data.Localization);
            }
        }
    });
}

function docTypeDropDownChange(sourceElementId, targetElementId, callBackFunction, parameterName) {
    let sourceElement = getDropDownSelection(sourceElementId);
    let url = getElementAttributeValue(targetElementId, 'data-change-url');

    $.ajax({
        type: 'get',
        url: url,
        dataType: 'json',
        data: { [parameterName]: sourceElement.id },
        success: function (data) {
            callBackFunction[0](data, targetElementId[0]);
            callBackFunction[1](data, targetElementId[1]);
            callBackFunction[2](data, targetElementId[2]);
        }
    });
}



function setLegislation(legislation) {
    let currentLegislation = $("#CurrentLegislation");
    currentLegislation.val(legislation);
}

function checkWorkerLegislation(legislation) {
    let legislationBA = $("#LegislationBA").val();
    let legislationRS = $("#LegislationRS").val();
    let legislationBD = $("#LegislationBD").val();

    if (legislation === legislationBA) {
        if (!$(".legislationRSBD").hasClass("hidden")) {
            $(".legislationRSBD").addClass("hidden");
        }
    }
    else if (legislation === legislationRS || legislation === legislationBD) {
        if ($(".legislationRSBD").hasClass("hidden")) {
            $(".legislationRSBD").removeClass("hidden");
        }
    }
    changeTableHeader(legislation);
}

function setWorkerDropDown(data, dropDownId) {
    if ($("#" + dropDownId).parents('.header-worker-div').hasClass('document-head-disabled-input')) {
        return;
    }

    if (data) {
        !data.Worker ? data.Worker = "" : data.Worker;
        !data.WorkerFullName ? data.WorkerFullName = "" : data.WorkerFullName;

        setDropdownValue(data.Worker, data.Worker + ' | ' + data.WorkerFullName, dropDownId);
    }
}

function setVehicleDropDown(data, dropDownId) {
    if (data && data.VehicleRegistrationNumber !== null) {
        setDropdownValue(data.VehicleRegistrationNumber, data.VehicleRegistrationNumber, dropDownId);
    }
}

function setJobDropDown(data, dropDownId) {
    if (data) {
        setDropdownValue(data.Job, data.Job, dropDownId);

        if (data.Job == null) {
            $("#" + dropDownId).select2('val', '');
        }
    }
}

function setDepartmentDropDown(data, dropDownId) {
    if (data) {
        setDropdownValue(data.Department, data.Department, dropDownId);

        if (data.Department == null) {
            $("#" + dropDownId).select2('val', '');
        }
    }
}

function setStatusDropdown(data, dropDownId) {
    // Set docType for status dropdown data url
    $("#" + dropDownId).attr('data-url', $("#GetTravelOrderStatusesUrl").val() + "?docType=" + data.DocumentType);

    if (data) {
        setDropdownValue(data.VerifyStatus, data.VerifyStatusName, dropDownId);

        if (data.VerifyStatus == null) {
            $("#" + dropDownId).select2('val', '');
        }
    }
}

function setTravelOrdersDocTypePermissions(data, dropDownId) {
    docTypePermissionCtrl.loadPermissions($("#" + dropDownId).val(), null, $('#HeaderWorker').val());
}
//#endregion HEADER DEFAULTS

//#region CURRENCY

function convertCurrency(dateId, currencyId, fxRateId, originalValueId, convertedValueId, tableId, rowNum, type) {
    var defaultFxRate = $("#defaultFxRate").val();
    var dateValue = getFieldValue(dateId);

    if (dateValue) {
        var date = toStandardDateFormatString(dateValue);
        $.getJSON($("#GetFxRateUrl").val(),
            {
                currency: getFieldValue(currencyId),
                date: date
            },
            function (data) {
                if (data !== 0) {
                    setFieldsValues(data, defaultFxRate, originalValueId, fxRateId, convertedValueId);

                    if (tableId && rowNum && type) {
                        saveDailyAllowExpense(tableId, rowNum, type);
                    }
                }
            });
    }
}

function getDefaultCurrency() {
    var currency = $("#current-currency").val();
    var newOption = new Option(currency, currency, true, true);
    $('.default-currency').append(newOption);
    $(".default-currency-text").text(currency);
}

function setDefaultCurrency(fieldId) {
    var currency = $("#current-currency").val();
    var newOption = new Option(currency, currency, true, true);
    $("#" + fieldId).append(newOption).trigger('change');
}
//#endregion CURRENCY

//#region UPLOAD FILES
function dropifyUpload() {
    var error = $("#GeneralErrorMessage").val();
    var remove = $("#Remove").val();
    var dragOrClick = $("#DragAndDropOrClickToReplace").val();
    var dragOrClickToReplace = $("#DragAndDropOrClickToReplace").val();
    var fileSizeMessage = $("#FileSizeMessage").val();
    var archive = $("#Archive").val();
    var classification = $("#Classification").val();
    var docType = $("#DocType").val();
    var incorrectDocType = $("#IncorrectDocTypeSettings").val();

    var dr = $('.dropify').dropify({
        messages: {
            'default': dragOrClick,
            'replace': dragOrClickToReplace,
            'remove': remove,
            'error': error
        },
        error: {
            'fileSize': fileSizeMessage
        }
    });

    var allowSubmit = true;
    dr.on('dropify.errors', function (event, element) {
        allowSubmit = false;
    });

    if (!archive || !classification) {
        allowSubmit = false;
    }

    $('.dropify').on('change', function () {

        uploadAttachmentTileTO(function () {
            setTimeout(function () { $('.dropify-loader').css('display', 'block'); }, 600);
            saveAttachments();
        }, allowSubmit);
    });

    var cc = paw.com.CameraCaptureComponent.create($('#camera-capture'), function (captured) {
        uploadAttachmentTileTO(function () {
            paw.com.CameraCaptureComponent.createThumbnailPreview(captured.blob).then(function ($thumbnail) {
                cc.showPreloader($thumbnail);
                saveAttachments(
                    paw.com.CameraCaptureComponent.setFormData($("#pn-form")[0], 'FilesToUpload', captured, cc)
                );
            });

        }, allowSubmit);


    });
    if (paw.com.CameraCaptureComponent.detectDevice() === 'mobile') {
        $('.camera-capture-wrapper').parent().css({
            'display': 'flex'
        });
        $('.camera-capture-wrapper').next().css({
            'max-width': '50%',
            'width': '50%',
            'padding-left': '8px'
        });
        $('.camera-capture-wrapper').removeClass('hidden');


    }
    else if (!$('.camera-capture-wrapper').hasClass('hidden')) {
        $('.camera-capture-wrapper').addClass('hidden');
        $('.camera-capture-wrapper').parent().css({
            'display': ''
        });
        $('.camera-capture-wrapper').next().css({
            'max-width': '',
            'width': '',
            'padding-left': ''
        });
    }
}

function uploadAttachmentTileTO(onUpload, allowSubmit) {
    if (allowSubmit) {
        onUpload();
    }
    else {
        $("#createDocumentIrisMessage").text(stringFormat(incorrectDocType, docType));
        $("#openDocTypeSettings").attr("onclick", "window.open('" + $("#OpenDocumentUrl").val() + "', '_blank')");
        $("#openClassificationSettings").attr("onclick", "window.open('" + $("#SettingsClassificationsUrl").val() + "', '_self')");
        $("#help-url").attr("onclick", "window.open('" + $("#DocTypeHelpUlr").val() + "', '_blank')");
        $("#createDocumentErrorModal").modal("show");
        $('#createDocumentErrorModal').on('hidden.bs.modal', function () {
            $('.dropify-clear').click();
        })
    }
}

function saveAttachments(formData) {
    $.ajax({
        url: $("#SaveAttachmentsUrl").val(),
        type: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: formData || new FormData($("#pn-form")[0]),
        success: function (data) {
            if (data && data === 'T') {
                var url = window.location.href;
                url = url.split("&")[0];
                url = url + "&isNewDistance=false&toDocTab=true";
                location.href = url;
            }
            else {
                handleRequestError();
            }
        },
        error: function (data) {
            handleRequestError();
        }
    });
}

//#endregion UPLOAD FILES

//#region HANDLE NOTES
var selectedNoteNo = '';
var selectedPurposeNo = '';
function openReturnNote(distanceNum) {
    selectedNoteNo = distanceNum;
    $("#item-note").val($("#return-note-" + distanceNum).val());
    $("#pn-modal").modal('show');
}

function saveReturnNote() {
    const noteValue = $("#item-note").val();
    $("#return-note-" + selectedNoteNo).val(noteValue);
    $(`#${selectedNoteNo}-ReturnNoteDistance`).val(noteValue);

    handleNoteButtonClass(noteValue, "#note-button-" + selectedNoteNo);
    updateDistance("#DistancesTable-" + selectedNoteNo, "#" + selectedNoteNo, distances, false);
}

function openTravelPurposeModal(distanceNum) {
    selectedPurposeNo = distanceNum;
    $("#distance-purpose-note").val($(`#${distanceNum}-Purpose`).val());
    $("#travel-purpose-modal").modal('show');
}

function saveDistancePurpose() {
    const purposeValue = $("#distance-purpose-note").val();
    $(`#${selectedPurposeNo}-Purpose`).val(purposeValue);

    handleNoteButtonClass(purposeValue, "#purpose-note-button-" + selectedPurposeNo);
    updateDistance("#DistancesTable-" + selectedPurposeNo, "#" + selectedPurposeNo, distances);
}

function handleNoteButtonClass(note, selector) {
    if (note.length > 0) {
        $(selector).addClass("text-primary");
    } else {
        $(selector).removeClass("text-primary");
    }
}

function updateTravelPurpose(element, distanceNum) {
    selectedPurposeNo = distanceNum;
    const purposeValueFromDropdown = $(element).val();
    $(`#${distanceNum}-Purpose`).val(purposeValueFromDropdown)
    $("#distance-purpose-note").val(purposeValueFromDropdown);
    saveDistancePurpose();
}
//#endregion HANDLE NOTES

//#region DESIGN HELPERS

function showDistanceDateTimePicker() {
    $('.distance-dt-picker').on("dp.show", function (e) {
        $('.divided-content-scrollable-not-mobile').css({
            "overflow-y": "unset",
            "overflow-x": "unset"
        });
    });

    $('.distance-dt-picker').on("dp.hide", function (e) {
        $('.divided-content-scrollable-not-mobile').css({
            "overflow-y": "auto",
            "overflow-x": "hidden"
        });
    });
}

function showExpenseDateTimePicker() {
    if (window.innerWidth > 768) {
        $('.expense-dt-picker').on("dp.show", function (e) {
            $('.divided-content-scrollable-not-mobile').css({
                "overflow-y": "unset",
                "overflow-x": "unset"
            });
        });

        $('.expense-dt-picker').on("dp.hide", function (e) {
            $('.divided-content-scrollable-not-mobile').css({
                "overflow-y": "auto",
                "overflow-x": "hidden"
            });
        });
    }
}

function checkIfWorkerIsEmpty() {
    if (!getFieldValue(headerWorkerSelector)) {
        $(".header-worker-div").find(".field-validation-valid").text($("#RequiredInput").val());
        $("#NewNode").val("").trigger("change");

        return true;
    }

    return false;
}

//#endregion DESIGN HELPERS

//#region HELPERS

function performAction(url) {
    $.ajax({
        cache: false,
        type: "post",
        url: url,
        data: {
            acKeys: selectedKeys
        },
        success: function (acKeys) {
            selectedKeys = [];

            // Focus and scroll to copied travel order
            if (acKeys.length == 1) {
                var copiedAcKey = acKeys[0];
                $('#travelorders').DataTable().ajax.reload(function (data) {
                    var rows = data.data;
                    for (var i = 0; i < rows.length; i++) {
                        if (rows[i].AcKey == copiedAcKey) {
                            var newRow = $("#travelorders tbody tr").eq(i);
                            newRow.first().addClass('side-menu-item-active').children(":first").addClass('side-menu-item-active');
                            newRow[0].scrollIntoView({ behavior: "smooth", block: "start" });
                        }
                    }
                });
            } else {
                $('#travelorders').DataTable().ajax.reload();
                $('#travelorders tbody tr')[0].scrollIntoView({ behavior: "smooth", block: "start" });
            }
        },
        error: function (error) {
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#GeneralErrorMessage").val() + error,
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: confirmText,
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function dropDownChange(sourceElementId, targetElementId, callBackFunction, parameterName) {
    let sourceElement = getDropDownSelection(sourceElementId);
    let url = getElementAttributeValue(targetElementId, 'data-change-url');

    $.ajax({
        type: 'get',
        url: url,
        dataType: 'json',
        data: { [parameterName]: sourceElement.id },
        success: function (data) {
            for (i = 0; i < targetElementId.length; i++) {
                callBackFunction[i](data, targetElementId[i]);
            }
        },
        error: function (error) {
            //console.log(error);
        }
    });
}

function jobDropDownChange(sourceElementId, targetElementId, callBackFunction) {
    let workerId;
    const docType = $("#HeaderDocumentType").val();

    if ($("#TravelOrdersUserCanWrite").val() === "True") {
        workerId = $("#" + sourceElementId).val();
    } else {
        const sourceElement = getDropDownSelection(sourceElementId);
        workerId = sourceElement.id;
    }

    $.ajax({
        type: "POST",
        url: $("#GetEmployeesTrvl").val(),
        contentType: "application/json",
        data: JSON.stringify({ id: workerId, docType: docType }),
        success: function (data) {
            data = JSON.parse(data);
            callBackFunction[0](data, targetElementId[0]);
        }
    });
}

function isEmpty(value) {
    return typeof value === 'string' && !value.trim() || typeof value === 'undefined' || value === null;
}

function errorNotify(message) {
    if (!isEmpty(message)) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#GeneralErrorMessage").val() + error,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: confirmText,
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    }
}

//#endregion HELPERS

//#region DAILY ALLOWS

function setDailyAllows(num) {
    var selectedDailyAllow = $("#DailyAllow-" + num + " :selected").val();
    var dailyAllowNo = $("#anDailyAllowNo-" + num);
    var dailyAllowPrice = $("#anPriceDailyAllow-" + num);
    var currency = $("#Currency-" + num);
    var dailyAllowValue = $("#Value-" + num);
    var currentLoc = $("#currentLoc").val();
    var locMK = $("#locMK").val();
    var locBA = $("#locBA").val();

    var dailyAllowNoConst = $("#dailyAllowNoConst").val();
    var dailyAllowNoBAMKConst = $("#dailyAllowNoBAMKConst").val();
    var url = $("#DailyAllowAmountUrl").val();

    dailyAllowNo.val(null);
    dailyAllowPrice.val(null);
    dailyAllowValue.val(null);
    currency.val(null);

    var date = null;

    $.getJSON(url,
        {
            dailyAllow: selectedDailyAllow,
            dateTimeFrom: date
        },
        function (data) {
            if (data) {
                dailyAllowNo.val(dailyAllowNoConst);
                if (currentLoc === locBA || currentLoc === locMK) {
                    dailyAllowNo.val(dailyAllowNoBAMKConst);
                }

                dailyAllowPrice.val(formatWithThousands(data.anPriceTo));
                var newOption = new Option(data.acCurrency, data.acCurrency, true, true);
                currency.append(newOption).trigger('change');
            }
        });
}

function SetDailyAllowFxRate(num, currencyId, fxRateId, dailyAllowNoId, priceDailyAllowId, valueId, tableId, rowId, type) {
    var defaultFxRate = $("#defaultFxRate").val();
    var dateValue = $("#" + num + "-DateHourFrom").val();

    if (dateValue) {
        var date = toStandardDateFormatString(dateValue);
        $.getJSON($("#GetFxRateUrl").val(),
            {
                currency: getFieldValue(currencyId),
                date: date
            },
            function (data) {
                if (data && data !== 0) {
                    var fxRateNumber = data.toString().replace(".", ",");
                    if (data === 1) {
                        fxRateNumber = defaultFxRate;
                    }
                    var dailyAllowNo = Number(toStandardDecimalString(getFieldValue(dailyAllowNoId)));
                    var priceDailyAllow = Number(toStandardDecimalString(getFieldValue(priceDailyAllowId)));
                    var fxRate = Number(data);

                    if (!isNaN(dailyAllowNo) && !isNaN(priceDailyAllow)) {
                        let dailyAllowValue = dailyAllowNo * priceDailyAllow * fxRate;
                        setFieldValue(fxRateId, fxRateNumber);
                        setFieldValue(valueId, formatWithThousands(dailyAllowValue));
                    }
                }

                if (tableId && rowId && type) {
                    saveDailyAllowExpense(tableId, rowId, type);
                }
            });
    }
}

//#endregion DAILY ALLOWS

//#region EXPENSES

function SetExpenseSettings(num) {
    var currentDateTime = new Date(new Date().getTime());
    $("#" + num + "-PriceCurrency").val(0);
    $("#" + num + "-DateCost").data("DateTimePicker").date(currentDateTime);
    setDefaultCurrency(num + "-ExpensesCurrency");
}

function clearAmount(num) {
    var amount = $("#" + num + "-PriceCurrencyString");
    amount.val(null);
}
//#endregion EXPENSES

function openDailyAllowDropdown(num) {
    $("#expand-dailyAllow-" + num).focus();
}

function setMileageByVehicle() {
    var regNo = $("#HeaderCarRegNo").val();
    var url = $("#GetVehicle").val();
    var priceKmRate = $("#PriceKmRate").val();

    var total = $("#total-value");
    var mileage = $("#mileage-total");
    var totalValue = Number(toStandardDecimalString(total.text()));
    var mileageValue = Number(toStandardDecimalString(mileage.text()));

    $.getJSON(url,
        {
            regNo: regNo
        },
        function (data) {
            if (data) {
                if (data.IsCompanyCar || data.IsRented) {
                    $('.mileage-input-value').each(function () {
                        var num = $(this).data("num");
                        var headerCost = $("#distance-total-amount-" + num);
                        headerCost.text(headerCost.data("cost"));
                        $(this).val("0,00");
                    });

                    if (!isNaN(totalValue) && !isNaN(mileageValue)) {
                        var totalEnd = totalValue - mileageValue;
                        total.text(display2decimalAmount(totalEnd));
                        mileage.text("0,00");
                    }
                } else {
                    var mileageSum = 0;
                    $('.mileage-input-value').each(function () {
                        var priceKm = Number(toStandardDecimalString(priceKmRate));
                        var km = Number($(this).data("km"));
                        var distanceMileage = priceKm * km;
                        mileageSum = mileageSum + distanceMileage;

                        var num = $(this).data("num");
                        var headerCost = $("#distance-total-amount-" + num);

                        var distanceTotal = Number(toStandardDecimalString(headerCost.data("cost"))) + distanceMileage;
                        headerCost.text(display2decimalAmount(distanceTotal));
                        $(this).val(display2decimalAmount(distanceMileage));
                    });

                    var totalSum = totalValue + mileageSum;
                    total.empty();
                    total.text(display2decimalAmount(totalSum));
                    mileage.empty();
                    mileage.text(display2decimalAmount(mileageSum));
                }
            }
        });
}

function display2decimalAmount(amount) {
    return amount.toFixed(2).toString().replace(".", ",");
}

function initializeHomeCheckBox() {
    var elems = Array.prototype.slice.call(document.querySelectorAll('#home .js-switch'));
    elems.forEach(function (html) {
        var switchery = new Switchery(html, { size: 'small' });
    });
}

$(document).ready(function () {
    let isCreate = $("#AcKeyTotals").val() === "" ? true : false;
    addDocTypeToCostTypeDataUrl();
    openIrisModal();
    initializeHomeCheckBox();
    checkDeleteStatus();
    if ($("#TempData").val()) { checkDeleteStatusMultiple(); }
    if ($("#isLicenseCM").val() === "True") { setGlobalHelpUrl($("#TravelOrdersLicenseCMHelpUrl").val()) }

    let currentLegislation = $("#CurrentLegislation").val();
    var expenseNote = $("input[name='Note']");
    var dailyAllowFxRate = $("input[name='anFxRate']");
    var addDailyAllowButton = $("#addDailyAllow");
    var addExpenseButton = $("#addExpense");
    var dateFrom = $("#TravelDateFrom");
    var dateTo = $("#TravelDateTo");

    if ($("#Header_AcKey").val()) {
        $("#HeaderDocumentType").prop("disabled", true);
        $("#to-docType-div").addClass("document-head-disabled-input");
    }

    changeTableHeader(currentLegislation);

    // On enter key add row
    dailyAllowFxRate.on("keypress", function (event) {
        onEnterAddRow(addDailyAllowButton);
    });

    addDailyAllowButton.on("keypress", function (event) {
        onEnterAddRow(addDailyAllowButton);
    });

    expenseNote.on("keypress", function (event) {
        onEnterAddRow(addExpenseButton);
    });

    addExpenseButton.on("keypress", function (event) {
        onEnterAddRow(addExpenseButton);
    });

    // On enter key filter by date 
    dateFrom.on("keypress", function (event) {
        onEnterFilterByDate(dateFrom);
    });

    dateTo.on("keypress", function (event) {
        onEnterFilterByDate(dateTo);
    });

    $("#street-search").change(function () {
        setTimeout(() => {
            if ($("#NewNode").hasClass("gm-err-autocomplete")) {
                $("#IRISContinueClickable").attr("onclick", "disableGoogleSearchButton()");
                $("#IRISContinueText").text($("#ContinueUsingExpiredGoogleMapKey").val());
                $('#google-api-key-expired-iris').modal('show');
            }
        }, "100")
    })

    if ($(window).width() <= 768) {
        $(".departmentDropdown").children("select").removeAttr("data-search-width")
        $(".costDrvDropdown").children("select").removeAttr("data-search-width")
        $(".purposeDropdown").children("select").removeAttr("data-search-width")
    }

    disableWorkerDropdownIfUserHasOwnDataPermission();

    $("#printButton").removeAttr("href");
    $("#saveButton").removeAttr("href");

    $('#HeaderDocumentType').on('change', function () {
        var selectedDocType = $(this).val();
        var currentWorkerDataUrl = $("#HeaderWorker").attr("data-url");
        var updatedWorkerDataUrl = currentWorkerDataUrl.replace(/(docType=).*?(&)/, '$1' + selectedDocType + '$2');
        $("#HeaderWorker").attr("data-url", updatedWorkerDataUrl);
    });

    if ($("#TravelOrdersUserCanWrite").val() === "True" && isCreate) {
        workerDropDownChange('HeaderWorker', ['HeaderCarRegNo', 'HeaderJob'], [setVehicleDropDown, setJobDropDown], 'filterBy', true);
    }

    initializeSortableRenumberTable();

    $(document).on('click', '.travel-order-position', function () {
        lastClickedAccordion = $(this);
    });
});

$(window).on('load', function (e) {
    setTimeout(() => {
        getGoogleSearch();
    }, "100");
});

function disableWorkerDropdownIfUserHasOwnDataPermission() {
    let isOwndataPermission = $("#HasOwnDataPermission").val();
    if (isOwndataPermission === 'True') {
        $("#Workers").attr("disabled", true);
    }
}

//set Allows-Expenses table mobile/tablet

function setDynamicTables() {
    var distancesCount = parseInt($("#DistancesCount").val());

    for (var i = 0; i < distancesCount; i++) {
        setAllowsAndExpensesTable("DailyAllowsTable-" + i);
        setAllowsAndExpensesTable("ExpensesTable-" + i);
    }
}

function setAllowsAndExpensesTable(tableId) {
    $('#' + tableId + ' tbody tr').each(function (index) {
        var num = index - 1;
        var rowClass = "collapse-table-row-" + num;
        $(this).addClass(rowClass);
    });

    setActionButtons(tableId);
}

function setActionButtons(tableId) {

    var tabletWidth = window.innerWidth >= 576 && window.innerWidth <= 768;
    var mobileWidth = window.innerWidth < 576;

    var colNum = $("#" + tableId + " > tbody > tr:first > td").length;

    if (tabletWidth === true && colNum > 5) {
        $('#' + tableId + ' tr').each(function () {
            $('th:last', this).remove().insertAfter($('th:nth-child(4)', this));
            $('td:last', this).remove().insertAfter($('td:nth-child(5)', this));
        });

        setExpandIcon(tableId);
    }

    if (mobileWidth === true && colNum > 2) {
        $('#' + tableId + ' tr').each(function () {
            $('th:last', this).remove().insertAfter($('th:nth-child(2)', this));
            $('td:last', this).remove().insertAfter($('td:nth-child(2)', this));
        });

        setExpandIcon(tableId);
    }
}

function setExpandIcon(tableId) {
    $('#' + tableId + ' tbody tr td:nth-child(2)').each(function (index) {
        var num = index - 1;
        var expandIcon = "expand-icon-" + num;
        $(this).prepend('<i id="' + expandIcon + '" +  class="fa fa-caret-right" onclick="expandTravelOrderRow(\'' + tableId + '\', \'' + num + '\')"></i>');
    });
}

function expandTableRow(tableId, index) {

    var rowId = "#" + tableId + " .collapse-table-row-" + index;
    var expandIconId = "#expand-icon-" + index;
    var borderClass = "border-left-success";
    var iconRight = "fa-caret-right";
    var iconDown = "fa-caret-down";

    if ($(rowId).hasClass(borderClass)) {
        $(rowId).removeClass(borderClass);
        $(expandIconId).addClass(iconRight);
        $(expandIconId).removeClass(iconDown);
    }
    else {
        $(rowId).addClass(borderClass);
        $(expandIconId).removeClass(iconRight);
        $(expandIconId).addClass(iconDown);
    }

    $(rowId).find('td').each(function (column, td) {
        if ($(td).css('display') == 'none') {
            $(td).css("display", "flex");
        }
        else if ($(td).css('display') == 'flex') {
            $(td).css("display", "none");
        }
    });
}

function changeTableHeader(legislation) {
    let currentLoc = $("#currentLoc").val();
    let locBA = $("#locBA").val();
    let locMK = $("#locMK").val();

    let legislationBA = $("#LegislationBA").val();
    let legislationRS = $("#LegislationRS").val();
    let legislationBD = $("#LegislationBD").val();
    let minusFive = $("#MinusFive").val();
    let minusTwenty = $("#MinusTwenty").val();
    let minusThirty = $("#MinusThirty").val();
    let minusFifty = $("#MinusFifty").val();
    let minusEighty = $("#MinusEighty").val();
    let plusSeventy = $("#PlusSeventy").val();

    let breakfast = $(".da-breakfast");
    let lunch = $(".da-lunch");
    let dinner = $(".da-dinner");
    let thBreakfast = $("#th-breakfast");
    let thLunch = $("#th-lunch");
    let thDinner = $("#th-dinner");

    if (currentLoc === locBA) {
        if (legislation === legislationBA) {
            thBreakfast.text(minusThirty);
            breakfast.attr("label", minusThirty);
            thLunch.text(plusSeventy);
            lunch.attr("label", plusSeventy);
        } else if (legislation === legislationRS || legislation === legislationBD) {
            thBreakfast.text(minusFifty);
            breakfast.attr("label", minusFifty);
            thLunch.text(minusEighty);
            lunch.attr("label", minusEighty);
            thDinner.text(minusThirty);
            dinner.attr("label", minusThirty);
        }
    }

    if (currentLoc === locMK) {
        thBreakfast.text(minusFifty);
        breakfast.attr("label", minusFifty);
        thLunch.text(minusTwenty);
        lunch.attr("label", minusTwenty);
        thDinner.text(minusFive);
        dinner.attr("label", minusFive);
    }
}

function setPercentageOnCreate(num) {
    let breakfast = $("#IsBreakfastIncluded-" + num);
    let lunch = $("#IsLunchIncluded-" + num);
    let dinner = $("#IsDinnerIncluded-" + num);
    let dailyAllow = $("#anPriceDailyAllow-" + num);
    let factor = $("#CalcFactor-" + num);
    let value = $("#Value-" + num);
    let dailyAllowNo = $("#anDailyAllowNo-" + num);

    let parameters = [breakfast, lunch, dinner, dailyAllow, factor, value, dailyAllowNo];
    calculatePercentage(parameters);
}

function setPercentage(num1, num2, num3) {
    let breakfast = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "IsBreakfastIncluded" + num3);
    let lunch = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "IsLunchIncluded" + num3);
    let dinner = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "IsDinnerIncluded" + num3);
    let dailyAllow = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "anPriceDailyAllow" + num3);
    let factor = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "CalcFactor" + num3);
    let value = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "Value" + num3);
    let dailyAllowNo = $("#DistanceViewModels" + num1 + "DailyAllows" + num2 + "anDailyAllowNo" + num3);

    let parameters = [breakfast, lunch, dinner, dailyAllow, factor, value, dailyAllowNo];
    calculatePercentage(parameters);
}

function calculatePercentage(parameters) {
    let defaultFactor = $("#DefaultFactor").val();
    let factorMinus5 = $("#FactorMinus5").val();
    let factorMinus20 = $("#FactorMinus20").val();
    let factorMinus30 = $("#FactorMinus30").val();
    let factorMinus50 = $("#FactorMinus50").val();
    let factorMinus80 = $("#FactorMinus80").val();
    let factorPlus70 = $("#FactorPlus70").val();

    let currentLoc = $("#currentLoc").val();
    let locBA = $("#locBA").val();
    let locMK = $("#locMK").val();

    let legislationBA = $("#LegislationBA").val();
    let legislationRS = $("#LegislationRS").val();
    let legislationBD = $("#LegislationBD").val();
    let currentLegislation = $("#CurrentLegislation").val();

    let dailyAllowToInt = parseFloat(toStandardDecimalString(parameters[3].val()));
    let dailyAllowNoToInt = parseFloat(toStandardDecimalString(parameters[6].val()));

    if (currentLoc === locBA) {
        //Breakfast
        if (parameters[0].val() === "true") {
            if (currentLegislation === legislationBA) {
                let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus30)
                let percentageValueStr = formatWithThousands(percentageValue);

                parameters[4].val(factorMinus30);
                parameters[5].val(percentageValueStr);
            } else if (currentLegislation === legislationRS || currentLegislation === legislationBD) {
                let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus50)
                let percentageValueStr = formatWithThousands(percentageValue);

                parameters[4].val(factorMinus50);
                parameters[5].val(percentageValueStr);
            }
            //Lunch
        } else if (parameters[1].val() === "true") {
            if (currentLegislation === legislationBA) {
                let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorPlus70)
                let percentageValueStr = formatWithThousands(percentageValue);

                parameters[4].val(factorPlus70);
                parameters[5].val(percentageValueStr);
            } else if (currentLegislation === legislationRS || currentLegislation === legislationBD) {
                let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus80)
                let percentageValueStr = formatWithThousands(percentageValue);

                parameters[4].val(factorMinus80);
                parameters[5].val(percentageValueStr);
            }
            //Dinner
        } else if (parameters[2].val() === "true") {
            if (currentLegislation === legislationRS || currentLegislation === legislationBD) {
                let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus30)
                let percentageValueStr = formatWithThousands(percentageValue);

                parameters[4].val(factorMinus30);
                parameters[5].val(percentageValueStr);
            }
            //DEFAULT
        } else {
            parameters[4].val(defaultFactor);
            parameters[5].val(formatWithThousands(dailyAllowToInt * dailyAllowNoToInt));
        }
    }

    if (currentLoc === locMK) {
        //Breakfast
        if (parameters[0].val() === "true") {
            let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus50)
            let percentageValueStr = formatWithThousands(percentageValue);

            parameters[4].val(factorMinus50);
            parameters[5].val(percentageValueStr);
            //Lunch
        } else if (parameters[1].val() === "true") {
            let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus20)
            let percentageValueStr = formatWithThousands(percentageValue);

            parameters[4].val(factorMinus20);
            parameters[5].val(percentageValueStr);
            //Dinner
        } else if (parameters[2].val() === "true") {
            let percentageValue = dailyAllowToInt * dailyAllowNoToInt * stringToFloat(factorMinus5)
            let percentageValueStr = formatWithThousands(percentageValue);

            parameters[4].val(factorMinus5);
            parameters[5].val(percentageValueStr);
            //DEFAULT
        } else {
            parameters[4].val(defaultFactor);
            parameters[5].val(formatWithThousands(dailyAllowToInt * dailyAllowNoToInt));
        }
    }
}

function stringToFloat(str) {
    return parseFloat(str.replace(",", "."));
}

function saveChanges(dateId) {
    let defaultDateValue = $("#" + dateId).val();

    $("#" + dateId).on('blur', function () {
        if (this.value != defaultDateValue) {
            $("#saveButton").click();
        }
    });
}

function onEnterAddRow(buttonId) {
    if (event.keyCode === 13) {
        event.preventDefault();
        buttonId.trigger("click");

        // After row is added, switch focus on Cost Type
        document.activeElement.blur();
        $("#0-CostType").next().find(".select2-selection--single").focus();
    }
}

function onEnterFilterByDate(dateId) {
    if (event.keyCode === 13) {
        event.preventDefault();
        $(dateId).datepicker("show");
        $(".active.day").trigger("click");
    }
}

$("#travelorders").on('click', '.clickable-icon', function () {
    $('tr').each(function () {
        $(this).removeClass('side-menu-item-active');
    });

    $(this).closest('tr').addClass('side-menu-item-active');

    $(".side-panel-handle").on('click', function () {
        $('tr').each(function () {
            $(this).removeClass('side-menu-item-active');
        });
    });
});

function openIrisModal() {
    var acKeyIRIS = $("#AcKeyIRIS").val();
    if (acKeyIRIS) {
        $('#travel-orders-iris').modal('show');
    }
}

function focusVehicleDropdown() {
    $("#travel-orders-iris").modal('hide');
    $("#HeaderCarRegNo").select2('open').next().find(".select2-selection--single").focus();
    searchOnFocus();
}

function searchOnFocus() {
    var select2_open;
    $(document).on('focus', '.select2-selection--single', function (e) {
        select2_open = $(this).parent().parent().siblings('select');
        select2_open.select2('open');
    });
}

function setNotForPayout(num, expId, notForPayId, tableId, rowNum, type) {
    if (!getFieldValue(expId)) {
        return;
    }

    var notForPay = $("#" + notForPayId);

    $.ajax({
        type: "GET",
        url: $("#GetExpTypeUrl").val(),
        data: {
            docType: $("#DocType").val(),
            type: parseInt(getFieldValue(expId))
        },
        success: function (data) {
            if (data.NotForPay) {
                notForPay.prop('checked', true);
                notForPay.val("true");
            }
            if (!data.NotForPay) {
                notForPay.prop('checked', false);
                notForPay.val("false");
            }

            //Causes cost dropdown to reopen on change
            //$("#" + expId).next().find(".select2-selection--single").focus();

            if (tableId && rowNum && type) {
                saveDailyAllowExpense(tableId, rowNum, type);
            }
        }
    });
}

function setNotForPayoutCheckedValue(checkBoxId) {
    let checked = $("#" + checkBoxId).val();

    if (checked === false || checked === "false") {
        $("#" + checkBoxId).prop('checked', true);
        $("#" + checkBoxId).val("true");
    }
    else if (checked === true || checked === "true") {
        $("#" + checkBoxId).prop('checked', false);
        $("#" + checkBoxId).val("false");
    }
}

function confirmDeleteAttachment(attachmentId) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteMessageLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: function () {
                    deleteAttachment(attachmentId);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function deleteAttachment(attachmentId) {
    $.get($("#DeleteAttachmentUrl").val() + "?docId=" + $("#Id").val() + "&attachId=" + attachmentId, function (response) {
        if (response) {
            $("#attachmentRow-" + attachmentId).remove();
            location.reload();
        } else {
            $().customModal({
                title: "",
                destroyOnClose: true,
                showCloseButton: true,
                type: "error",
                text: $("#GeneralErrorLoc").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary'
                    }
                ]
            });
        }
    });
}

function initializeNewDistanceInput($element, localization) {
    let searchDistanceUrl = $element.attr('dataUrl');
    let focusOpen = true;

    if (/*$("#distance-accordion")[0].children.length !== 0 ||*/ screen.width <= 768) { //focusOpen breaks Destination input field for mobile if set to true
        focusOpen = false;
    }

    $element.customTypeahead({
        value: "Id",
        display: "Name",
        width: "40%",
        minWidth: "330px",
        minSearchLength: 0,
        focusOpen: focusOpen,
        paginate: false,
        columns: [
            { name: localization.company, value: "Id", width: "25%" },
            { name: localization.name, value: "Name", width: "35%" },
            { name: localization.address, value: "Address", width: "20%" },
            { name: localization.gridzipcode, value: "ZipCode", width: "20%" }
        ],
        localization: { noResults: localization.noResults },
        url: searchDistanceUrl,
        urlRequestMethod: "POST",
        onSelect: function (data) {
            item = {
                id: data.Id, name: data.Name, address: data.Address, zipCode: data.ZipCode
            };

            $("#NewNode").next("input").val(item.id + " | " + item.name + " | " + item.address + " | " + item.zipCode);
            $("#NewNode").data("Id", item.id);
            $("#NewNode").data("Text", `${item.id} | ${item.name} | ${item.address} | ${item.zipCode}`);
            setDistanceKilometers("NewNode", "Km", true);
        }
    });

    $("#NewNode").next("input").on("blur", function () {
        if ($(this).val() === "") {
            $("#NewNode").val("");
        }
    });
}

var enterDestinationWithoutGoogleApiKey = false;
function checkGoogleApiKey(apiKey) {
    if ($("#UserHasTravelOrdersPermission").val() == "True" && !enterDestinationWithoutGoogleApiKey && (apiKey == "" || apiKey == null)) {
        $("#HeaderWorker").select2("close");
        $('#google-api-key-iris').modal('show');
    }
}

function closeGoogleApiKeyIris() {
    $('#google-api-key-iris').modal('hide');
    enterDestinationWithoutGoogleApiKey = true;
}

function setGoogleApiKey() {
    window.location.href = $("#CompanyPageUrl").val();
}

function saveAndPrint(printUrl) {
    disablePrintButton();
    disableSaveButton();

    if (screen.width > 768) {
        var printWindow;
        printWindow = createPrintWindow(printWindow);
    }

    $.ajax({
        url: $("#SaveHeaderAndDistancesUrl").val(),
        type: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: new FormData($("#pn-form")[0]),
        success: function (data) {
            if (screen.width > 768) {
                printWindow.location = printUrl;
            } else if (screen.width <= 768) {
                downloadPdfMobile(printUrl);
            }
            enableSaveButton();
            enablePrintButton();
        },
        error: function (data) {
            enablePrintButton();
            handleRequestError(false);
        }
    });
}

function downloadPdfMobile(printUrl) {
    var link = document.createElement('a');
    link.href = printUrl;
    link.download = 'TravelOrder.pdf';
    link.dispatchEvent(new MouseEvent('click'));
}

function disablePrintButton() {
    swapLoadingIcon(true, "printButton", "far fa-print");
    $("#printButton").addClass("print-btn-disable");
}

function enablePrintButton() {
    swapLoadingIcon(false, "printButton", "far fa-print");
    $("#printButton").removeClass("print-btn-disable");
}

function disableSaveButton() {
    swapLoadingIcon(true, "saveButton", "fa fa-save");
    $("#saveButton").addClass("print-btn-disable");
}

function enableSaveButton() {
    swapLoadingIcon(false, "saveButton", "fa fa-save");
    $("#saveButton").removeClass("print-btn-disable");
}

function addNewDistance() {
    let acKey = $("#AcKeyTotals").val();

    if ($("#UserHasTravelOrdersPermission").val() == "False") return;
    if (!$("#NewNode").val()) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#NewDistanceCannotBeEmpty").val()
        });

        return;
    }

    if (acKey) {
        disableSaveButton();
        $.ajax({
            url: $("#CreateDistanceUrl").val(),
            type: 'POST',
            processData: false,
            contentType: false,
            cache: false,
            enctype: 'multipart/form-data',
            data: new FormData($("#pn-form")[0]),
            success: function (data) {
                var url = window.location.href;
                url = url.split("&")[0];
                url = url + "&isNewDistance=true&toDocTab=false";
                location.href = url;
            },
            error: function (data) {
                handleRequestError();
            }
        });
    }
    else {
        saveAndDisableSaveButton();
    }
}

function saveAndDisableSaveButton() {
    $("#isPrint").val(false);
    disableSaveButton();
    $("#pn-form").submit();
}

function getGoogleSearch() {
    let isGoogleSearch = (isAutoTest) ? isGoogleSearchEnabled : localStorage.getItem("isGoogleSearch");

    if (isGoogleSearch === "true") {
        $("#googleSearchBtn").addClass("google-btn-focused");

        var element = document.querySelector("#NewNode");
        if (element && element.style.height === "0px") {
            toggleNodeSelection();
        }

        let apiKey = $("#apiKey").val();
        checkGoogleApiKey(apiKey);
    }
}

function setGoogleSearch() {
    let googleSearch = (isAutoTest) ? isGoogleSearchEnabled : localStorage.getItem("isGoogleSearch");

    if (googleSearch !== null) {
        let isGoogleSearch = (googleSearch === "true");
        toggleGoogleSearch(!isGoogleSearch);
    }
    else {
        toggleGoogleSearch(true);
    }
}

function toggleGoogleSearch(isGoogleSearch) {
    if (isAutoTest) {
        isGoogleSearchEnabled = isGoogleSearch;
    }
    else {
        localStorage.setItem("isGoogleSearch", isGoogleSearch);
    }
    $("#googleSearchBtn").toggleClass("google-btn-focused");
    if (!isGoogleSearch) {
        $("#googleSearchBtn").blur();

        if ($("#NewNode").hasClass("gm-err-autocomplete")) {
            document.getElementById("googleSearchBtn").disabled = true;
        }
    }
}

function disableGoogleSearchButton() {
    setGoogleSearch();
    toggleNodeSelection();
    document.getElementById("googleSearchBtn").disabled = true;
}

function expandTravelOrderRow(tableId, index, isOnChange = false) {
    if (window.screen.width < 768) {
        var rowId = "#" + tableId + " .collapse-table-row-" + index;
        var expandIconObj = $("#" + tableId).find("#expand-icon-" + index);
        var borderClass = "border-left-success";
        var iconRight = "fa-caret-right";
        var iconDown = "fa-caret-down";

        $(rowId).find('td').each(function (column, td) {
            if ($(td).css('display') == 'none') {
                $(td).css("display", "flex");

                $(rowId).addClass(borderClass);
                expandIconObj.removeClass(iconRight);
                expandIconObj.addClass(iconDown);
            }
            else if ($(td).css('display') == 'flex' && !isOnChange) {
                $(td).css("display", "none");

                $(rowId).removeClass(borderClass);
                expandIconObj.addClass(iconRight);
                expandIconObj.removeClass(iconDown);
            }
        });
    }
}

function setFieldsValues(data, defaultFxRate, originalValueId, fxRateId, convertedValueId) {
    var fxRateNumber = data.toFixed(6).toString().replace(".", ",");
    if (data === 1) {
        fxRateNumber = defaultFxRate;
    }
    let originalValue = Number(toStandardDecimalString(getFieldValue(originalValueId)));
    let conversionRate = Number(data);

    if (!isNaN(originalValue) && !isNaN(conversionRate)) {
        let fieldValue = originalValue * conversionRate;
        setFieldValue(fxRateId, fxRateNumber);
        setFieldValue(convertedValueId, formatWithThousands(fieldValue));
    }
}

function validateDistanceDate(rowId) {
    let dateHourFrom = $(rowId + "-DateHourFrom").val();
    let dateHourTo = $(rowId + "-DateHourTo").val();

    if (dateHourFrom == "" || dateHourTo == "") {
        showErrorModal($("#ArrivalDateAndDepartureDateMustNotBeEmpty").val());
        return false;
    }

    dateHourFrom = moment(dateHourFrom, 'DD.MM.YYYY H:mm:ss').toDate();
    dateHourTo = moment(dateHourTo, 'DD.MM.YYYY H:mm:ss').toDate();
    if (dateHourTo < dateHourFrom) {
        if (dateHourTo.toDateString() === dateHourFrom.toDateString()) {
            showErrorModal($("#ArrivalTimeMustBeAfterDepartureTime").val());
        }
        else {
            showErrorModal($("#ArrivalDateMustBeAfterDepartureDate").val());
        }
        return false;
    }

    return true;
}

function updateDistance(tableId, rowId, type, isDateChanged = false, node = "", changedDateId = "") {
    if (isDateChanged && !$("#" + changedDateId).hasClass("date-changed")) {
        return;
    }
    if (isDateChanged && !validateDistanceDate(rowId) || $("#UserHasTravelOrdersPermission").val() == "False") {
        return;
    }

    disableSaveButton();

    let model = generateRequestModel(tableId, rowId, type);
    if (node) {
        model["Node"] = node;
        model["acSubject"] = node;
    }

    getNotInCurrencyData(model, rowId);

    $.ajax({
        url: $("#DistanceUpdateUrl").val(),
        type: 'POST',
        data: model,
        success: function (data) {
            if (isDateChanged) {
                location.reload();
            }
            else {
                handleSaveRequestSuccess(data, rowId, tableId, type);
                updateStartEndKM();
            }
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function confirmDeleteDistance(tableId, rowId, acKey, ordinalNumber) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#ConfirmDeleteMessageLoc").val(),
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: function () {
                    deleteDistance(tableId, rowId, acKey, ordinalNumber);
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function deleteDistance(tableId, rowId, acKey, ordinalNumber) {
    disableSaveButton();
    $.ajax({
        url: $("#DeleteDistanceUrl").val() + "?acKey=" + acKey + "&distanceId=" + ordinalNumber,
        type: 'GET',
        success: function (data) {
            DeleteDistance(tableId, rowId);
            getTotals();
            enableSaveButton();
            getDistancesForRenumbering();
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function saveExpense(tableId, rowId, type, prefixId = "", idPrefixId = "", anNo = 0) {
    let rowNum = rowId.split("-").pop();
    let dateCost = $("#" + rowNum + "-DateCost").val();

    if (dateCost === null || dateCost === undefined || dateCost === "") {
        dateCost = moment(new Date()).format("DD.MM.YYYY HH:mm");
        $("#" + rowNum + "-DateCost").val(dateCost);

        let currentElementId = $("#" + rowNum + "-DateCost").attr("id");
        let name = "DateCost";
        let currencyId = currentElementId.replace(name, "ExpensesCurrency");
        let fxRateId = currentElementId.replace(name, "FxRate");
        let priceCurrencyStringId = currentElementId.replace(name, "PriceCurrencyString");
        let valueId = currentElementId.replace(name, "Value");
        let date = toStandardDateFormatString(dateCost);

        $.getJSON($("#GetFxRateUrl").val(),
            {
                currency: getFieldValue(currencyId),
                date: date
            },
            function (data) {
                if (data !== 0) {
                    var defaultFxRate = $("#defaultFxRate").val();
                    setFieldsValues(data, defaultFxRate, priceCurrencyStringId, fxRateId, valueId);
                    saveDailyAllowExpense(tableId, rowId, type, prefixId, idPrefixId, anNo);
                }
            });
    }
    else {
        saveDailyAllowExpense(tableId, rowId, type, prefixId, idPrefixId, anNo);
    }

}

function saveDailyAllowExpense(tableId, rowId, type, prefixId = "", idPrefixId = "", anNo = 0) {
    if (!ValidateRow($(rowId)) || $("#UserHasTravelOrdersPermission").val() == "False") {
        return;
    }

    let url;
    if (type === dailyAllows) {
        url = $("#SaveDailyAllowUrl").val();
    } else if (type === expenses) {
        url = $("#SaveExpenseUrl").val();
    }

    let model = generateRequestModel(tableId, rowId, type);
    disableSaveButton();

    $.ajax({
        url: url,
        type: 'POST',
        data: model,
        success: function (data) {
            handleSaveRequestSuccess(data, rowId, tableId, type, prefixId, idPrefixId, anNo);
        },
        error: function (error) {
            handleRequestError();
        }
    });

    expandTravelOrderRow(tableId.slice(1), "-1");
}

function generateRequestModel(tableId, rowId, type) {
    let elements = type === distances ? $(tableId + " tr td").find("select, input") : $(tableId + " " + rowId + " td").find("select, input");
    let model = {};

    elements.each(function () {
        let name = $(this).attr("name").split(".")[2] == undefined ? $(this).attr("name") : $(this).attr("name").split(".")[2];
        let value = $(this).val();

        if (name.includes("Date")) {
            value = moment(value, 'DD.MM.YYYY H:mm:ss').toISOString();
        }
        model[name] = value;
    });

    return model;
}

function handleSaveRequestSuccess(data, rowId, tableId, type, prefixId = "", idPrefixId = "", anNo = 0) {
    if (data != null) {
        if (rowId.includes("DailyAllowsCreate") || rowId.includes("ExpensesCreate")) {
            if (type === expenses) {
                anNo = data["AnCostNo"];
            }
            var newRow = AddRow(rowId, prefixId, tableId, idPrefixId, anNo, true);

            // decorate delete button with doc type permissions and execute doc type permissions evaluation for newly added row's children
            var $deleteBtn = $(newRow).find('#delete-record-' + tableId.replace('#', '') + '-' + newRow.attr("id"));
            docTypePermissionCtrl.decorateElt($deleteBtn, 'Delete', 'hide');
            docTypePermissionCtrl.evalPermissions(null, $(newRow));

            fillRowFileds(tableId, "#" + newRow.attr("id"), data, type, anNo, true);
            setCreateRowDefaultCurrencyFxRate(rowId, type);
        }
        else {
            fillRowFileds(tableId, rowId, data, type);
        }
        updateDistanceTable(tableId, data, type);

    }
    getTotals();
    enableSaveButton();
}

function updateDistanceTable(tableId, data, type) {
    let anNo;
    switch (type) {
        case distances: anNo = data.OrdinalNumber; break;
        case dailyAllows: anNo = data.AnNo; break;
        default: anNo = data.ExpenseAnNo;
    }
    getDistanceTableData(tableId, anNo, type)
}

function getDistanceTableData(tableId, anNo, type) {
    let distanceNum = tableId.split("-").pop();
    let acKey = $("#AcKeyTotals").val();

    if (type !== distances) {
        getDistance(distanceNum, acKey, anNo);
    }
    getDistanceHeader(distanceNum, acKey, anNo);
}

function getDistanceHeader(distanceNum, acKey, anNo) {
    $.ajax({
        url: $("#GetDistanceHeaderUrl").val() + "?acKey=" + acKey + "&ordinalNumber=" + anNo + "&distanceNum=" + distanceNum,
        type: 'GET',
        success: function (data) {
            let selectNodeId = "#" + distanceNum + "-NodeDistance";
            let div = $(selectNodeId).closest('div');
            let name = $(selectNodeId).attr('name');
            let dataUrl = $(selectNodeId).attr('data-url');
            let selectData = $(selectNodeId).select2('data');
            let filterBy = $(selectNodeId).attr("filter-by");

            var $headerTable = $("#distance-accordion-" + distanceNum).children('table');
            $headerTable.html(data);

            // evaluate doc type permissions after distance header DOM was rebuilt
            docTypePermissionCtrl.evalPermissions(null, $headerTable);

            $(div).html(
                BuildSelectList(selectNodeId,
                    name,
                    dataUrl,
                    selectData,
                    filterBy
                ));

            initializeSelect2WithAPI(selectNodeId);
            getDefaultCurrency();
            setDropdownMenuPN();
        },
        error: function (error) {
        }
    });
}

function getDistance(distanceNum, acKey, anNo) {
    $.ajax({
        url: $("#GetDistanceWithAddressUrl").val() + "?acKey=" + acKey + "&ordinalNumber=" + anNo,
        type: 'GET',
        success: function (data) {
            fillRowFileds("#DistancesTable-" + distanceNum, "#" + distanceNum, data, distances, 0, false);
        },
        error: function (error) {
        }
    });
}

function setCreateRowDefaultCurrencyFxRate(rowId, type) {
    let rowNum = rowId.split("-").pop();
    let defaultFxRate = $("#defaultFxRate").val();
    let defaultFactor = $("#defaultFactor").val();
    if (type === dailyAllows) {
        $('#anFxRate-' + rowNum).val(defaultFxRate);
        $('#CalcFactor-' + rowNum).val(defaultFactor);
        setDefaultCurrency('Currency-' + rowNum);
    }
    else if (type === expenses) {
        $('#' + rowNum + '-FxRate').val(defaultFxRate);
        setDefaultCurrency(rowNum + '-ExpensesCurrency');
    }
}

function handleRequestError() {
    enableSaveButton();
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "alert",
        text: $("#RequestError").val(),
    });
    location.reload();
}

function fillRowFileds(tableId, rowId, data, type, anNo, create) {
    let elements = type === distances ? $(tableId + " tr td").find("select, input") : $(tableId + " " + rowId + " td").find("select, input");

    elements.each(function () {
        let name = $(this).attr("name").split(".")[2];
        let value = data[name];
        if (($(this).hasClass("thousands-with-decimals") || $(this).hasClass("two-dec-places-num")) && !isNaN(value)) {
            value = formatWithThousands(value);
        }
        else if ($(this).hasClass("six-dec-places-num") && !isNaN(value)) {
            value = formatWithDecPlaces(value, 6);
        }
        if (name.includes("Date") && value) {
            let date = new Date(parseInt(value.substr(6)));
            value = moment(date).format("DD.MM.YYYY HH:mm");
        }
        if ($(this).is(':checkbox')) {
            $(this).prop('checked', value);
            if (value) {
                $(this).attr('checked', 'checked');
            }
        }

        $(this).val(value);
        $(this).attr('placeholder', '');

        if (create && type === dailyAllows) {
            addDailyAllowEvents($(this), name, tableId, rowId, anNo, type);
        }
        else if (create && type === expenses) {
            addExpenseEvents($(this), name, tableId, rowId, anNo, type);
        }
    });

    if (create) {
        let anNo = type === dailyAllows ? data.AnNo : data.ExpenseAnNo;
        addButtonEvent(tableId, rowId, data.QId, type, anNo);
    }
}

function addButtonEvent(tableId, rowId, qId, type, anNo) {
    let buttons = $(tableId + " " + rowId + " td").find("button");
    let table = tableId.split("#").pop();
    let row = rowId.split("#").pop();
    buttons.each(function () {
        $(this).attr('onclick',
            "deleteDailyAllowExpense('" + table + "', " + row + ", " + qId + ", '" + type + "', " + anNo + ")");
    });
}

function addDailyAllowEvents(element, name, tableId, rowId, anNo, type) {
    let dailyAllowNum = tableId.split("-").pop();
    let currentElementId = element.attr("id");

    if (name === "DailyAllow" || name === "anDailyAllowNo" || name === "anPriceDailyAllow" || name === "Currency") {
        let currencyId = replaceLast(name, "Currency", currentElementId);
        let anFxRateId = replaceLast(name, "anFxRate", currentElementId);
        let anDailyAllowNoId = replaceLast(name, "anDailyAllowNo", currentElementId);
        let anPriceDailyAllowId = replaceLast(name, "anPriceDailyAllow", currentElementId);
        let valueId = replaceLast(name, "Value", currentElementId);

        element.attr('onchange',
            "SetDailyAllowFxRate('" + dailyAllowNum + "', '" + currencyId + "', '" + anFxRateId + "', '" + anDailyAllowNoId + "', '" + anPriceDailyAllowId + "', '" + valueId + "', '" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (element.hasClass('daily-allow-checkbox')) {
        let rowNum = rowId.split("#").pop();
        let includedId1;
        let includedId2;
        let anDailyAllowNoId = currentElementId.replace(name, "anDailyAllowNo");

        if (name === "IsBreakfastIncluded") {
            includedId1 = currentElementId.replace(name, "IsLunchIncluded");
            includedId2 = currentElementId.replace(name, "IsDinnerIncluded");
        }
        else if (name === "IsLunchIncluded") {
            includedId1 = currentElementId.replace(name, "IsBreakfastIncluded");
            includedId2 = currentElementId.replace(name, "IsDinnerIncluded");
        }
        else {
            includedId1 = currentElementId.replace(name, "IsBreakfastIncluded");
            includedId2 = currentElementId.replace(name, "IsLunchIncluded");
        }

        element.attr('onchange',
            "setCheckedValue('" + currentElementId + "', '" + includedId1 + "', '" + includedId2 + "', '" + anDailyAllowNoId + "'); setPercentage(" + dailyAllowNum + "," + rowNum + "," + anNo + "); saveDailyAllowExpense('" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (name === "anPriceFieldBonus" || name === "Value" || name === "anFxRate") {
        element.attr('onchange',
            "saveDailyAllowExpense('" + tableId + "', '" + rowId + "', '" + type + "')");
    }

    if (name === "Currency") {
        element.addClass("daily-allow-currency");
    }

    if (name === "DailyAllow")
        addExpandableTableRows(tableId, rowId, element);
}

function addExpenseEvents(element, name, tableId, rowId, anNo, type) {
    let expensesNum = tableId.split("-").pop();
    let currentElementId = element.attr("id");
    let dateCostId = currentElementId.replace(name, "DateCost");

    if (name === "CostType") {
        let notForPaymentId = currentElementId.replace(name, "NotForPayment");
        element.attr('onchange',
            "setNotForPayout('" + expensesNum + "', '" + currentElementId + "', '" + notForPaymentId + "', '" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (name === "PriceCurrencyString" || name === "Currency" || name === "DateCost") {
        let currencyId = currentElementId.replace(name, "Currency");
        let fxRateId = currentElementId.replace(name, "FxRate");
        let priceCurrencyStringId = currentElementId.replace(name, "PriceCurrencyString");
        let valueId = currentElementId.replace(name, "Value");
        let action = name === "DateCost" ? 'onblur' : 'onchange';
        element.attr(action,
            "convertCurrency('" + dateCostId + "', '" + currencyId + "', '" + fxRateId + "', '" + priceCurrencyStringId + "', '" + valueId + "', '" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (name === "NotInCurrency") {
        element.attr('onchange',
            "setCheckedValue('" + currentElementId + "');saveDailyAllowExpense('" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (name === "NotForPayment") {
        element.attr('onchange',
            "setNotForPayoutCheckedValue('" + currentElementId + "');saveDailyAllowExpense('" + tableId + "', '" + rowId + "', '" + type + "')");
    }
    else if (name === "FxRate" || name === "Note") {
        element.attr('onchange',
            "saveDailyAllowExpense('" + tableId + "', '" + rowId + "', '" + type + "')");
    }

    if (name === "CostType")
        addExpandableTableRows(tableId, rowId, element);

    if (name === "PriceCurrencyString") element.attr('onkeydown', "selectFieldOnTab(event," + dateCostId + ")");
}

function addExpandableTableRows(tableId, rowId, element) {
    let rowNum = rowId.split("#").pop();

    var oldParent = element.parent();
    var oldChild = document.getElementById(element.attr("id"));
    var oldChildSibling = oldChild.nextSibling;
    var wrapper = document.createElement('div');

    $(tableId).find("#" + rowNum).removeClass();
    $(tableId).find("#" + rowNum).addClass("collapse-table-row-" + rowNum);

    oldParent.append(wrapper);

    if (window.innerWidth <= 768) {
        oldParent.prepend('<i id="' + "expand-icon-" + rowNum + '" +  class="fa fa-caret-right" onclick="expandTravelOrderRow(\'' + tableId.slice(1) + '\', \'' + rowNum + '\')"></i>');
    }

    wrapper.appendChild(oldChild);
    wrapper.appendChild(oldChildSibling);
    wrapper.style.width = "100%";

    wrapper.setAttribute('onclick',
        "expandTravelOrderRow('" + tableId.slice(1) + "', " + rowNum + ", " + true + ");");
}

function deleteDailyAllowExpense(tableId, rowId, id, type, anNo) {
    let url;
    if (type === dailyAllows) {
        url = $("#DeleteDailyAllowUrl").val() + "?qId=" + id;
    } else if (type === expenses) {
        url = $("#DeleteExpenseUrl").val() + "?qId=" + id;
    }

    disableSaveButton();

    $.ajax({
        url: url,
        type: 'GET',
        success: function (data) {
            DeleteRow(tableId, rowId);
            getDistanceTableData(tableId, anNo, type);
            getTotals();
            enableSaveButton();
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function replaceLast(find, replace, string) {
    var lastIndex = string.lastIndexOf(find);
    if (lastIndex === -1) {
        return string;
    }

    var beginString = string.substring(0, lastIndex);
    var endString = string.substring(lastIndex + find.length);
    return beginString + replace + endString;
}

function getTotals() {
    $.ajax({
        url: $("#GetTravelOrderTotalsUrl").val() + "?acKey=" + $("#AcKeyTotals").val(),
        type: 'GET',
        success: function (data) {
            $("#travel-orders-footer").html(data);
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function showTimeRecordMissingIRIS() {
    let timeRecordMissingDescription = $('#TimeRecordMissingDescription').val()
        .replace('[1]', $('#AcKeyDisplay').val())
        .replace('[2]', $('#dateMin').val())
        .replace('[3]', $('#dateMax').val());

    let addTimeRecordDescription = $('#AddTimeRecordDescription').val()
        .replace('[1]', $('#dateMin').val())
        .replace('[2]', $('#dateMax').val());

    $('#iris-header').text($('#TimeRecordMissing').val());
    $('#iris-message').text(timeRecordMissingDescription);
    $('#option-1-header').text($('#AddTimeRecord').val());
    $('#option-1-text').text(addTimeRecordDescription);
    $('#option-2-header').text($('#Abandon').val());
    $('#option-2-text').text($('#ContinueWithoutTimeRecord').val());
    $('#option-3-header').text($('#ViewInstructions').val());
    $('#option-3-text').text($('#ViewInstructionsDescription').val());

    $('#option-1-clickable').click(function () {
        generateTimeRecordsDocForPN();
    });
    $('#option-3-clickable').click(function () {
        window.open('https://usersite.datalab.eu/wiki/tabid/178/language/en-us/topic/224066/htmlid/1000004631/default.aspx', '_blank')
    });
    $('#blank-iris').modal('show');
}

function generateTimeRecordsDocForPN() {
    const worker = $("#HeaderWorker").val();
    const dateStart = moment($("#dateMin").val(), 'DD.MM.YYYY').toISOString();
    const dateEnd = moment($("#dateMax").val(), 'DD.MM.YYYY').toISOString();

    var xhr = new XMLHttpRequest();
    xhr.open('POST', $("#GenerateTimeRecordsDocForPN").val() + '?DateStart=' + dateStart + '&DateEnd=' + dateEnd + '&Workers=' + worker, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
        if (xhr.status === 200) {
            var blob = xhr.response;
            saveTravelOrderTimeRecord(blob);
            $('#blank-iris').modal('hide');
        } else {
            console.error('Error obtaining timeRecord pdf, status code:', xhr.status);
        }
    }
    xhr.onerror = function () {
        console.error('Error sending request');
    }
    xhr.send();
};

function saveTravelOrderTimeRecord(blob) {
    var dateFrom = $('#dateMin').val().replaceAll('.', '_');
    var dateTo = $('#dateMax').val().replaceAll('.', '_');

    const formData = new FormData();
    formData.append('FilesToUpload', blob, $('#TimeRecord').val() + dateFrom + '-' + dateTo + '.pdf');
    formData.append('acKey', $("#AcKeyTotals").val());

    $.ajax({
        url: $('#SaveTravelOrderTimeRecordUrl').val(),
        type: 'POST',
        dataType: 'json',
        mimeType: 'multipart/form-data',
        contentType: false,
        cache: false,
        processData: false,
        data: formData,
        success: function () {
            location.reload();
        }
    });
}

function timeRecordExists() {
    var dateFrom = $('#dateMin').val().replaceAll('.', '_');
    var dateTo = $('#dateMax').val().replaceAll('.', '_');
    var name = $('#TimeRecord').val() + dateFrom + '-' + dateTo + '.pdf';

    return $('#Files').val().includes(name);
}

function updateHeaderData() {
    if ($("#UserHasTravelOrdersPermission").val() == "False") return

    disableSaveButton();

    if (parseInt($('#daysBetween').val()) > 1 && !timeRecordIRISShown && $("#currentLoc").val() === $("#locSL").val() && !timeRecordExists()) {
        showTimeRecordMissingIRIS();
        enableSaveButton();
        timeRecordIRISShown = true;
        return;
    }

    $.ajax({
        url: $("#UpdateTravelOrderHeaderUrl").val(),
        type: 'PUT',
        data: getHeaderModel(),
        success: function (data) {
            fillHeaderFileds("header", data);
            fillHeaderFileds("home", data);
            updateDistances();
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function getHeaderModel() {
    let model = {};
    model = generateHeaderModel("header", model);
    model = generateHeaderModel("home", model);
    return model;
}

function generateHeaderModel(divId, model) {
    let elements = $("#" + divId).find("select, input");

    elements.each(function () {
        let name = $(this).attr("name").split(".")[1];
        if (name !== undefined && name !== 'TotalKm' && name !== 'CounterAfter' && name !== 'CounterBefore') {
            let value = $(this).val();

            if (name.includes("Date")) {
                value = moment(value, 'DD.MM.YYYY H:mm:ss').toISOString();
            }
            model[name] = value;
        }
    });
    return model;
}

function fillHeaderFileds(divId, data) {
    let elements = $("#" + divId).find("select, input");

    elements.each(function () {
        let name = $(this).attr("name").split(".")[1];
        if (name !== undefined && name !== 'TotalKm' && name !== 'CounterAfter' && name !== 'CounterBefore') {
            let value = data[name];
            if (name.includes("Date") && value) {
                let date = new Date(parseInt(value.substr(6)));
                value = moment(date).format("DD.MM.YYYY");
            }
            $(this).val(value);
            $(this).attr('placeholder', '');
        }
    });
}

function updateDistances() {
    var distanceElements = $("#distance-accordion").find(".distance-table");
    if (distanceElements.length == 0) {
        enableSaveButton();
    }
    distanceElements.each(function () {
        let tableId = "#" + $(this).attr("id");
        let row = $(this).find("tr");
        let rowId = "#" + row.attr("id");

        updateDistance(tableId, rowId, distances);
    });
}

function updateStartEndKM() {
    var distancesCount = parseInt($("#DistancesCount").val());

    var startKM = $("#0-KMCounterBeforeString").val();
    var endKM = $("#" + (distancesCount - 1) + "-KMCounterAfterString").val();

    var totalKM = formatWithThousandsNoDecimals(removeDots(endKM) - removeDots(startKM));

    $("#startKM").val(startKM);
    $("#endKM").val(endKM);
    $("#totalKM").val(totalKM);
}

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

let revertSumHoursCheckbox = false;
function setSumHours() {
    if (revertSumHoursCheckbox) {
        revertSumHoursCheckbox = false;
        return;
    }

    var action = $("#Action").val();
    var distancesLength = $("#DistancesLength").val();
    var text = "";

    if ($("#HeaderSumHours").val() === 'True') {
        $("#HeaderSumHours").removeAttr("checked");
        $("#HeaderSumHours").attr("value", "False");
        text = $("#DoYouWantToTurnOffOptionSumHours").val();
    }
    else {
        $("#HeaderSumHours").attr("checked", true);
        $("#HeaderSumHours").attr("value", "True");
        text = $("#DoYouWantToTurnOnOptionSumHours").val();
    }

    if (action === editAction && distancesLength > 0) {
        confirmSumHoursOnOff(text);
    }
}

function confirmSumHoursOnOff(text) {
    $().customModal({
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: text,
        buttons: [
            {
                icon: 'fa fa-times',
                text: $("#NoLoc").val(),
                action: function () {
                    revertSumHoursCheckbox = true;
                    $("#HeaderSumHours").trigger("click");
                },
                closeOnAction: true,
                type: 'ghost'
            },
            {
                icon: 'fa fa-check',
                text: $("#YesLoc").val(),
                action: function () {
                    handleDistanceDa();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function handleDistanceDa() {
    disableSaveButton();
    $.ajax({
        url: $("#HandleDistancesSumHoursDaUrl").val(),
        type: 'PUT',
        data: getHeaderModel(),
        success: function (data) {
            location.reload();
        },
        error: function (error) {
            enableSaveButton();
        }
    });
}

function openRequestForm() {
    $('#travel-orders-newrequest-modal').modal('show');
}

$(document).on("submit", "#travelorder-newrequest-form", function () {
    $('#LeaderValidation, #WorkerValidation').addClass('hidden');

    if (!$("#Leader").val()) {
        $("#LeaderValidation").removeClass('hidden');
        return false;
    }
    else {
        $("#submit-btn-icon").removeClass("fa fa-check");
        $("#submit-btn-icon").addClass("fa fa-spin fa-spinner");
        return true;
    }
});

function collapseTravelOrderAccordion(id, element) {
    if ($(id).hasClass('in')) {
        $(id).removeClass('in');
        $(id).addClass('collapsed');
        $(element).addClass('collapsed');
    }
    else {
        $(id).addClass('in');
        $(id).removeClass('collapsed');
        $(element).removeClass('collapsed');
    }
}

function selectFieldOnTab(e, field) {
    if (e.key === "Tab") {
        e.preventDefault();
        const fieldId = $(field).attr("id");
        $("#" + fieldId).focus().select();
    }
}

function addDocTypeToCostTypeDataUrl() {
    $('[name*="CostType"]').each(function (index) {
        $(this).attr("data-url", $(this).attr("data-url") + "?docType=" + $("#HeaderDocumentType").val())
    });
}

function openPdfPreview(url) {
    loadPdfPanelContentPAAS($("#pdfPanel"), url, true);
}

function printFromEdit(printType) {
    const printUrl = `${$("#PrintUrl").val()}?PrintType=${printType}&KeyFrom=${$("#AcKeyTotals").val()}`;
    disablePrintButton();
    disableSaveButton();

    printWindow = window.open();
    printWindow.document.write(generatePrintingPage());
    printPAAS("", false, false, printUrl, false);

    enableSaveButton();
    enablePrintButton();
}

function copyExpenseToTravelOrder() {
    const data = {
        FromTravelOrder: $("#FromTravelOrder").val(),
        ToTravelOrder: $("#ToTravelOrder").val(),
        FromPosition: $("#FromPosition").val(),
        ToPosition: $("#ToPosition").val()
    };

    const isDataValid = Object.values(data).every(value => value != null || value != undefined);

    if (!isDataValid) {
        $("#CopyExpenseValidation").removeClass("hidden");
        return;
    }

    $("#CopyExpenseValidation").addClass("hidden");
    swapLoadingIcon(true, "CopyExpenseBtn", "fa fa-check");

    $.ajax({
        url: $("#CopyExpenseToTravelOrder").val(),
        type: 'POST',
        data: data,
        success: function (res) {
            swapLoadingIcon(false, "CopyExpenseBtn", "fa fa-check");

            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: res.Status ? "success" : "error",
                text: res.Status ? $("#CopyTravelOrderExpenseMess").val() : $("#GeneralErrorMessage").val(),
                buttons: [
                    {
                        icon: 'fa fa-check',
                        text: $("#ConfirmLoc").val(),
                        closeOnAction: true,
                        type: 'primary',
                        action: () => $('#copy-expense-modal').modal('hide')
                    }
                ]
            });
        }
    });
}

function setTravelOrderPosition(element, id) {
    const acKey = $(element).val();
    $("#" + id).val(null).trigger('change');

    if (acKey) {
        $("#" + id).attr("data-url", `${$("#GetTravelOrderPositions").val()}?acKey=${acKey}`);
    }
}

function getDistancesForRenumbering() {
    $.ajax({
        url: $("#GetDistancesForRenumberingUrl").val() + "?acKey=" + $("#AcKeyTotals").val(),
        type: 'GET',
        success: function (data) {
            $("#travelorder-renumbering-table").html(data);
            initializeSortableRenumberTable();
        },
        error: function (error) {
            handleRequestError();
        }
    });
}

function initializeSortableRenumberTable() {
    // Make table rows sortable for #TrvlPositionRenumber
    $("#TrvlPositionRenumber tbody").sortable({
        helper: fixHelper,
        axis: "y", // Constrain movement to vertical
        update: function (event, ui) {
            const order = $("#TrvlPositionRenumber tbody tr").map(function () {
                return $(this).index();
            }).get();
        }
    }).disableSelection();

    // Prevent cell width distortion during drag
    function fixHelper(e, ui) {
        ui.children().each(function () {
            $(this).width($(this).width());
        });
        return ui;
    }
}

function saveRenumberedPositions() {
    let renumbered = [];

    $("#TrvlPositionRenumber tbody tr").each(function (index) {
        let position = index + 1;
        const anNoValue = parseInt($(this).find("#anNo").attr("anNo"));

        renumbered.push({
            newPosition: position,
            oldPosition: anNoValue
        });
    });

    if (renumbered.length > 0) {
        saveRenumberedPositionsAsync(renumbered);
    }
    else {
        location.reload();
    }
}

function saveRenumberedPositionsAsync(renumbered) {
    $.ajax({
        url: $("#SaveRenumberedPositionsUrl").val(),
        type: 'POST',
        data: {
            Key: $("#RenumberingAcKey").val(),
            RenumberedItems: renumbered
        },
        success: function (data) {
            if (data.result.Status === true) {
                showRenumberMessage("success", $("#CheckTheValuesInDateFromAndDateTo").val());
            }
            else {
                showRenumberMessage("alert", $("#GeneralErrorMessage").val());
            }
        }
    });
}

function resetRenumberedPositions() {
    const tbody = $("#TrvlPositionRenumber tbody");

    const sortedRows = tbody.find("tr").sort(function (a, b) {
        const anNoA = parseInt($(a).find("#anNo").attr("anNo"), 10);
        const anNoB = parseInt($(b).find("#anNo").attr("anNo"), 10);

        return anNoA - anNoB;
    });

    tbody.append(sortedRows);
}

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

function showInsertPositonConfirmModal() {
    $().customModal({
        id: 'TrvlInsertPositionModal',
        destroyOnClose: true,
        showCloseButton: true,
        type: "question",
        text: $("#AreYouSureYouWantToResetTheDocumentPosition").val(),
        buttons: [
            {
                id: 'TrvlInsertPositionCancelBtn',
                icon: 'fa fa-times',
                text: $("#Cancel").val(),
                closeOnAction: true,
                type: 'ghost'
            },
            {
                id: 'TrvlInsertPositionConfirmBtn',
                icon: 'fa fa-check',
                text: $("#Confirm").val(),
                action: function () {
                    confirmPositionInsert();
                },
                closeOnAction: true,
                type: 'primary'
            }
        ]
    });
}

function confirmPositionInsert() {
    $("#DistancesCreate td input").focus();
    insertingPosition = true;
}

function insertPosition() {
    if ($("#UserHasTravelOrdersPermission").val() == "False") return;

    if (!$("#NewNode").val()) {
        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: $("#NewDistanceCannotBeEmpty").val()
        });

        return;
    }

    if (lastClickedAccordion == null || lastClickedAccordion == undefined) {
        addNewDistance();
        return;
    }

    insertingPosition = false;
    disableSaveButton();

    $.ajax({
        url: $("#InsertDistanceUrl").val() + "?insertPosition=" + $(lastClickedAccordion).attr("anNo"),
        type: 'POST',
        processData: false,
        contentType: false,
        cache: false,
        enctype: 'multipart/form-data',
        data: new FormData($("#pn-form")[0]),
        success: function (data) {
            var url = window.location.href;
            url = url.split("&")[0];
            url = url + "&isNewDistance=true&toDocTab=false";
            location.href = url;
        },
        error: function (data) {
            handleRequestError();
        }
    });
}

function getNotInCurrencyData(model, rowId) {
    const notInCurrency = $(rowId + "-NotInCurrency");
    const distanceNum = rowId.replace("#", "");

    if (notInCurrency.length > 0) {
        model.NotInCurrency = $(notInCurrency).prop('checked');

        const dailyAllowsTable = $('#DailyAllowsTable-' + distanceNum);

        if (dailyAllowsTable.length > 0) {
            const lastDailyAllowRow = dailyAllowsTable.find('tr:last');

            if (lastDailyAllowRow.length > 0) {
                const currencyField = lastDailyAllowRow.find('select.daily-allow-currency');

                if (currencyField.length > 0) {
                    model.Currency = currencyField.val();
                }
            }
        }
    }
}