// JavaScript version of cookie.class.php (cookies are interchangeable)
// Version: 1.0
// Date: 14-Mar-2009
// Cookie is in the format:  escape(escape(value),escape(value),escape(value),escape(value))

// Cookie object
function Cookie(name, domain, path, lifetime)
{
	// Properties
	this.name = (typeof(name)=='undefined') ? 'CookieWithNoName' : name;
	this.domain = (typeof(domain)=='undefined') ? 'photosuccession.net' : domain;
	this.path = (typeof(path)=='undefined') ? '/' : path;
	this.lifetime = (typeof(lifetime)=='undefined') ? 1 : lifetime; // lifetime is in days
	this.data = new Array(); // Will hold a list of all items in the cart (duplicates are OK)
	this.parse = ',';

	// Methods
	this.add = cookie_add;
	this.remove = cookie_remove;
	this.clear = cookie_clear;
	this.save = cookie_save;
	this.destroy = cookie_destroy;


	// Get cart data from existing cookie if it's there
	var cookieStart, cookieEnd, cookieData, cookieValues, value;
	if (document.cookie.length>0)
	{
		cookieStart=document.cookie.indexOf(this.name + "=");
		if (cookieStart!=-1)
		{
			// Get start and end of cookie data
			cookieStart=cookieStart + this.name.length+1;
			cookieEnd=document.cookie.indexOf(";",cookieStart);
			if (cookieEnd==-1) cookieEnd=document.cookie.length;

			// Split cookie data into an array (this.parse is the data seperator)
			cookieData = document.cookie.substring(cookieStart,cookieEnd);
			cookieData = unescape(cookieData); // This removes the first layer of encoding to reeveal the parse characters
			if (cookieData.length > 0) cookieValues = cookieData.split(this.parse);

			// Unescape each value and add it to this.data
			for (i in cookieValues) this.add(unescape(cookieValues[i])); // This removed the second layer of coding to reveal the data
		}
	}

}

function cookie_add(value)
{
	this.data.push(value);
}

function cookie_remove(value)
{
	for (i in this.data)
	{
		if (this.data[i] == value)
		{
			this.data.splice(i, 1); // Remove first item then break out of loop
			break;
		}
	}
}

function cookie_clear()
{
	this.data = new Array();
}

function cookie_save()
{
	// Encode cookie data
	var encodedValues = new Array();
	for (i in this.data) encodedValues.push(escape(this.data[i])); // Encode the data so it won't be confused with parse characters
	var cookieData = escape(encodedValues.join(this.parse)); // Encode the final string to protect parse characters

	// Calculate cookie expiry
	var expiryDate=new Date();
	expiryDate.setDate(expiryDate.getDate()+this.lifetime);

	// Save cookie
	document.cookie = this.name+'='+cookieData+';domain='+this.domain+';path='+this.path+';expires='+expiryDate.toGMTString();
}

function cookie_destroy()
{
	this.lifetime = -1;
	this.clear();
	this.save();
}


