//	Copyright: Well-connected Ltd (http://www.well-connected.net/), 2012. All rights reserved.

function get_random_id () {
	return Math.round ( Math.random () * 10000 );
}

function set_cookie ( name, value, expires, path, domain, secure ) {
//	Set time in milliseconds
	var today = new Date ();
	today.setTime ( today.getTime () );

	if ( expires ) {
//		If the expires variable is set, make the correct expires time.
//		The default will set it for x number of days.
//		To make it for hours, delete * 24, for minutes, delete * 60 * 24

		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime () + ( expires ) );

	document.cookie = name + "=" + escape ( value ) +
		( ( expires )	? "; expires=" + expires_date.toGMTString() : "" ) +
		( ( path )	? "; path=" + path : "" ) +
		( ( domain )	? "; domain=" + domain : "" ) +
		( ( secure )	? "; secure" : "" );
}

function get_cookie ( check_name ) {
//	First split cookie into name=value pairs.
//	Note: document.cookie only returns name=value, not the other components.
	var a_all_cookies	= document.cookie.split(';');
	var a_temp_cookie	= '';
	var cookie_name		= '';
	var cookie_value	= '';
	var b_cookie_found	= false;

	for ( var i = 0; i < a_all_cookies.length; i++ )
	{
//		Split name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );

//		Trim left/right whitespace
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

//		Check if the extracted name matches the argument check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
//			Cookie has no value, but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
//			Note: if cookie is initialised but without a value, null is returned
			return cookie_value;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	return null;
}

function clone_cookie ( name, path, domain ) {
	var cookie_value = get_cookie ( name );

	if ( cookie_value ) {
		var cookie_name = name + "_" + get_random_id ();
		document.cookie = cookie_name + "=" + cookie_value +
			( ( path )	? "; path=" + path : "") +
			( ( domain )	? "; domain=" + domain : "" );
		return cookie_name;
	} else {
		return false;
	}
}

function delete_cookie ( name, path, domain ) {
	document.cookie = name + "=" +
		( ( path )	? "; path=" + path : "") +
		( ( domain )	? "; domain=" + domain : "" ) +
		"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function save_form_cookie ( form_name ) {
	var cookie_name		= form_name;
	var cookie_value	= serialise_form ( form_name );
	var cookie_expiry	= 2;

	set_cookie ( cookie_name, cookie_value, cookie_expiry );
}

