// Cookie Class
// Adapted from Recipe 1.9 of O'Reilly's JavaScript & DHTML Cookbook
// (c) 2005 Jason Frame
//
// TODO: can we reload expiry date etc. on open?
//
// Usage:
// foo = new Cooke("bar");
// foo.value = "raaa";
// foo.setExpires(14,0,0);
// foo.save();

function Cookie(name)
{
	this.name = name;
	
	if (!this.open()) {
		this.value = null;
		this.expires = null;
		this.path = null;
		this.domain = null;
		this.secure = false;
		this.saved = false;
	} else {
		this.saved = true;
	}
}

Cookie.prototype.open = function()
{
	var arg = this.name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i,j) == arg) {
			var end = document.cookie.indexOf(";",j);
			if (end == -1) {
				end = document.cookie.length;
			}
			this.value = unescape(document.cookie.substring(j,end));
			return true;
		}
		i = document.cookie.indexOf(" ",i) + 1;
		if (i == 0) break;
	}
	
	return false;
}

Cookie.prototype.save = function()
{
	document.cookie = this.name + "=" + escape(this.value) +
		((this.expires) ? ("; expires=" + this.expires) : "") +
		((this.path) ? ("; path=" + this.path) : "") +
		((this.domain) ? ("; domain=" + this.domain) : "") +
		((this.secure) ? "; secure" : "");
	this.saved = true;
}

Cookie.prototype.remove = function()
{
	if (this.saved) {
		document.cookie = this.name + "=" +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT" +
			((this.path) ? "; path=" + this.path : "") +
			((this.domain) ? "; domain=" + this.domain : "");
		this.saved = false;
	}
}

Cookie.prototype.setExpires = function(d,h,m)
{
	var da = new Date();
	da.setDate(da.getDate() + parseInt(d));
	da.setHours(da.getHours() + parseInt(h));
	da.setMinutes(da.getMinutes() + parseInt(m));
	this.expires = da.toGMTString();
}
