// Id: CookieJar.js,v 1.3 2009/01/30 02:20:50 cmanley Exp
// Copyright (c) 2008, Craig Manley (craigmanley.com)


// Cookie methods. Watch out for IE6 bug: http://support.microsoft.com/kb/820536
var CookieJar = new (function() {

	var _objGetClass = function(o) {
		if (!(o && (typeof(o) == 'object') && o.constructor)) {
			return undefined;
		}
		var result = undefined;
		var ctr = o.constructor.toString();
		//alert(ctr);
		var matches = ctr.match(/^\s*function\s+(\w+)\(\)/); // /^\[class (\S+)\]$/
		if (matches && (matches.length == 2)) {
			result = matches[1];
		}
		/*
		function String() {
			[native code]
		}
		*/
		return result;
	}

	this.getCookies = function() {
		var nvs = document.cookie ? document.cookie.split(/\s*;\s*/) : [];
		var cookies = {};
		for (var i=0; i < nvs.length; i++) {
			var j = nvs[i].indexOf('=');
			if (j > 0) {
				var n = nvs[i].substr(0,j);
				var v = j+1 < nvs[i].length ? nvs[i].substr(j+1) : '';
				cookies[n] = unescape(v);
			}
		}
		return cookies;
	}

	this.contains = function(name) {
		var cookies = this.getCookies();
		return (name in cookies);
	}

	this.read = function(name) {
		var cookies = this.getCookies();
		if (name in cookies) {
			return cookies[name];
		}
		return null;
	}

	this.remove = function(name) {
		document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';
	}

	this.store = function(name, value, expires, path) {
		var cookie = name + "=" + escape(value);
		if (expires != null) {
			var t = typeof(expires);
			var c = _objGetClass(expires);
			if (((t == 'string') || (c == 'String')) && expires.length) {
				cookie += "; expires=" + expires;
			}
			else if (c == 'Date') {
				cookie += "; expires=" + expires.toGMTString();
			}
			else if ((t == 'number') || (c == 'Number')) { // assume days
				var date = new Date();
				date.setTime(date.getTime()+(parseInt(expires,10)*24*60*60*1000));
				cookie += "; expires=" + date.toGMTString();
			}
		}
		if (path) {
			cookie += '; path=' + path;
		}
		document.cookie = cookie;
	}

})();

