(function($) {
	$.cart = function(tire_id, quantity) {
		var cart = parseCookie();
		if (tire_id) {								// $.cart() returns the entire cart object.
			if (typeof(quantity) == "undefined") {	// $.cart(123) returns the current quantity of tire 123.
				return (tire_id in cart) ? cart[tire_id] : 0;
			} else {
				if (quantity === 0) {				// $.cart(123, 0) deletes tire 123 from cart.
					delete cart[tire_id];
				} else {							// $.cart(123, 2) sets the quantity of tire 123 to 2.
					cart[tire_id] = quantity;
				}
				writeCookie(cart);
			}
		}
		return cart;

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

		function writeCookie(cart) {
			var crumbs = [];
			for (var i in cart) {
				crumbs.push('"' + i + '":' + cart[i]);
			}
			$.cookie('talon_cart', "{" + crumbs.join(",") + "}", { expires: 30, domain: '.talontire.com'});
		}
	}
})(jQuery);
