/* 
Contains Useful javascript cookie functions.
*/

// Handler to check for missing cookies
(function(aListener) {
	if(window.addEventListener)
		window.addEventListener('load', aListener, false);
	else if(window.attachEvent)
		window.attachEvent('onload', aListener);
}(new Function('alertMissingCookies("You will need to enable cookies in order to use this application.")')));

/* 
Returns a cookie by name.
*/
function getCookie(name)
{
	var a_all_cookies = document.cookie.split(';');
	var a_temp_cookie = '';

	for (var i = 0; i < a_all_cookies.length; i++)
	{
		a_temp_cookie = a_all_cookies[i].split('=');
		if (a_temp_cookie.length == 2 && name == a_temp_cookie[0].replace(/^\s+|\s+$/g, ''))
			return unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
	}
	return null;
}

/* 
Creates/sets the specified cookie.
*/
function setCookie(name, value, expireDays, path, domain, secure)
{
	var expires = new Date();
	if (expireDays)
		expires.setTime(expires.getTime() + expireDays * 24 * 60 * 60 * 1000);
	document.cookie = name + '=' + escape(value) +
		((expireDays) ? ';expires=' + expires.toGMTString() : '') +
		((path) ? ';path=' + path : '') +
		((domain) ? ';domain=' + domain : '') +
		((secure) ? ';secure' : '');
}

/* 
Deletes the specified cookie.
	
It does this by expiring it in the past.
*/
function deleteCookie(name, path, domain)
{
	if (getCookie(name))
		document.cookie = name + '=' +
			((path) ? ';path=' + path : '') +
			((domain) ? ';domain=' + domain : '') +
			';expires=Thu, 01-Jan-1970 00:00:00 GMT';
}

/* 
Displays an alert to the user when cookies cannot be used.
	
It determines this by attempting to create/retrieve a cookie called 'test'.
*/
function alertMissingCookies(warning)
{
	var name = 'test';
	if (!getCookie(name))
	{
		setCookie(name, 'test value');
		if (getCookie(name))
			deleteCookie(name);
		else
			alert(warning);
	}
}