// All functions for providing a working cookie system within an Ajax framework

function setCookie(cName,value,expireDays) // function for setting a JS cookie
{
	if (expireDays)
	{
		var date = new Date(); // create a new JS date object
		date.setTime(date.getTime()+(expireDays*24*60*60*1000)); // set date object of todays time plus expiry time in milliseconds
		var expires = ";expires="+date.toGMTString(); // set the cookie expiry string to equal a formatted GMT string
	}
	else
	{
		var expires = ""; // if not set will never expire
	}
	document.cookie = cName + "=" + value + expires; // set the cookie with name, value and expiry date
}

function readCookie(cName) // function for reading a JS cookie
{
	var cookieFQ = cName + "="; // set a variable for the fully qualified cookie name string
	var cookieCrumbs = document.cookie.split(';'); // split the cookie string on ; into an array. This seperates all values
	for(var i=0;i < cookieCrumbs.length;i++) // for loop steps through cookie array
	{ 
		var crumb = cookieCrumbs[i]; // assign a variable for each crumb of cookie array
		while (crumb.charAt(0)==' ') // check cookie string to see if white space
		{
			crumb = crumb.substring(1,crumb.length); // remove white space if found
		}
		if (crumb.indexOf(cookieFQ) == 0) // search for fully qualified name, if found
		{
			return crumb.substring(cookieFQ.length,crumb.length); // then return the value as a substring, removing FQ name
		}
	}
	return null; // else return cookie does not exist
}

function checkCookie(cName) // function for checking cookie existance
{
	if (document.cookie.length>0) // make sure any cookies exist
  	{
  		var isCookieSet = document.cookie.indexOf(cName) // find cookie name in cookie list
  		if ( isCookieSet == -1 ) // if this return -1 then cookie is not set
    	{ 
     		return false;
		}
		else // otherwise it is
		{	
			return true;
		}
    }
	else
	{
		return false; // on total failure fail function
	}		
}

function deleteCookie(cName) // function for deleting the cookie
{
	setCookie(cname,"",-1); // simply set cookie to expire 1 day previously
}
