/*  CART FUNCTIONS  */


/*
 *  Hook events for all cart pages
 */
Event.observe(window, "load",
		function() {
			/*  Category products list handling hooks  */
			$$("table.products .content .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);
			}
			if( $("btnClear") ) {
				Event.observe($("btnClear"), "click", handlerClearCart);
			}
		}
);

function checkHideSummary() {
	if( hideCartSummary ) {
		Element.hide("cart_contents");
	} else {
		setTimeout('checkHideSummary()', 500);
	}
}

function attachCartSummaryEvents() {
	Event.observe($("cart_contents"), "mouseover", function( event ) { hideCartSummary = false; return false; });
	Event.observe($("cart_contents"), "mouseout",  function( event ) { hideCartSummary = true;  return false; });

	Event.observe($("cart_image"), "mouseover",
		function( event ) {
			hideCartSummary = false;
			Element.show("cart_contents");
			return false;
		}
	);
	Event.observe($("cart_image"), "mouseout",
		function( event ) {
			hideCartSummary = true;
			setTimeout('checkHideSummary()', 500);
			return false;
		}
	);
}


/*  User adds a product to the cart.
 * Add the product and update the cart summary
 */
function handleAddToCart( event ) {
	var params = new Object();
	var cartHoldSummaryObject;
	
	params["fuseaction"] = "add_product";
	params["id"]         = Event.findElement(event, "FORM").id.value;
	params["f_quantity"] = Event.findElement(event, "FORM").f_quantity.value;

	/*  We are the only ones who can handle this event  */
	Event.stop( event );

	// TODO: Replace this with a more user friendly message
	if( params["f_quantity"] == '' || isNaN(params["f_quantity"]) || params["f_quantity"] < 0 ) {
		alert( "Bitte geben Sie eine Zahl größer als 0 ein." );
		return false;
	}
	
	if( window.opener ) {
		/*  We're in a popup, refresh the cart summary from the window that opened us  */
		cartHoldSummaryObject = window.opener.document.getElementById( "cart_summary_holder" );
	} else {
		cartHoldSummaryObject = $("cart_summary_holder");
	}


	/*  Use POST method: http://www.cs.tut.fi/~jkorpela/forms/methods.html  */
	var ajax = new Ajax.Updater(cartHoldSummaryObject, p_web_root + "/label/index.cfm",
			{
			method:'post',
			evalScripts:true,
			parameters:params,
			onComplete:function() {
									if( $("latest_news_background") && Element.visible( $("latest_news_background") ) ) {
										Element.hide( $("latest_news_background") );
										Element.hide( $("latest_news") );
									}

									if( ! Element.visible( $("cart_summary_background") ) ) {
										Element.show( $("cart_summary_background") );
										Element.show( $("cart_summary_holder") );

										/*  Animate cart appearance  */
										new Effect.SlideDown("cart_summary", {duration:1});
									}
								},
			onFailure:function(t) { alert('Error: ' + t.status + ' -- ' + t.statusText);}
			});

	/*  Clear the quantity the user entered (signal that the operation went ok)  */
	Event.findElement(event, "FORM").f_quantity.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("cart_summary_holder", p_web_root + "/label/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); }
			});
}


function handlerClearCart( event ) {
	var params = new Object();

	params["fuseaction"] = "clear_cart";

	/*  We are the only ones who can handle this event  */
	Event.stop( event );

	var ajax = new Ajax.Updater("cart_summary_holder", p_web_root + "/label/index.cfm",
			{
			method:'post',
			evalScripts:true,
			parameters:params,
			onComplete:function() {
					Element.hide("btnOrder");
					Element.show("btnUpdate");
					
					/*  Force a refresh from the server, otherwise Firefox might cache quantity input values  */
					window.location.reload( true );
			},
			onFailure:function(t) { alert('Error: ' + t.status + ' -- ' + t.statusText); }
			});
}
