// JavaScript Document

/* 
Creates a cookie to store information on a client's computer.

@usage createCookie("mycookie" ,"value of my cookie" , 7)
@param name - String - 
@param value - String - 
@param days - Integer - Number of days until cookie expires, and is deleted. Set to 0 for cookie to be deleted once browser is closed.
*/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


/*
Read a cookie stored on the client's computer.

@usage   var x = readCookie('ppkcookie1')
		 if (x) {
			[do something with x]
		 }
		 
@param name - String - The name of the cookie to read
@return the cookie as a String. If the cookie can't be found, null is returned. Null must be checked for on the return of this function.
*/
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*
Delete a cookie stored on the client's computer, by setting the cookie with an expiry date of one day ago.
The browser, seeing that the expiry date has passed, immediately removes the cookie.

@usage  eraseCookie('ppkcookie')

@param name - String - the name of the cookie to be erased

*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}


/* 
Tests if cookies are enabled on the users browser.
A cookie is created and then an attempt is made to retrived it.
If cookies are enable, it will be retieved.

@usage if checkCookiesEnabled() {
          ...
	   }else{
	   	  ... redirect to error message page
	   }
	   
@returns true or false if cookies enabled or disabled
*/
function cookiesEnabled() {
	createCookie('testIfCookiesEnabled','yes',0);
	var x = readCookie('testIfCookiesEnabled');
	
	if(x){
		//Cookies enabled, so delete it.
		eraseCookie('testIfCookiesEnabled');
		return true;
	}else{
		//Cookie wasnt returned, ie cookies disabled.
		return false;
	}
}
