/**
 * jQuery Cookie Handler by HenningK.de
 */

jQuery.extend( {
	Cookie : function(key) {
		var C = document.cookie;

		return {

			/**
			 * Returns the value of cookie or "" if not set
			 */
			read : function() {
				var keynval = C.match(new RegExp(key + "=([^;]+)"));
				return keynval ? unescape(keynval[0].substr(String(key + "=").length)) : "";
			},

			/**
			 * Returns true/false if cookie (not) exists
			 */
			check : function() {
				return new Boolean(C.match(new RegExp(key + "=([^;]+)")));
			},

			/**
			 * Writes value to cookie - exp in ms from now (if not set extend for 1 day) - OVERWRITES existing keys/values!
			 */
			write : function(value, exp) {

				if (typeof exp === "number")
					ext = exp;
				else
					ext = 86400000; // 86400000ms = 1day

				var now = new Date();
				var exp = new Date(now.setMilliseconds(now.getMilliseconds() + ext));

				document.cookie = key + "=" + escape(value) + ";expires=" + exp.toUTCString();
			},

			/**
			 * Extends cookie-lifetime in ms
			 */
			extend : function(ms) {
				if(typeof ms !== "number") return;
				var exp = new Date(new Date().getMilliseconds() + ms);
				var val = this.read(key);
				if (val !== "") {
					document.cookie = key + "=" + escape(val) + ";expires=" + exp.toUTCString();
				}
			},

			/**
			 * Deletes cookie by setting "expires" to first UTC Date
			 */
			remove : function() {
				document.cookie = key + "=null;expires=" + new Date(0).toUTCString();
			}
		}
	}
});
