/*  CART FUNCTIONS  */
/*
 *  Hook events for all cart pages
 */
Event.observe(window, "load",
		function() {
			/*  Category products list handling hooks  */
			$$("#productDetails .button").each(
				function(item) {
					Event.observe(item, "click", handleAddToCart);
				}
			);


			/*  Product details */
			$$("#popup_content_product .button").each(
				function(item) {
					Event.observe(item, "click", handleAddToCart);
				}
			);


			$$("table.cartView .cartColQuantity input[type='text']").each(
				function(item) {
					Event.observe(item, "keydown", handleChangeQuantity)
				}
			);
			if( $("btnUpdate") )
				Event.observe($("btnUpdate"), "click", handleUpdateCart );

		}
);

/*  User adds a product to the cart.
 * Add the product and update the cart summary
 */
function handleAddToCart( event ) {
	var cartHoldSummaryObject;
	var form = Event.findElement(event, "FORM");
	var length = 0, validQuantityFound = false;
	
	/*  We are the only ones who can handle this event  */
	Event.stop( event );

	for (var i = 0, length = form.elements.length; i < length; i++) {
		if( form.elements[i].name.match(/^f_quantity\d*/) ) {
			if( parseInt(form.elements[i].value) != NaN && parseInt(form.elements[i].value) >= 0 ) {
				validQuantityFound = true;
			}
		}
	}

	// TODO: Replace this with a more user friendly message
	if( ! validQuantityFound ) {
		alert( "Bitte fügen Sie mindestens ein Stück." );
		return false;
	}

	cartHoldSummaryObject = $("cart_hold_summary");

	/*  Use POST method: http://www.cs.tut.fi/~jkorpela/forms/methods.html  */
	new Ajax.Updater(cartHoldSummaryObject, p_web_root_lang + "/gastgeber/shop/index.cfm",
			{
			method:'post',
			parameters:form.serialize(true),
			onSuccess:function() { new Effect.Highlight( "cart_summary", {duration:1} ); new Effect.Highlight( "cart_info", {duration:1} );},
			onFailure:function(t) { alert('Error: ' + t.status + ' -- ' + t.statusText);}
			});

	/*  Clear the quantity the user entered (signal that the operation went ok)  */
	for (var i = 0, length = form.elements.length; i < length; i++) {
		if( form.elements[i].name.match(/^f_quantity\d*/) ) {
			form.elements[i].value = '';
		}
	}

	return false;
}


/*
 *  Called after the user changes product quantity when viewing the cart.
 */
function handleChangeQuantity( event ) {
	Element.hide("btnOrder");
	Element.show("btnUpdate");

	/*  IE doesn't want to submit a form if the submit button is hidden
	 * (and this happens when we hide the Order button and display the Update button)
	 * so handle that case here. If the user hits ENTER then update the cart.
	 */
	if( event.keyCode == 13) {
		handleUpdateCart( event );
	}
}


/*
 *  Called when the user clicks on the button to update cart quantities
 * The product table prices is updated via received Javascript (so we evaluate javascript
 * in the reponse)
 */
function handleUpdateCart( event ) {
	var params = new Object();
	var productQuantities = $$("table.cartView .cartColQuantity input[type='text']");

	params["fuseaction"] = "update_quantities";
	params["ids"] = "";

	/*  For each product in the cart have field with the name "f_quantity#id#" and the value is the new quantity  */
	for(var i=0; i < productQuantities.length; i++) {
		params["ids"] = params["ids"] + productQuantities[i].id.replace(/f_quantity/i, '') + ",";
		params[ productQuantities[i].id ] = productQuantities[i].value;
	}

	/*  We are the only ones who can handle this event  */
	Event.stop( event );

	var ajax = new Ajax.Updater("ajax-response-holder", p_web_root_lang + "/gastgeber/shop/index.cfm",
			{
			method:'post',
			evalScripts:true,
			parameters:params,
			onComplete:function() {
					Element.show("btnOrder");
					Element.hide("btnUpdate");
			},
			onFailure:function(t) { alert('Error: ' + t.status + ' -- ' + t.statusText); }
			});
}
