dojo.provide("UI.Util.Cookie");
dojo.require("dojo.cookie");

(function() {
	dojo.setObject("UI.Util.Cookie", {
		/**
		 * @param string name The name of the cookie to set.
		 * @param mixed value The value to set the cookie as (will be JSON encoded).
		 * @param mixed expiry A date object, or the number of minutes. If null, a session cookie will be set.
		 */
		set: function(name, value, expiry) {
			dojo.cookie(name, dojo.toJson(value), dojo.mixin(
				this.getDefaultParams(),
				// Only set the expiry if provided. This is how to do session cookies
				expiry ? {expires: expiry} : {}
			));
		},

		/**
		 * @param string name The name of the cookie to get.
		 * @return mixed The decoded JSON value of the cookie (or a string if not in JSON).
		 */
		get: function(name) {
			var cookie = dojo.cookie(name);

			try {
				return dojo.fromJson(cookie);
			} catch (e) {
				return cookie;
			}
		},

		/**
		 * @param string name The name of the cookie to delete.
		 */
		erase: function(name) {
			this.set(name, null, -1);
		},

		/**
		 * Test whether or not cookies are enabled.
		 */
		test: function() {
		    var name = "x-ppp-cookie-test";

		    this.set(name, 1);

		    if ( this.get(name) == 1 )  {
		    	this.erase(name);
		        return true;
		    }

		    return false;
		},

		/**
		 * Default cookie parameters
		 */
		getDefaultParams: function() {
			var domain = window.location.host;
			var subdomainMatch  = domain.match(/[^\.]+\.([^\.]+\.[^\.]+)$/i);

			if ( subdomainMatch ) {
				domain = subdomainMatch[1];
			}

			// Do not use a static object, it will cause you to only be able to set one cookie because it is used in a mixin below
			return {
				// Set all cookies to the root so that php can delete any cookie that js creates
				path: "/",
				// Use same domain as default php domain
				domain: "." + domain
			}
		}
	});
}());
