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

var selectedKeys = [];

//#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"));

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

    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: "", render: $.fn.dataTable.render.preview("AcKey"), className: 'dt-body-center dt-head-center' },
        { 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: "AcWorker", name: "AcWorker", filtertype: "text" },
        { data: "AnValue", name: "AnValue", filtertype: "text", render: $.fn.dataTable.render.number('.', ',', $("#DefaultDecimalPlacesPrice").val(), '') },
        { data: "AcVehicle", name: "AcVehicle", filtertype: "text" },
        { data: "AcDept", name: "AcDept", filtertype: "text" },
        { data: "AcPayer", name: "AcPayer", filtertype: "text" },
        { data: "AcStatus", name: "AcStatus", filtertype: "text" }
    ];

    initializeDataTables('travelorders', 'Keywords', columns, acKey, 2, null, null, date);
}

//#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);
    }

    if (selectedKeys.length > 0) {
        $(".printDropdown, .dropdown-toggle").prop('disabled', false);
    }
    else {
        $(".printDropdown, .dropdown-toggle").prop('disabled', true);
    }

    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();
}
//#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,
            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'
                    }
                ]
            });
        }
    });
}

//#endregion MULTI DELETE

//#endregion DELETE TRAVEL ORDER

//#region COPY

function copyTravelOrder() {
    let url = $("#Copy").val();
    performAction(url);
}

//#endregion COPY

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

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) {
    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,
        dataType: 'json',
        data: { subjectId: subjectId },
        success: function (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 () { saveAndDisableSaveButton(); }, interval);
                            }
                            else {
                                searchDistanceFromGoogle(getDistanceStartPoint(), subjectText, fieldId, false);
                                setTimeout(function () { saveAndDisableSaveButton(); }, 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 () { saveAndDisableSaveButton(); }, interval);
                            }
                            else {
                                searchDistanceFromGoogle(getDistanceStartPoint(), subjectText, fieldId, true);
                                setTimeout(function () { saveAndDisableSaveButton(); }, 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 () {

        $().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);
                        setTimeout(function () { saveAndDisableSaveButton(); }, interval);
                    },
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: returnWay,
                    action: async function () {
                        searchDistanceFromGoogle(getDistanceStartPoint(), input.value, 'Km', true);
                        setTimeout(function () { saveAndDisableSaveButton(); }, 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 = Math.round(parseFloat(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 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, parameterName) {
    let sourceElement = getDropDownSelection(sourceElementId);
    let url = getElementAttributeValue(targetElementId, 'data-change-url');
    let currentLegislation = $("#CurrentLegislation").val();

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

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', '');
        }
    }
}
//#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) {
                    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));
                    }

                    if (tableId && rowNum && type) {
                        updateTravelOrderInput(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 () {
        if (allowSubmit) {
            setTimeout(function () { $('.dropify-loader').css('display', 'block'); }, 600);
            $('#pn-form').submit();
        }
        else {
            $("#createDocumentIrisMessage").text(stringFormat(incorrectDocType, docType));
            $("#openDocTypeSettings").attr("onclick", "window.open('" + $("#OpenDocumentUrl").val() + "', '_blank')");
            $("#help-url").attr("onclick", "window.open('" + $("#DocTypeHelpUlr").val() + "', '_blank')");
            $("#createDocumentErrorModal").modal("show");
            $('#createDocumentErrorModal').on('hidden.bs.modal', function () {
                $('.dropify-clear').click();
            })
        }
    });
}
//#endregion UPLOAD FILES

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

function saveNote() {
    var noteValue = $("#item-note").val();
    $("#return-note-" + selectedNoteNo).val(noteValue);

    if (noteValue.length > 0) {
        $("#note-button-" + selectedNoteNo).addClass("text-primary");
    } else {
        $("#note-button-" + selectedNoteNo).removeClass("text-primary");
    }
}

function setPurposeDescription(ordinalNumber) {
    var note = $("#travel-note-" + ordinalNumber).text();
    $("#travel-note-" + ordinalNumber).find('option').remove();
    $("#" + ordinalNumber + "-Purpose").empty();
    $("#" + ordinalNumber + "-Purpose").val(note);
    $("#" + ordinalNumber + "-Purpose").focus();
}
//#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"
            });
        });
    }
}

