// Cookie functions loosely based on the Flanagan book

/** @constructor */

function Cookie(doc) {
    this.doc = doc || document;
}

Cookie.prototype.set = function(key, value, age, path) {
    // TODO Argh, IE does not support max-age; see
    //
    //   http://blogs.msdn.com/ieinternals/archive/2009/08/20/WinINET-IE-Cookie-Internals-FAQ.aspx

    if (!path) { path = "/"; }
    this.doc.cookie = key + "=" + encodeURIComponent(value) + "; max-age=" + age + "; path=" + path;
};

Cookie.prototype.setObj = function(key, value, age, path) {
    this.set(key, Object.toJSON(value), age, path);
};

Cookie.prototype.get = function(key, def) {
    
    var s = this.doc.cookie;
    var pos = s.indexOf(key + "=");

    if (pos != -1) {
        var v0 = pos + key.length + 1;
        var v1 = s.indexOf(";", v0);
        if (v1 == -1) { v1 = s.length; }
        var value = s.substring(v0, v1);
        return decodeURIComponent(value);
    }
    else {
        return def;
    }

};

Cookie.prototype.getObj = function(key, def) {
    var value = this.get(key);
    return value ? value.evalJSON() : def;
};

