$(document).ready(function () {
    let localStorageFilters = localStorage.getItem("localStorageFilters");

    if (localStorageFilters) {
        let storageFilterObject = JSON.parse(localStorageFilters);
        if ($("#localStorageFiltersFor").val() && storageFilterObject.page === $("#localStorageFiltersFor").val() && storageFilterObject.filters) {
            storageFilterObject.filters.forEach(filter => {
                if ($("#" + filter.name).hasClass("localStorageFilter")) {
                    if ($("#" + filter.name).hasClass("selectpicker"))
                        $("#" + filter.name).selectpicker('val', filter.value.split(","));
                    else
                        $("#" + filter.name).val(filter.value);
                }
            });
        } else if ($("#localStorageFiltersFor").val()) {
            localStorage.removeItem("localStorageFilters");
        }
    }

    $(".localStorageFilter").on("change", function () {
        var filters = $(".localStorageFilter");

        if (filters) {
            var filterValues = [];
            Array.from(filters).forEach(filter => {
                if (filter.value)
                    filterValues.push({ name: filter.id, value: $(filter).hasClass("selectpicker") ? $(filter).val().join(",") : filter.value });
            });

            if (filterValues && filterValues.length > 0) {
                localStorage.setItem("localStorageFilters", JSON.stringify({ page: $("#localStorageFiltersFor").val(), filters: filterValues }));
            }
        }
    });
});