$(document).ready(function () {
    $('.thousands-no-decimals')
        .on('change', function () {
            let number = Number(toStandardDecimalString(getFieldValue(this.id)));
            setFieldValue(this.id, formatWithThousandsNoDecimals(number));
        });

    $('.thousands-with-decimals')
        .on('change', function () {
            let number = Number(toStandardDecimalString(getFieldValue(this.id)));
            setFieldValue(this.id, formatWithThousands(number));
        });

    $(".int-thousands-with-dot").each(function () {
        var value = formatWithThousandsNoDecimals(parseInt($(this).val()));
        setFieldValue($(this).attr("id"), value);
    });
});

function getFieldValue(id) {
    let fieldValue = $("#" + id).val();

    if (!fieldValue) {
        return null;
    }
    else {
        return fieldValue;
    }
}

function setFieldValue(fieldId, fieldValue) {
    $("#" + fieldId).val(fieldValue);
}

function setDropdownValue(key, value, dropDownId) {
    let newOption = new Option(value, key, true, true);
    $("#" + dropDownId).empty();
    $("#" + dropDownId).append(newOption).trigger('change');
}

function getDropDownSelection(fieldId) {
    let field = $("#" + fieldId);

    if (field.hasClass('select2-hidden-accessible')) {
        var selectedValue = field.select2('data');
        if (selectedValue.length > 0) {
            return selectedValue[0];
        }
    }
}

function getElementAttributeValue(fieldId, attribute) {
    let field = $("#" + fieldId);
    return field.attr(attribute);
}

function sumFields(fieldIds, targetField) {
    let sum = 0;
    
    for (i = 0; i < fieldIds.length; i++) {
        
        let fieldValue = Number($("#" + fieldIds[i]).val().toString().replace(/\./g, '').replace(',', '.'));
        sum += fieldValue;
    }

    if (!isNaN(sum)) {
        setFieldValue(targetField, formatWithThousandsNoDecimals(sum));
    }
}

function multiplyFields(fieldIds, targetField) {
    let sum = 0;

    for (i = 0; i < fieldIds.length; i++) {
        let fieldValue = Number($("#" + fieldIds[i]).val());
        sum *= fieldValue;
    }

    if (!isNaN(sum)) {
        setFieldValue(targetField, sum);
    }
}


function toStandardDecimalString(number) {
    if (number) {
        return number.replace(".", "").replace(",", ".");
    } 
}

function toDecimalWithComma(number) {
    if (number) {
        return number.replace(".", ",");
    }
}

function toStandardDateFormatString(date) {
    return moment(date, "DD.MM.YYYY").format("MM.DD.YYYY");
}

function formatWithThousands(num) {
    return (
        num
            .toFixed(2)
            .replace('.', ',')
            .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
    );
}

function formatWithDecPlaces(num, places) {
    return (
        num
            .toFixed(places)
            .replace('.', ',')
    );
}

function formatWithThousandsNoDecimals(num) {
    return (
        num
            .toFixed(0)
            .replace('.', ',')
            .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
    );
}

function formatFieldWithThousands(fieldId) {
    let fieldValue = getFieldValue(fieldId);
    

    if (fieldValue) {
        let fieldValueAsNumber = Number(fieldValue);
        if (!isNaN(fieldValueAsNumber)) {
            setFieldValue(fieldId, formatWithThousands(fieldValueAsNumber));
        }
    }
}

function toThousandsNoDecimalsFormat(id) {
    let value = getFieldValue(id);

    if (value) {
        value = removeDots(value);
        let formatedValue = formatWithThousandsNoDecimals(parseInt(value));
        setFieldValue(id, formatedValue);
    }
}

function toThousandsDecimalsFormat(id) {
    let value = getFieldValue(id);

    if (value) {
        value = removeDots(value);
        let formatedValue = formatStringWithThousands(value);
        setFieldValue(id, formatedValue);
    }
}

function formatStringWithThousands(num) {
    return (
        num.replace('.', ',')
            .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
    );
}

function removeDots(value) {
    return value.replaceAll('.', '')
}


