document.observe('dom:loaded', function (event) {
	$$('input.product-quantity').each( function(elem) {

		elem.setTotalPrice = function(transport) {

			// Check the outcome of the transport
			if (!transport.responseJSON.totalPrice) {
				this.showFailureMessage(transport);
				return false;
			}

			// For now: reload the entire page after changing the amount.
			// In the future we will set the new price immediately and update the (sub)totals as well
			window.top.document.location.reload();
		}

		elem.showFailureMessage = function(transport) {

			dialogElem = window.top.PbLib.createDialog(false, 400, 75);
			dialogElem.update("<div style='text-align: center;'>" +
				"<div>" + transport.responseJSON.msg + "</div>" +
				"<div><a href='#' onclick='Event.stop(event); window.top.document.location.reload(); window.top.PbLib.destroyDialog();'>" +
				PbLib.g('Close') + "</a></div>" + "</div>");

			if (transport.responseJSON.stockAmount && this.value > transport.responseJSON.stockAmount) {
				this.value = transport.responseJSON.stockAmount;
			}

			return false;
		}

		elem.observe('change', function(event) {
			var productId = this.name.sub('product-quantity-', '');
			var url = PbLib.getNewURI('l/webshop2/shoppingcart/quantity/' + productId + '/' + this.value);
			new Ajax.Request(url, {
					'onSuccess': this.setTotalPrice.bindAsEventListener(this),
					'onFailure': this.showFailureMessage.bindAsEventListener(this)
				});
		});

	});
});