
var Cart = { };

Cart.addItem = function (form, quantity) {
	var result = Cart.sendItem(form, quantity);
}

Cart.sendItem = function (form) {
	var args = form.serialize( { hash: false, submit: false } );
	var opts = {
			parameters:		args,
			onSuccess:		Cart.itemAddOK,
			onFailure:		Cart.itemAddFailed
		};

	new Ajax.Request('/TP/shop/add-item.php', opts);
}


Cart.itemAddOK = function (response) {
	if (!response.responseJSON) {
		var mesg;
		// Oops ... probably error from PHP
		if (response.responseText)
			mesg = response.responseText.stripTags();
		else
			mesg = Object.inspect($H(response));
		jsError(mesg);
		alert('Internal error in Cart.addItemOK.  Webmaster has been notified.');
		return;
	}
	Cart.showCart();
	Cart.updateCartDisplay(response.responseJSON);
	Cart.notifyCustomer(response.responseJSON);
	window.location.href = '/show-cart.php';
}

Cart.itemAddFailed = function(response) {
	alert('Add-item failed: ' + response.status);
}

Cart.updateCartDisplay = function (stats) {
	Cart.updateItemCount(stats.itemCount);
	Cart.updateTotalCost(stats.totalCost);
}

Cart.notifyCustomer = function(response) {
	//alert('Item added to cart');
}

Cart.startPage = function() {
	Cart.getStats();
}

Cart.getStats= function () {
	var opts = {
			onSuccess:		Cart.gotStats,
			onFailure:		Cart.failedStats
		};

	new Ajax.Request('/TP/shop/get-cart-stats.php', opts);
}

Cart.showCart = function() {
	$('cart-slot').show();
}

Cart.removeItem = function (uid) {
	Cart.doRemoveAction(uid);
}

Cart.empty = function () {
	if (confirm('Really throw away cart contents?'))
		Cart.doRemoveAction('all');
}

Cart.doRemoveAction = function (uid) {
	var opts = {
		method:			'get',
		onSuccess:		function () { location.href = location.href; },
		onFailure:		Cart.removeFailed
	};

	if (uid == 'all')
		opts.parameters = { all: 1 };
	else
		opts.parameters = { uid: uid };

	new Ajax.Request('/TP/shop/remove-item.php', opts);
}

Cart.removeFailed = function (response) {
	jsError('Cart.empty failure: ' + response.responseText);
	alert('Internal error: webmaster notified');
}

Cart.gotStats = function(response) {
	var stats = response.responseJSON;

	if (stats.hasCart) {
		Cart.showCart();
		Cart.updateItemCount(stats.itemCount);
		Cart.updateTotalCost(stats.totalCost);
	}
}

Cart.updateItemCount = function(count) {
	$('item-count').down('span').update(count);
}

Cart.updateTotalCost = function(total) {
	$('item-total').down('span').update(total);
}

Cart.failedStats = function(response) {
	alert('Internal error: ' + response.responseText);
}