function setCheckedValue(checkBoxId, turnOffId1, turnOffId2, dailyAllowNoId) {
    let currentLoc = $("#currentLoc").val();
    let locBA = $("#locBA").val();
    let locMK = $("#locMK").val();
    let turnOn = $("#" + checkBoxId);
    let turnOff1 = $("#" + turnOffId1);
    let turnOff2 = $("#" + turnOffId2);
    let checked = $("#" + checkBoxId).attr("checked");
    let isSLInternationalC = $("#isSLInternationalC").val();
    let isSLInternational = $("#isSLInternational").val();
    let dailyAllowNo = $("#" + dailyAllowNoId).val();
    let dailyAllowNo025 = $("#dailyAllowNo025").val();

    if (currentLoc === locBA ||
        currentLoc === locMK ||
        (dailyAllowNo === dailyAllowNo025 && (isSLInternationalC || isSLInternational))) {
        if (checked) {
            turnOn.removeAttr("checked");
            turnOn.removeAttr("value");
        } else {
            turnOn.attr("checked", true);
            turnOn.attr("value", "true");
            turnOff1.attr("checked", false);
            turnOff1.attr("value", "false");
            turnOff2.attr("checked", false);
            turnOff2.attr("value", "false");
        }
    } else {
        if (!checked) {
            setFieldAttribute(checkBoxId, 'checked', 'checked');
            setFieldAttribute(checkBoxId, 'value', 'true');
        }
        else {
            removeFieldAttribute(checkBoxId, 'checked');
            setFieldAttribute(checkBoxId, 'value', 'false');
        }
    }
}

function setFieldAttribute(fieldId, attribute, attributeValue) {
    $("#" + fieldId).attr(attribute, attributeValue);
}

function removeFieldAttribute(fieldId, attribute) {
    $("#" + fieldId).removeAttr(attribute);
}

function swapLoadingIcon(loading, buttonId, icon) {
    var $button = $("#" + buttonId);
    var $buttonIcon = $button.find("i");
    var $buttonGroupButtons = $button.parent().find("button");

    if (loading) {
        $buttonIcon.removeClass(icon).addClass("fa fa-spinner fa-spin fa-fw");
        $buttonGroupButtons.attr("disabled", true);
    }
    else {
        $buttonIcon.removeClass("fa fa-spinner fa-spin fa-fw").addClass(icon);
        $buttonGroupButtons.removeAttr("disabled");
    }
}

function prevNeighbour(acKey) {
    let url = window.location.href;
    let splitted = url.split('acKey=');
    let prevUrl = splitted[0];

    $(".prev-next-key-display .fa-chevron-left").removeClass("fa-chevron-left").addClass("fa-spinner").addClass("fa-spin");
    window.location.href = prevUrl + "acKey=" + acKey;
}

function nextNeighbour(acKey) {
    let url = window.location.href;
    let splitted = url.split('acKey=');
    let nextUrl = splitted[0];

    $(".prev-next-key-display .fa-chevron-right").removeClass("fa-chevron-left").addClass("fa-spinner").addClass("fa-spin");
    window.location.href = nextUrl + "acKey=" + acKey;
}

function disableChangeAcKey() {
    let prevAcKey = $("#PrevAcKey").val();
    let nextAcKey = $("#NextAcKey").val();

    if (!prevAcKey) $(".prev-next-key-display .fa-chevron-left").css("pointer-events", "none").addClass("disabled");
    if (!nextAcKey) $(".prev-next-key-display .fa-chevron-right").css("pointer-events", "none").addClass("disabled");
}

function goToList(acKey, date) {
    let url = $("#ItemList").val();

    if (!acKey || !date) {
        window.location.href = url;
        return;
    }

    let querySeparator = "&";

    if (!url.includes("?")) {
        querySeparator = "?";
    }

    window.location.href = url + querySeparator + "acKey=" + acKey + "&date=" + date;
}

function isMobile() {
    let mobileWidth = 576;

    if (window.innerWidth < mobileWidth)
        return true;

    return false;
}

function isTablet() {
    let tabletWidth = 768;
    let mobileWidth = 576;

    if (window.innerWidth <= tabletWidth && window.innerWidth >= mobileWidth)
        return true;

    return false;
}

function getTime(date) {
    if (date) {
        let time = new Date(parseInt(date.substr(6)));
        time = moment(time).format("HH:mm");
        return time;
    }
}

function convertMinutesToTime(duration) {
    let d = new Date();
    d.setHours(0, 0, 0, 0);
    d.setMinutes(d.getMinutes() + parseInt(duration));
    let time = moment(d.getTime()).format("HH:mm");
    return time;
}

function convertTimeToMinutes(time) {
    if (time) {
        let hours = time.split(":")[0] * 60;
        let minutes = time.split(":")[1];
        let total = parseInt(hours) + parseInt(minutes);
        return total;
    }
}

function calculateDuration(startDate, endDate) {
    const difference = Math.abs(endDate - startDate);
    const days = Math.floor(difference / (1000 * 60 * 60 * 24));
    const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) % 24;
    const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)) % 60;

    return {
        days: days,
        hours: hours,
        minutes: minutes
    };
}

function setCheckboxValue(checkbox) {
    if ($(checkbox).is(':checked')) {
        $(checkbox).val(true);
    } else {
        $(checkbox).val(false);
    }
}