/**
 * Functions to create, read and delete cookies
 */

/*
 This method writes a cookie, assuming that the path will be "/".

 Sample usage:
 createCookie("loginStatus", "logged_in", "20");
 Writes a cookie named "loginStatus" and with a value "logged_in". The
 cookie will expire 20 days from first creation.
 "path" and "domain" are set automatically.

 Parameters:
 name: The name of the cookie (e.g. "loginStatus")
 value: The value related to the cookie (e.g. "logged_in")
 days: The amount of days the cookie shall "live". The script will calculate
       the correct expiration date.
*/
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 {
		// if no days have been submitted, the cookie expires
		// when closing the browser
		var expires = "";
	}
	// write the cookie
	document.cookie = name+"="+value+expires+"; path=/";
}

/*
 This method writes a cookie, assuming that the path will be "/" with a specified domain

 Sample usage:
 createDomainCookie("loginStatus", "logged_in", "20", "www.domain.com");
 Writes a cookie named "loginStatus" and with a value "logged_in". The
 cookie will expire 20 days from first creation.
 "path" and "domain" are set automatically.

 Parameters:
 name: The name of the cookie (e.g. "loginStatus")
 value: The value related to the cookie (e.g. "logged_in")
 days: The amount of days the cookie shall "live". The script will calculate
       the correct expiration date.
 domain: The domain where the cookie is written, which must be the current
         host or another proper value to actually set the value of the cookie.
*/
function createDomainCookie(name,value,days,domain) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		// if no days have been submitted, the cookie expires
		// when closing the browser
		var expires = "";
	}
	// write the cookie
	document.cookie = name+"="+value+expires+"; path=/;domain="+domain;
}

/*
 This method reads a cookie.

 Sample usage:
 readCookie("loginStatus");
 Reads the cookie with the name "loginStatus". .

 Parameters:
 name: The name of the cookie (e.g. "loginStatus")
*/
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;
}

/*
 This method deletes a cookie by "overwriting" it with days=-1, which
 is an expired date.

 Sample usage:
 eraseCookie("loginStatus");
 Deletes the cookie with the name "loginStatus". .

 Parameters:
 name: The name of the cookie (e.g. "loginStatus")
*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}