﻿// A utility class for performing hash, querystring, and cookie functions
var Cookies = Class.create({
        cookiename: 'FSS',
        cookiePairDelimiter: '&',
        cookieAssignment: '=',
        initialize: function() {
    },
    getCookieValue: function(key) {
        var cookie = this.getCookie(this.cookiename);
        if (cookie && cookie.length > 0) {
            var settings = this.parse(cookie, this.cookiePairDelimiter, this.cookieAssignment);
            if (settings && settings[key])
                return settings[key];
        }
        return "";
    },
    getCookie: function() {
        var cookies = document.cookie;
        var cookie = "";
        if (cookies && cookies.length > 0) {
            var start = cookies.indexOf(this.cookiename);
            if (start >= 0) {
                start += this.cookiename.length + 1;
                var end = cookies.indexOf(";", start);
                if (end > start)
                    cookie = cookies.substring(start, end);
                else
                    cookie = cookies.substring(start, cookies.length);
            }
        }
        return cookie;
    },
    parse: function(parseString, pairDelimiter, assignment) {
        var keyValuePairs = parseString.split(pairDelimiter);
        var hashesAsArray = new Array();
        keyValuePairs.each(function(pair) {
            if (pair && pair.length > 0) {
                var key = pair.split(assignment)[0];
                var value = '';
                if (pair.indexOf(assignment) > 0) {
                    value = pair.split(assignment)[1];
                }
                hashesAsArray[key] = value;
            }
        });
        return hashesAsArray;
    },
    setCookieValue: function(key, value) {
        if (!key || key.length == 0)
            return;

        //decide between temp and permanent cookie
        var theCookieName = this.cookiename;

        var cookie = this.getCookie(theCookieName);
        if (cookie && cookie.length > 0) {
            //assume path and expires is set
            if (cookie.indexOf(key) >= 0) {
                var pattern = new RegExp(key + this.cookieAssignment + "[^" + this.cookiePairDelimiter + "]*");
                cookie = cookie.replace(pattern, key + this.cookieAssignment + value);
            } else {
                cookie += this.cookiePairDelimiter + key + this.cookieAssignment + value;
            }
        } else {
            //assume new cookie
            cookie += key + this.cookieAssignment + value;
        }
        var expires = "";
        var nextYear = new Date();
        nextYear.setFullYear(nextYear.getFullYear() + 1);
        expires = ("; expires=" + nextYear.toGMTString());
        document.cookie = (theCookieName + "=" + cookie
            + "; path=/" + expires);
    }
});