/**
 * @author Nicholas Cloud; c.f. http://www.w3schools.com/js/js_cookies.asp
 */

/**
 * Sets the document cookie
 * @param {String} key
 * @param {String} value
 * @param {Int} expireDays
 * @param {String} path
 * @param {String} domain
 */
function setCookie(key, value, expireDays, path, domain) {
		
		var theCookie = key + "=" + escape(value);
		
		if(expireDays != null) {
			var date = new Date();
			date.setDate(date.getDate() + expireDays);	
			theCookie += ";expires=" + date.toGMTString();
		}
		
		if(path != null && path.length > 0) {
			theCookie += ";path=" + path;
		}
		
		if(domain != null && domain.length > 0) {
			theCookie += ";domain=" + domain;
		}
		
		theCookie += ";";
		
		document.cookie = theCookie;
}

/**
 * Gets the current document cookie value for a given key
 * @param {String} key
 * @return {String}
 */
function getCookieValue(key) {
	var theCookieValue = "";
	
	if(document.cookie.length > 0) {
		var cookieCollection = document.cookie.split(";");
		
		for(var i = 0; i < cookieCollection.length; i++) {
			var cookie = cookieCollection[i].split("=");
			if(cookie[0].replace(" ", "") == key.replace(" ", "")) {
				theCookieValue = cookie[1];
				break;
			}
		}
	}
	
	return theCookieValue;
}

/**
 * Returns the key/value pair for the given key
 * @param {String} key
 */
function getCookie(key) {
	var theCookie = "";
	
	if(document.cookie.length > 0) {
		var cookieCollection = document.cookie.split(";");
		var cookie = null;
		
		for(var i = 0; i < cookieCollection.length; i++) {
			cookie = cookieCollection[i].split("=");
			if(cookie[0] == key) {
				theCookie = cookieCollection[i];
				break;
			}
		}
	}
	
	return theCookie;
}

/**
 * Expires a particular cookie by key
 * @param {String} key
 */
function expireCookie(key) {
	var date = new Date();
	date.setTime(date.getTime() - 1);
	document.cookie = key += ";expires=" + date.toGMTString();
}

/**
 * Expires all cookies in the cache
 */
function expireAllCookies() {
	if(document.cookie.length > 0) {
		var cookieCollection = document.cookie.split(";");
		var cookie = null;
		
		for(var i = 0; i < cookieCollection.length; i++) {
			cookie = cookieCollection[i].split("=");
			expireCookie(cookie[0]);
		}
	}
}
