function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function addProduct(productId, size, quantity) {

	var productIds = '';
	var sizes = '';
	var quantities = '';

	// Check to see if the user already has products in their basket.
	existingIds = getCookie('pId');
	existingSizes = getCookie('pS');
	existingQuantites = getCookie('pQ');

	// Set the arrays that we're going to be using later.
	var productIds = [];
	var sizes = [];
	var quantities = [];


	// If the cookies are set the user has products in their cart
	// Lets find out what they are.
	if(existingIds.length > 0) {
		if(existingIds.indexOf(',') !== -1) {
			productIds = existingIds.split(',');
			sizes = existingSizes.split(',');
			quantities = existingQuantites.split(',');
		} else {
			productIds.push(existingIds);
			sizes.push(existingSizes);
			quantities.push(existingQuantites);
		}
	}

	// Regardless of if the products have been set above or not,
	// add the new product to an array, so that we can update the cookie.
	productIds.push(productId);
	sizes.push(size);
	quantities.push(quantity);

	cookieIds = productIds.join(',');
	cookieSizes = sizes.join(',');
	cookieQuantities = quantities.join(',');

	setCookie('pId', cookieIds, 1);
	setCookie('pS', cookieSizes, 1);
	setCookie('pQ', cookieQuantities, 1);

}

function removeProduct(arrayIndex) {

	var newIds = [];
	var newSizes = [];
	var newQuantites = [];

	existingIds = getCookie('pId');
	existingSizes = getCookie('pS');
	existingQuantites = getCookie('pQ');

	productIds = existingIds.split(',');
	sizes = existingSizes.split(',');
	quantities = existingQuantites.split(',');

	if(typeof(productIds) == 'object') {
		for(i = 0; i < productIds.length; i++) {
			if(i !== arrayIndex) {
				newIds.push(productIds[i]);
				newSizes.push(sizes[i]);
				newQuantites.push(quantities[i]);
			}
		}
		setCookie('pId', newIds, 1);
		setCookie('pS', newSizes, 1);
		setCookie('pQ', newQuantites, 1);
	} else {
		clearCart();
	}

}

function clearCart() {

	// User wishes to clear their cart.

	var emptyArray = [];

	setCookie('pId', emptyArray, 1);
	setCookie('pS', emptyArray, 1);
	setCookie('pQ', emptyArray, 1);

}
