/*

	General-purpose Javascript functions used by Trouble

*/

// Test for a "valid" email address format
// For right now just making sure there is one @
function IsValidEmailAddress(address)
{
	return (address.indexOf('@') != -1);
}

// Returns the value of the cookie specified by 'name' or
// NULL if the cookie was not found.
function GetCookie(name)
{
	var all_cookies = document.cookie.split( ';' );
	var temp_cookie = '';
	var cookie_name = '';
	
	for ( i = 0; i < all_cookies.length; i++ )
	{
		temp_cookie = all_cookies[i].split( '=' );
		cookie_name = temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
		if ( cookie_name == name )
		{
			// make sure cookie value exists
			if (temp_cookie[1])
				return unescape( temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			
			return "";
		}
	}

	return null;
}

// Saves a cookie with the provided information
// Use NULL values to omit them
// A NULL value for expiration_date implies saving it forever (or long enough anyway)
function SaveCookie(name, value, expiration_date, path, domain, secure)
{
	var exDate;

	if (expiration_date)
		exDate = new Date(expiration_date);
	else
		exDate = new Date("1/1/2038");

	document.cookie = name + "=" + escape(value) +				// name and value
		(exDate ? ";expires=" + exDate.toGMTString() : "") +	// expiration date if provided
		(path ? ";path=" + path : "") +							// path if provided
		(domain ? ";domain=" + domain : "") +					// domain if provided
		(secure ? ";secure" : "");
}

// Deletes a cookie by setting it's expiration date in the past
// This works differently on various browsers, some cache data
function DeleteCookie(name)
{
	document.cookie = name + "=; expires=Fri, 21 Dec 1976 04:31:24 GMT;";
}


// Gets a value from the window's querystring
// Returns NULL for invalid keys
function GetQueryStringValue(key)
{
	// get querystring
	var qs = location.search.substring(1,location.search.length);

	// switch + signs back into spaces
	qs = qs.replace(/\+/g, ' ');

	// split into key/value pairs
	var kvps = qs.split('&');

	// iterate through key-value pairs to find the one we want
	for (var i = 0; i < kvps.length; i++)
	{
		var pair = kvps[i].split('=');
		var name = unescape(pair[0]);

		if (name == key)
		{
			if (pair.length == 2)
				return unescape(pair[1]);
			else
				return name;
		}
	}

	return null;
}