(function($) {
	$.cart = function(product_id, values, quantity) {
		var cart = parseCookie();
		if (product_id) {	                        // $.cart() returns the enproduct cart object.
			product_id = parseInt(product_id, 10);
			values = $.map(values, function(value) { return parseInt(value, 10); });
			var index = indexOf(product_id, values);

			if (typeof(quantity) == "undefined") {	// $.cart(123, [1, 2]) returns the current quantity of product 123 and values [1, 2].
				return index != -1 ? cart[index].quantity : 0;
			} else {
				quantity = parseInt(quantity, 10);
				if (quantity === 0) {               // $.cart(123, [1, 2], 0) deletes product 123-1,2 from cart.
					cart.splice(index, 1);
				} else {                            // $.cart(123, [1, 2], 2) sets the quantity of product 123-1,2 to 2.
					var item = {
						product_id: product_id,
						quantity: quantity,
						values: values
					}
					if (index == -1) {
						cart.push(item);
					} else {
						cart[index] = item;
					}
				}
				writeCookie();
			}
		}
		return cart;

		function indexOf(product_id, values) {
			for (var i in cart) {
				if (cart[i].product_id == product_id && $(cart[i].values).compare(values)) {
					return i;
				}
			}
			return -1;
		}

		function parseCookie() {
			var cookie = $.cookie('omani_cart');
			if (cookie) {
				try {
					return $.parseJSON(cookie) || [];
				} catch (e) {
					return [];
				}
			}
			return [];
		}

		function writeCookie() {
			var crumbs = [];
			for (var i in cart) {
				crumbs.push(
					'{"product_id":' + cart[i].product_id + ',"quantity":' + cart[i].quantity + ',"values":[' + cart[i].values.toString() + ']}'
				);
			}
			$.cookie('omani_cart', "[" + crumbs.join(",") + "]", { expires: 30, domain: '.'+location.hostname, path: '/' });
		}
	};

	$.cart.empty = function() {
		$.cookie('omani_cart', null, { domain: '.'+location.hostname, path: '/' });
	};
})(jQuery);
