
// Gets a cookie by name.
// Returns null if the cookie isn't set.
function get_cookie(cookieName)
{
	if (document.cookie.length == 0) return null;

	var cName = cookieName + '=';

	var begin = document.cookie.indexOf(' ' + cName);
	if (begin != -1) ++begin; // to get past the space
	else
	{
		// check the very first cookie
		begin = document.cookie.indexOf(cName);
		if (begin != 0) return null;
	}

	begin += cName.length;
	var end = document.cookie.indexOf(';', begin);
	if (end == -1) end = document.cookie.length;

	var encoded = document.cookie.substring(begin, end);

	// PHP uses "+" instead of "%20" to encode spaces in the cookie value,
	// which confuses both IE and mozilla (the plusses don't get decoded).
	// If we replace "+" with "%20" before decoding, everything works properly.
	encoded = encoded.replace(/\+/g, '%20');

	return unescape(encoded);
}

// Sets a cookie by name.
// You can optionally make the cookie permanent; otherwise it will be session-only.
// Setting the cookie's value to null, false or the empty string will delete it.
function set_cookie(cookieName, cookieValue, permanent)
{
	if (set_cookie.arguments.length < 2) return false;

	if (cookieValue === null || cookieValue === false || cookieValue === '')
		return delete_cookie(cookieName);

	var newCookie = cookieName + '=' + escape(cookieValue) + '; path=/';
	if (permanent) newCookie += '; expires=' + new Date('01/01/2037').toUTCString();

	document.cookie = newCookie;
	return true;
}

// Removes a cookie by name.
// This works by setting the expiration date to the beginning of time.
function delete_cookie(cookieName)
{
	document.cookie = cookieName + '=; expires=Thu, 01-Jan-70 00:00:01 GMT' + '; path=/';
	return true;
}
