/**
 * fusionLib JavaScript cookie library.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * Copyright (c) 2012 - 2014 fusionLib. All rights reserved.
 */

(function() {

	fusionLib.fn.extend({

		/**
		 * Set a cookie.
		 *
		 * @param string name The name of the cookie.
		 * @param string value The value to set in the cookie.
		 * @param Date|int expire Date cookie expires or time in seconds cookie to live.
		 * @param path string The path the cookie is limited to.
		 * @param domain string The domain the cookie is limited to.
		 * @param bool secure true if secure cookie; else false.
		 */
		setCookie: function(name, value, expire, path, domain, secure) {
			var cookie = name + '=' + escape(value);

			if(expire !== undefined) {
				if(typeof expire !== 'object' || !(expire instanceof Date)) {
					expireDate = new Date();
					expireDate.setTime(expireDate.getTime() + expire);
					expire = expireDate;
				}

				cookie += '; expires=' + expire.toGMTString();
			}

			if(path) cookie += '; path=' + encodeURI(path);
			if(domain) cookie += '; domain=' + encodeURI(domain);
			if(secure) cookie += '; secure';

			document.cookie = cookie;
			return this;
		},

		/**
		 * Get the value of a cookie.
		 *
		 * @param string name The name of the cookie to get the value of.
		 * @return string The value from the cookie or null.
		 */
		getCookie: function(name) {
			var results = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
			return results ? decodeURI(results[2]) : null;
		},

		/**
		 * Delete a cookie.
		 *
		 * @param string name The name of the cookie.
		 * @param path string The path the cookie is limited to must match value when set.
		 * @param domain string The domain the cookie is limited to must match value when set.
		 */
		delCookie: function(name, path, domain) {
			fusionLib.setCookie(name, '', -3600, path, domain);
			return this;
		},

		/**
		 *  Test if the browser accepts cookies.
		 *
		 *  @return bool true if the browser accepts cookies; else false.
		 */
		testCookies: function() {
			fusionLib.setCookie('fusionLib_cookieTest', 'data');
			if(fusionLib.getCookie('fusionLib_cookieTest') === 'data') {
				fusionLib.delCookie('fusionLib_cookieTest');
				return true;
			}
			else
				return false;
		}
	});

	fusionLib.setCookie = fusionLib.fn.setCookie;
	fusionLib.getCookie = fusionLib.fn.getCookie;
	fusionLib.delCookie = fusionLib.fn.delCookie;
	fusionLib.testCookies = fusionLib.fn.testCookies;
})();