function clickCart (el, elNo) {
	document.getElementById(el).value = updateCart(elNo, document.getElementById(el).value); 
	return true;
}

function setCookie(name, value) {
	// document.cookie = name + "=" + escape(value);
	document.cookie = name + "=" + value;
}

function clearCart () {
	setCookie ('cart', '');
	deleteCookie('cart');
	displayCartTotal();
}

function getCookie(name) {
	if (document.cookie.length>0) {
  		c_start = document.cookie.indexOf(name + "=");
  		if (c_start!=-1) { 
    			c_start=c_start + 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 updateCart(product_price_id, qty) {
	// alert ('' + product_price_id + '' + qty + '' + cookie);

	// Read the existing cookie to check for this product
	var cookie = getCookie('cart');
	
	qty = parseInt(qty);
	if (isNaN(qty)) {
		qty = 0;
	}


	// We should now have a list of product_price_ids and qtys separated by commas
	var products = new Array();
	var newProducts = new Array();
	products = cookie.split(",");

	var i=0;

	var arrayLength = products.length;

	while (i < arrayLength) {
		if (products[i] != product_price_id) {
			newProducts.push(products[i]);
			newProducts.push(products[i+1]);
		}
		i++;
		i++;
	}

	if (qty > 0) {
		newProducts.push(product_price_id);
		newProducts.push(qty);
	}

	var newCookie = newProducts.join(",");
	setCookie("cart", newCookie);
	// alert (newCookie);
	displayCartTotalDelay();
	return qty;


}

function displayCartTotalDelay () {
	document.getElementById("cart_items").innerHTML = 'Updating';
	setTimeout ('displayCartTotal()', 1000 );
}

function clearSearchBox () {
	var el = document.getElementById("search_box");
	el.innerHTML = '';
}

function displayCartTotal () {
	var cookie = getCookie('cart');
	var products = new Array();
	products = cookie.split(",");
	var arrayLength = products.length;
	var productCount = 0;

	var i = 0;
	while (i < arrayLength) {
		i++;
		if (products[i] > 0) {
			productCount++;
		}	
		i++;
	}

	// var items = '<form method="GET" action="' + window.location.href + '">';
	var items = '' + productCount + ' ';
	if (productCount == 1) {
		items += 'item ';
	}
	else {
		items += 'items ';
	}
	// items += '</form>';
	document.getElementById("cart_items").innerHTML = items;
}

function deleteCookie(name) {
	var d = new Date();
	document.cookie = name + ";expires=" + d.toGMTString() + ";";
}
function clearSearchBox () {
	//var search_string=document.form1.search_string.value;
	document.form1.search_string.value="";
}

