/**
 * Javascript object that represents a cookie
 * Author: www.bachius.com
 *
 * Parameters:
 * @name 	 - Name of the cookie
 * @duration - Number of days to store this cookie in a browser
 **/
function CookieObject(name, duration) {
	this.data = "";

	if (duration) {
		var date = new Date();
		var curTime = new Date().getTime();
		date.setTime(curTime + (1000 * 60 * 60 * 24 * duration));
		this.data = ";expires=" + date.toGMTString();
	}

	function getCookieValue() {
		var m = document.cookie.match(new RegExp("(" + name + "=[^;]*)(;|$)"));
		return m ? m[1] : null;
	}

	this.setValue = function(key, value) {
		var cv = getCookieValue();
		value = escape(value);

		if (value) {
			var keyValue = "@" + key + "#" + value;
			
			if (cv) {
				if (new RegExp("@" + key).test(cv)) {
					document.cookie =
						cv.replace(new RegExp("@" + key + "#[^@;]*"), keyValue) + this.data;
				} else {
					document.cookie =
						cv.replace(new RegExp("(" + name + "=[^;]*)(;|$)"), "$1" + keyValue) + this.data;
				}
			} else {
				document.cookie = name + "=" + keyValue + this.data;
			}
		} else if (new RegExp("@" + key).test(cv)) {
			document.cookie = cv.replace(new RegExp("@" + key + "#[^@;]*"), "") + this.data;
		}
	}
	
	this.addValue = function(value) {
		var cv = getCookieValue();
		value = escape(value);

		if (value) {
			var keyValue = "#" + value;
			
			if (cv) {
				document.cookie = cv + keyValue + this.data;
			} else {
				document.cookie = name + "=" + keyValue + this.data;
			}
		}
	}
	
	this.removeValue = function(value) {
		var cv = getCookieValue();

		if (value && cv) {
			value = escape(value);
			document.cookie = cv.replace("#"+value, "") + this.data;
		}
	}

	this.getValue = function(URL) {
		var cv = getCookieValue();
		if (cv) {
			var m = cv.match(new RegExp("@" + URL + "#([^@;]*)"));
			if (m && m[1]) {
				return unescape(m[1]);
			}
		}
	}
	
	/*this.getKeys = function() {
		var cv = getCookieValue();
		var keys = "";
		
		if (cv) {
			var keyRegExp = new RegExp("@[^#;]*");
			while (m = cv.match(keyRegExp)) {
				keys += m;
				cv = cv.replace(m, "");
			}
			keys = keys.substr(1, keys.length);
		}
		return keys.split("@");
	}*/

}
