﻿/****************************************************************************
Cookie Utility
****************************************************************************/
function Cookie(name) {
    //store the name
    this.$name = name;
    //check for cookies
    var allcookies = document.cookie;
    if (allcookies == "") return;

    var cookie = null;
    var cookies = allcookies.split(';');
    //find the cookie    
    for (var i = 0; i < cookies.length; i++) {
        var s = new String(cookies[i]).replace(/\s/, "");
        if (s.substring(0, name.length + 1) == (name + "=")) {
            cookie = s;
            break;
        }
    }
    if (cookie == null) return;

    var cookieval = cookie.substring(name.length + 1);
    var a = cookieval.split('&');
    for (var i = 0; i < a.length; i++) {
        a[i] = a[i].split(':');
    }
    //create and populate properties
    for (var i = 0; i < a.length; i++) {
        this[a[i][0]] = decodeURIComponent(a[i][1]);
    }
}
//Saves the Cookie
Cookie.prototype.store = function(daysToLive, path, domain, secure) {
    var cookieval = "";
    for (var prop in this) {
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
            continue;

        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + encodeURIComponent(this[prop]);
    }

    var cookie = this.$name + '=' + cookieval;
    if (daysToLive || daysToLive == 0) {
        cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
    }

    if (path) cookie += "; path=" + path;
    if (domain) cookie += "; domain=" + domain;
    if (secure) cookie += "; secure";

    //store the cookie
    document.cookie = cookie;
}
//Removes the Cookie
Cookie.prototype.remove = function(path, domain, secure) {
    //delete cookie properties
    for (var prop in this) {
        if (prop.charAt(0) != '$' && typeof this[prop] != 'function')
            delete this[prop];
    }
    //store the cookie with a lifetime of 0
    this.store(0, path, domain, secure);
}
//Checks to see if cookies are enabled for the current browser
Cookie.enabled = function() {
    //use navigator.cookieEnabled if this browser defines it
    if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;
    //if we've already cached a value, use that value
    if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;
    //otherwise, create a test cookie with a lifetime
    document.cookie = "testcookie=test; max-age=10000";
    //now see if that cookie was saved
    var cookies = document.cookie;
    if (cookies.indexOf("testcookie=test") == -1) {
        //cookie was not saved
        return Cookie.enabled.cache = false;
    }
    else {
        //cookie was saved, delete it before returning
        document.cookie = "testcookie=test; max-age=0";
        return Cookie.enabled.cache = true;
    }
}