function setCookie (name, value) {
	var largeExpDate = new Date ();
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	largeExpDate.setTime(largeExpDate.getTime() + (365 * 24 * 3600 * 1000));
	var expires = largeExpDate;
	document.cookie = name + "=" + escape (value) +"; expires=" + expires.toGMTString() +  "; path=/";
}


function getCookie(name) {
	if(document.cookie == "") return false;
	else {
		var cookieStart, cookieEnd;
		var cookieString = document.cookie;
		cookieStart = cookieString.indexOf(name+"=");
		if(cookieStart != -1) {
			cookieStart += name.length+1;
			cookieEnd = cookieString.indexOf(";", cookieStart);
			if(cookieEnd == -1) cookieEnd = cookieString.length;
			return cookieString.substring(cookieStart, cookieEnd);
		} else {
			return false;
		}
	}
}


// SHOPPING CART FUNCTIONS //

function getcart() {
	var rows = new Array();
	var cart = unescape(getCookie("shoppingcart"));
	if (cart) {
		rows = cart.split(" ");
	}
	return rows.length;
}

function emptycart() {
	setCookie("shoppingcart", "");
	return false;
}

function updatecart() {
	var cart = unescape(getCookie("shoppingcart"));
	var rows = new Array();
	var itm  = new Array();

	if (cart) {
		rows = cart.split(" ");
		for (i=0; i<rows.length; i++) {
			itm = rows[i].split("=");
			rows[i] = itm[0] + "=" + document.getElementById("qty_" + itm[0]).value;
		}
	}
	setCookie("shoppingcart", rows.join(" "));
	return false;
}

function removefromcart(id) {
	var rows = new Array();
	var itm  = new Array();
	var cart = unescape(getCookie("shoppingcart"));
	var newcartstring = "";

	if (cart) {
		rows = cart.split(" ");
		for (i=0; i<rows.length; i++){
			itm = rows[i].split("=");
			if (itm[0] != id && rows[i] != '') {
				newcartstring = newcartstring + rows[i] + " ";
			}
		}
		
	}
	if (newcartstring.length)
		newcartstring = newcartstring.substr(0, newcartstring.length-1);
	setCookie("shoppingcart", newcartstring);
}

function addtocart(id, quant) {
	var rows = new Array();
	var itm  = new Array();
	var cart = unescape(getCookie("shoppingcart"));
	var flag_available = false;

	if (cart) {
		rows = cart.split(" ");
		for (i=0; i<rows.length; i++) {
			itm = rows[i].split("=");
			if (itm[0] == id) {
				flag_available = true;
			}
		}
		
	}
	
	if (!flag_available) {
		if (rows && rows[0] != "false") {
			rows[rows.length] = id + "=" + quant;
		}
		else {
			rows[0] = id + "=" + quant;
		}
		setCookie("shoppingcart", rows.join(" "));
	}

	if (!flag_available)
		alert('This item is added into your shopping cart');
	else
		alert('This item is ALREADY in your shopping cart');
}