//#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 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, rowNum, type) {
    var defaultFxRate = $("#defaultFxRate").val();
    var dateValue = $("#" + num + "-DateHourFrom").val();

    if (dateValue) {
        var date = toStandardDateFormatString(dateValue);
        $.getJSON("/TravelOrders/GetFxRate",
            {
                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 && rowNum && type) {
                    updateTravelOrderInput(tableId, rowNum, 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()));

    var previousCar = $('#HeaderCarRegNo').data('pre');
    $.getJSON(url,
        {
            regNo: regNo
        },
        function (data) {
            if (data) {
                $('#HeaderCarRegNo').data('pre', data.IsCompanyCar);

                if (data.IsCompanyCar === previousCar) {
                    return;
                }

                if (data.IsCompanyCar) {
                    $('.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");
                    });

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

$(document).ready(function () {
    openIrisModal();

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

$(window).load(function (e) {
    getGoogleSearch();
});

//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="expandTableRow(\'' + 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) {
    var notForPay = $("#" + notForPayId);

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

            $("#" + expId).next().find(".select2-selection--single").focus();

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

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) {
        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 (!enterDestinationWithoutGoogleApiKey && (apiKey == "" || apiKey == null)) {
        $('#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) {
    swapLoadingIcon(true, "saveButton", "fa fa-save");
    swapLoadingIcon(true, "printButton", "far fa-print");
    togglePrintButton();

    $("#isPrint").val(true);

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

    $.ajax({
        url: $("#SaveTravelOrderUrl").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);
            }

            swapLoadingIcon(false, "saveButton", "fa fa-save");
            swapLoadingIcon(false, "printButton", "far fa-print");
            togglePrintButton();
        },
        error: function (data) {
            swapLoadingIcon(false, "saveButton", "fa fa-save");
            swapLoadingIcon(false, "printButton", "far fa-print");
            togglePrintButton();
        }
    });
}

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


function togglePrintButton() {
    $("#printButton").toggleClass("print-btn-disable");
}


function saveAndDisableSaveButton() {
    $("#isPrint").val(false);
    swapLoadingIcon(true, "saveButton", "fa fa-save");
    $("#pn-form").submit();
}

function updateTravelOrderInput(tableId, rowNum, type) {
    let elements = $("#" + tableId + " .collapse-table-row-" + rowNum + " td").find("select, input");
    let model = {};
    let url;

    if (type === dailyAllows) {
         url = $("#DailyAllowUpdateUrl").val();
    } else if (type === expenses) {
         url = $("#ExpenseUpdateUrl").val();
    } else if (type === distances) {
         url = $("#DistanceUpdateUrl").val();
         elements = $("#" + tableId + " tr td").find("select, input");
    }

    elements.each(function () {
        let 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;
    });

    swapLoadingIcon(true, "saveButton", "fa fa-save");

    $.ajax({
        url: url,
        type: 'POST',
        data: model,
        success: function (data) {
            swapLoadingIcon(false, "saveButton", "fa fa-save"); 
        },
        error: function (error) {
            swapLoadingIcon(false, "saveButton", "fa fa-save"); 
            $(".select2-container--focus").removeClass("select2-container--focus");
            $().customModal({
                destroyOnClose: true,
                showCloseButton: true,
                type: "alert",
                text: $("#RequestError").val(),
            });
        }
    });
}
function getGoogleSearch() {
    let isGoogleSearch = localStorage.getItem("isGoogleSearch");

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

        toggleNodeSelection();

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

function setGoogleSearch() {
    let googleSearch = localStorage.getItem("isGoogleSearch");
    
    if (googleSearch !== null) {
        let isGoogleSearch = (googleSearch === "true");
        toggleGoogleSearch(!isGoogleSearch);
    }
    else {
        toggleGoogleSearch(true);
    }
}

function toggleGoogleSearch(isGoogleSearch) {
    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 AddNewRow(rowId, prefixId, tableId) {
    var newRow = AddRow(rowId, prefixId, tableId);
    if (newRow !== null) {
        saveAndDisableSaveButton();
    }
}

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