(function () {
    var onAnalyticsOk = []; 

    var analyticsOk = function () {
        for (var i = 0; i < onAnalyticsOk.length; i++){
            onAnalyticsOk[i]();
        }
    }
    var preferences = {

        setAnalyticsOkCallback: function (callback) {
            var pref = this.getPreference();
            if (!pref || !pref.analytics) {
                onAnalyticsOk.push(callback);
            } else {
                callback();
            }
        },
        updatePreference: function (analytics, callback) {
            const preferences = {
                analytics: analytics,
            };
            const data = JSON.stringify(preferences)
            // Save preferences to storage
            localStorage.setItem('cookiePreferences', data);

            fetch("/user/SetCookiePreference", {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: data
            }).then(res => {
                //console.log("Request complete! response:", res);
                callback(res);
                if (preferences.analytics) analyticsOk();
            });
        },

        getPreference: function () {
            var json = localStorage.getItem("cookiePreferences")
            if (json) return JSON.parse(json);
            return null;
        }
        
    }
    window.cookiePreferences = window.cookiePreferences || preferences;
}
)()