// 	cookies.js
//	Library for cookie access
// 	2006-12-21 usp - Release

function cookieExists( cookieName, cookieString )
{
	if ( ! cookieString ) cookieString = document.cookie;
	return cookieString.indexOf( cookieName >= 0 );
}

// Sets a cookie in the current document
// All arguments except cookieName are optional.
// LifeTime can be specified in (s)econds, (m)inutes, (h)ours, (d)ays, (M)onths or (y)ears.
// The type can be number of string, but must be parseable as integer. If the unit is omitted, 
// days are assumed. Setting a lifetime of 0 will delete the cookie.
// If lifetime is omitted or a zero-length string, no expiration date is added to the cookie. In this 
// case, the cookie's lifetime will end with window closure.
// 
function setCookie( cookieName, cookieValue, lifeTime, pathName, domainName )
{
	// check cookie name
	if ( ! cookieName ) return;
	// collect information
	var s = cookieName;
	// value
	if ( cookieValue && cookieValue.length > 0 ) s = s + "=" + escape( cookieValue );
	// lifetime
	lifeTime = "" + lifeTime;
	if ( lifeTime.length > 0 )
	{
		var matches = lifeTime.match( new RegExp( "([-0-9]*)([dDhHmMyYsS]{0,1})" ));
		if ( matches && matches.length == 3 )
		{
			var i = parseInt( matches[1] );
			var expirationDate = new Date();
			switch ( matches[2] )
			{
			case "y":
			case "Y":
				expirationDate.setYear( expirationDate.getYear() + i );
				break;
			case "M":
				expirationDate.setMonth( expirationDate.getMonth() + i );
				break;
			case "":
			case "d":
			case "D":
				expirationDate.setDate( expirationDate.getDate() + i );
				break;
			case "h":
			case "H":
				expirationDate.setHours( expirationDate.getHours() + i );
				break;
			case "m":
				expirationDate.setMinutes( expirationDate.getMinutes() + i );
				break;
			case "s":
			case "S":
				expirationDate.setSeconds( expirationDate.getSeconds() + i );
				break;
			}
			if ( expirationDate ) s = s + "; expires=" + expirationDate.toGMTString();
		}
	}
	// add path 
	if ( pathName && pathName.length > 0 ) s = s + "; path=" + pathName;
	// add domain
	if ( domainName && domainName.length > 0 ) s = s + "; domain=" + domainName
	// write cookie string
	// alert( "cookie set: " + s );
	document.cookie = s;
}

// Deletes a cookie by setting the lifetime to null.
// Note that you must specify the currennt cookie value, as well as path and domain name 
// if called from a different location or if the cookie has a path and/or domain specified.
//
function deleteCookie( cookieName, cookieValue, pathName, domainName )
{
	setCookie( cookieName, cookieValue, 0, pathName, domainName );
}

// Retrieves a cookie value
//
function getCookie( cookieName )
{
	var matches = document.cookie.match( new RegExp( "\\b" + cookieName + "=([^;]*|)" ));
	if ( matches && matches.length == 2 ) return unescape( matches[1] );	
}

