function writeCookie(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=/";
}

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;
}

function wipeCookie(name) {
	writeCookie(name,"",-1);
}


/*
cart format
	name:number|name:number|...
*/

//set vars
var cart = 'cart';

function clearCart()
{
	wipeCookie(cart);
}
function addItem(itemname)
{
	var temp = readCookie(cart);
	if(temp == null)
	{
		writeCookie(cart, itemname+':1', 1);
	}
	else
	{
		if(temp.indexOf(itemname) == -1) //not in cart
			writeCookie(cart, temp+'|'+itemname+':1', 1);
		else //find and update
		{
			var tarr = temp.split('|');
			var forout = '';
			for(var i = 0; i < tarr.length; i++)
			{
				if(tarr[i].indexOf(itemname) == -1)
				{
					forout = forout + '|' + tarr[i];
				}
				else
				{
					var tt = tarr[i].split(':');
					forout = forout + '|' + itemname;
					var xx = parseInt(tt[1]) + 1;
					forout = forout + ':' + xx;
				}
			}
			if(forout[0] == forout[1] == '|')
				forout = forout.substring(1);
			writeCookie(cart, forout, 1);
		}		
	}
}

function setItem(itemname, howmany)
{
	var temp = readCookie(cart);
	if(temp == null)
	{
		writeCookie(cart, itemname+':'+howmany, 1);
	}
	else
	{
		if(temp.indexOf(itemname) == -1) //not in cart
		{
			writeCookie(cart, temp+'|'+itemname+':'+howmany, 1);
		}
		else //find and update
		{
			var tarr = temp.split('|');
			var forout = '';
			for(var i = 0; i < tarr.length; i++)
			{
				if(tarr[i].indexOf(itemname) == -1)
				{
					forout = forout + '|' + tarr[i];
				}
				else
				{
					var tt = tarr[i].split(':');
					forout = forout + '|' + itemname;
					forout = forout + ':' + howmany;
				}
			}
			if(forout[0] == forout[1] == '|')
				forout = forout.substring(1);
			writeCookie(cart, forout, 1);
		}		
	}
}

function clearItem(itemname)
{
	var temp = readCookie(cart);
	if(temp == null)
	{
		writeCookie(cart, itemname+':1', 1);
	}
	else
	{
		if(temp.indexOf(itemname) == -1) //not in cart
			wipeCookie(cart);
		else //find and update
		{
			var tarr = temp.split('|');
			var forout = '';
			for(var i = 0; i < tarr.length; i++)
			{
				if(tarr[i].indexOf(itemname) == -1)
				{
					forout = forout + '|' + tarr[i];
				}
			}
			writeCookie(cart, forout, 1);
		}		
	}
}

