
var AjaxCart = Class.create({
	initialize: function(elementIDs, baseURL) {
		this.elementIDs = elementIDs;
		this.url = baseURL;
		this.data = false;
		this.get('');
		this.updateView();
	},
	get: function(url_extras) {
		var request_url = this.url + url_extras; 
		new Ajax.Request(request_url,{
			method: 'post',
			parameters: { 'ajax': 1 },
			onSuccess: this.receive.bind(this)
		});
		//alert('get');
	},
	add: function(item_id,qty) {
		if (qty == "formfield") 
			qty = $F(item_id+'_qty');
		this.get('/add/'+item_id+'/'+qty);
		this.data = false;
		this.updateView();
		//alert('add');
	},
	receive: function(transport) {
		this.data = transport.responseText.evalJSON();
		this.updateView();
		//alert('receive');
	},
	updateView: function() {
		//alert('update');
		var loading    = $(this.elementIDs.loading);
		var cartview   = $(this.elementIDs.cartview);
		var noitemview = $(this.elementIDs.noitemview);

		if (!this.data) {
			if (loading) jQuery(loading).show();
			if (cartview) jQuery(cartview).hide();
			if (noitemview) jQuery(noitemview).hide();
		}

		if (loading) jQuery(loading).hide();
		
		if (this.data.num_items) {
			if (cartview) jQuery(cartview).show();
			if (noitemview) jQuery(noitemview).hide();
		} else {
			if (cartview) jQuery(cartview).hide();
			if (noitemview) jQuery(noitemview).show();
		}

		var count = $(this.elementIDs.count);
		if (count) count.innerHTML = this.data.num_items;
		var total = $(this.elementIDs.total);
		if (total) total.innerHTML = this.data.total;

		//alert('updateView');
	}
});


