// Use a DIV which is only present in the MBT Store layout to deduce which website
// the user is viewing at the moment and set a variable so that exceptions can be made
// in the functions below
var bKathmandu;
if ($('container-wrap')) {
	bKathmandu = false;
} else {
	bKathmandu = true;
}

// A function which alters the display of the shopping cart content DIV,
// depending on its state at the time of invoking this function
function fToggleCartContent() {
	// Store local references to DOM elements to save memory
	var divCartContent;
	var anchorShowCart = $('showCart');
	if (bKathmandu) { divCartContent = $('cartContent'); } else { divCartContent = $('cartOpen'); }

	// If the DIV was hidden, display it and alter a few related styles
	// Otherwise, hide it and alter a few related styles back
	if (divCartContent.getStyle('display') == 'none') {
		anchorShowCart.set('html', 'verberg');
		anchorShowCart.setAttribute('title', 'Verberg verkorte overzicht');
		divCartContent.setStyle('display', 'block');

		// If this is the MBT Store website, make the shopping appear open
		if (!bKathmandu) { $('cart').addClass('open'); }
	} else {
		anchorShowCart.set('html', 'toon');
		anchorShowCart.setAttribute('title', 'Toon verkorte overzicht');
		divCartContent.setStyle('display', 'none');

		// If this is the MBT Store website, make the shopping appear closed
		if (!bKathmandu) { $('cart').removeClass('open'); }
	}
}


// A function which initialises the shopping cart by checking the cookie for
// any previously added items and loading them into the shopping cart DIV
// If no items were found in the cookie, feedback is provided for the user
function fInitCart() {
	// Iterate through the cookie array to store the desired cookies into another
	// array, formatted correctly for use with JSON.decode
	var aItemCookies = fGetItemCookies();

	// If the array containing cookies which are prefixed by 'item' is not empty, proceed
	// to iterate through it; otherwise, it means there were no previously added items found,
	// so display feedback to the user that the shopping cart is empty
	if (aItemCookies.length > 0) {
		// Use the corresponding cart icons for the website the user is on
		var sIconPath = "";
		if (!bKathmandu) { sIconPath = "mbt-store/"; }

		// Iterate through the array of JSON-formatted strings and add each item (and its details) to 
		// the HTML which will be used for creating the visual representation of the shopping cart
		var htmlCartContent = '';
		var iTotalNumber = 0;
		var iTotalPrice = 0;
		var sCurrName = '';
		for (iCnt = 0; iCnt < aItemCookies.length; iCnt++) {
			// Decode the current JSON string for access to its properties
			var oItem = JSON.decode(aItemCookies[iCnt]);

			// Add the quantity of the current item and the total of 
			// this item's price*quantity to the total price
			iTotalNumber = iTotalNumber + parseInt(oItem.quantity);
			iTotalPrice = iTotalPrice + (parseFloat(oItem.price) * parseInt(oItem.quantity));

			// If the current item's name is too long, truncate it
			if ((oItem.name).length > 16) {
				sCurrName = (oItem.name).substring(0, 15) + '...';
			} else {
				sCurrName = oItem.name;
			}

			htmlCartContent = htmlCartContent + 
												'<div id="item' + oItem.id + '" class="item">' + 
													'<div class="left"><img src="' + oItem.image + '" width="45" height="45" alt="' + oItem.name + '" title="' + oItem.name + '" /></div>' + 
													'<div class="right">' + 
														'<span class="name">' + sCurrName + '</span><br />' + 
														'<span class="size">' + oItem.size + '</span><br />' + 
														'<span class="price">&euro; ' + ((parseFloat(oItem.price).toFixed(2)).toString()).replace(/\./, ',') + '</span>' + 
													'</div>' + 
													'<div class="controls">' + 
														'<span id="item' + oItem.id + '_nr" class="number">' + oItem.quantity + '</span>' + 
														'<div>' + 
															'<a href="javascript:void(0);" class="plus" title="Meer" onclick="fIncrementItem(' + oItem.id + ', \'small\')"><img src="../media/img/' + sIconPath + 'icon/cart-plus.gif" width="11" height="10" alt="Meer" /></a>' + 
															'<a href="javascript:void(0);" class="min" title="Minder" onclick="fDecrementItem(' + oItem.id + ', \'small\')"><img src="../media/img/' + sIconPath + 'icon/cart-minus.gif" width="11" height="10" alt="Minder" /></a>' + 
															'<a href="javascript:void(0);" class="del" title="Verwijder" onclick="fRemoveFromCart(' + oItem.id + ', \'small\')"><img src="../media/img/icon/cart-delete.gif" width="12" height="12" alt="Verwijder" /></a>' + 
														'</div>' + 
													'</div>' + 
												'</div>';
		}

		// Set the generated HTML output to reside in the shopping cart items DIV element
		// and add the total price + cart buttons to the bottom of the parent DIV
		$('cartItems').set('html', htmlCartContent);
		fAddCartOrderDetails();

		// Set the shopping carts HTML elements for total quantity and total cost
		// to reflect the values calculated in the above for loop
		$('cartTotalNr').set('html', iTotalNumber);
		$('totalPrice').set('html', fConvertCurrency(iTotalPrice.toFixed(2)));
	} else {
		$('cartItems').set('html', '<p class="noDisplay">Uw winkelmandje is nog leeg.</p>');
		$('cartTotalNr').set('html', 0);
	}
}


// A function which adds some elements to the DOM making it possible to
// see the total price of the order and to view it or continue to purchase
function fAddCartOrderDetails() {
	var orderDetails = new Element("div", {"id": "orderDetails"}).injectAfter($('cartItems'));
	var htmlOrderDetails =	'<strong>Totaal:</strong> &euro; <span id="totalPrice">0,00</span>' + 
													'<div class="clearer">&nbsp;</div>';

	if (bKathmandu) {
		htmlOrderDetails =	htmlOrderDetails + 
												'<a href="' + sShoppingCartURL + '" class="cartButton">Bekijk bestelling</a> <a href="' + sOrderPageURL + '" class="continueButton">Afrekenen &raquo;</a>';
	} else {
		htmlOrderDetails =	htmlOrderDetails + 
												'<a href="' + sShoppingCartURL + '" class="continueButton floatLeft" title="Bekijk bestelling">Bekijk bestelling</a> <a href="' + sOrderPageURL + '" class="continueButton floatRight" title="Afrekenen">Afrekenen</a>';
	}

	orderDetails.set('html', htmlOrderDetails);
}


// A function which adds an item to the shopping cart
//
// @aProduct - an array of the details of the item which should be added
function fAddToCart(aProduct) {
	// Use the corresponding settings for the website the user is on
	var idCart = "cartContent", sIconPath = "", aHighlightColours = Array();
	if (!bKathmandu) {
		idCart = "cartOpen";
		sIconPath = "mbt-store/";
		aHighlightColours = ['#af2b55', '#eeeeee'];
	} else {
		aHighlightColours = ['#a99eeb', '#e3e3e3'];
	}


	// If the shopping cart was empty, some controls must be added before adding the item
	// and the <p> element must be deleted
	if (($('cartTotalNr').get('html')) == "0" && !($('orderDetails'))) {
		fAddCartOrderDetails();
		$('cartItems').set('html', '');
	}
	
	// If the shopping cart contents were not already displayed, toggle it
	if ($(idCart).getStyle('display') == 'none') { fToggleCartContent(); }

	// Check whether or not this item was already added to the shopping cart before proceeding
	var cookieExist = Cookie.read('item' + aProduct[0]);
	if (cookieExist != null) {
		// This item has already been added to the visual representation of the shopping cart, so instead of
		// adding it again, just update its visual information for the quantity
		var spanItemNumber = $('item' + aProduct[0] + '_nr');
		var iNewItemNumber = parseInt(aProduct[5]) + parseInt(spanItemNumber.get('html'));
		spanItemNumber.set('html', iNewItemNumber);

		// Copy the new quantity value to the array value which will be written to the cookie
		var iUpdateExistingQuantity = iNewItemNumber;

		// To provide correct feedback for the user, highlight the item of which the quantity just updated
		$('item' + aProduct[0]).highlight(aHighlightColours[0], aHighlightColours[1]);
	} else {
		// Create a DIV container for the item details / controls to display in and highlight it
		var addedItem = new Element("div", {"id": "item" + aProduct[0], "class": "item"}).injectInside($('cartItems'));
		addedItem.highlight(aHighlightColours[0], aHighlightColours[1]);

		// If the item's name is too long, truncate it
		if ((aProduct[1]).length > 16) {
			sCurrName = (aProduct[1]).substring(0, 15) + '...';
		} else {
			sCurrName = aProduct[1];
		}

		// The inner HTML of the item's DIV container
		var htmlItem =	'<div class="left"><img src="' + aProduct[2] + '" width="45" height="45" alt="' + aProduct[1] + '" title="' + aProduct[1] + '" /></div>' + 
										'<div class="right">' + 
											'<span class="name">' + sCurrName + '</span><br/ >' + 
											'<span class="size">' + aProduct[3] + '</span><br />' + 
											'<span class="price">' + aProduct[4] + '</span>' + 
										'</div>' + 
										'<div class="controls">' + 
											'<span id="item' + aProduct[0] + '_nr" class="number">' + aProduct[5] + '</span>' + 
											'<div>' + 
												'<a href="javascript:void(0);" class="plus" title="Meer" onclick="fIncrementItem(' + aProduct[0] + ', \'small\')"><img src="../media/img/' + sIconPath + 'icon/cart-plus.gif" width="11" height="10" alt="Meer" /></a>' + 
												'<a href="javascript:void(0);" class="min" title="Minder" onclick="fDecrementItem(' + aProduct[0] + ', \'small\')"><img src="../media/img/' + sIconPath + 'icon/cart-minus.gif" width="11" height="10" alt="Minder" /></a>' + 
												'<a href="javascript:void(0);" class="del" title="Verwijder" onclick="fRemoveFromCart(' + aProduct[0] + ', \'small\')"><img src="../media/img/icon/cart-delete.gif" width="12" height="12" alt="Verwijder" /></a>' + 
											'</div>' + 
										'</div>';
		addedItem.set('html', htmlItem);
	}

	// Store the correct quantity value to use below; if an already existing item in the
	// shopping cart was added again, the quantity added should be added to the visual
	// representations of the total price and total items, not the quantity added + the
	// already existing amount in the cookie (which would double the actual value instead)
	if (typeof iUpdateExistingQuantity == "undefined") {
		var iItemQuantity = aProduct[5];
	} else {
		var iItemQuantity = iUpdateExistingQuantity;
	}

	// Update the shopping cart total items and price ********************
		// Add this item to the cookie
		var cartCookie = Cookie.write(
			'item' + aProduct[0], 
			'{' + 
				'"id":"' + aProduct[0] + '",' + 
				'"image":"' + aProduct[2] + '",' + 
				'"name":"' + aProduct[1] + '",' + 
				'"size":"' + aProduct[3] + '",' + 
				'"price":"' + (aProduct[4].replace(/,/, '.')).substr(2) + '",' + 
				'"quantity":"' + iItemQuantity + '"' + 
			'}', 
			{duration: 2}
		);

		// Retrieve current values
		var iCurrTotalNr = parseInt($('cartTotalNr').get('html'));
		var iCurrTotalPrice = ($('totalPrice').get('html')).replace(/\./, '');

		// Format the price for calculations and calculate the new price
		iCurrTotalPrice = parseFloat(iCurrTotalPrice.replace(/,/, '.')).toFixed(2);
		var sCurrItemPrice = (aProduct[4]).replace(/,/, '.');
		var iCurrItemPrice = parseFloat(sCurrItemPrice.substr(2)) * parseInt(aProduct[5]);
		var sNewPrice = (parseFloat(iCurrTotalPrice) + parseFloat(iCurrItemPrice)).toFixed(2);

		// Update the values
		$('cartTotalNr').set('html', (iCurrTotalNr + parseInt(aProduct[5])));
		$('totalPrice').set('html', fConvertCurrency(sNewPrice));
	// *******************************************************************
}


// A function which removes an item from the shopping cart
//
// @iProductID - an integer which references the ID of a product to remove
// @sCase - a string which tells the function what type of shopping cart is invoking the function
function fRemoveFromCart(iProductID, sCase) {
	// Start fading the item's container DIV out and when the fade is finished, remove it from the DOM
	$('item' + iProductID).get('tween').start('opacity', 0).chain(function() {
		var oTweenCartHeight = new Fx.Tween($('item' + iProductID));
		oTweenCartHeight.start('height', '0px').chain(function() {
			$('item' + iProductID).parentNode.removeChild($('item' + iProductID));

			// Call the function which checks if this was the last item left in the cart
			fCheckEmptyCart(sCase);
		});
	});

	// Update the shopping cart total items and price ********************
		// Retrieve the cookie values for this item
		var oItem = fGetCookieItem(iProductID);
		
		// Dispose of the cookie which was set for this item
		Cookie.dispose('item' + iProductID);

		// Update the display of the total cost
		var iCurrTotalCost, sNewTotalCost, sOverviewTotalCost, sHTMLelem;
		if (sCase == "small") { sHTMLelem = "totalPrice"; } else if (sCase == "big") { sHTMLelem = "subPrice"; }

		// Retrieve current values
		var iCurrTotalNr = $('cartTotalNr').get('html');
		var iCurrTotalPrice = ($(sHTMLelem).get('html')).replace(/\./, '');

		// Format the price for calculations and calculate the new price
		iCurrTotalPrice = parseFloat(iCurrTotalPrice.replace(/,/, '.')).toFixed(2);
		var iCurrItemPrice = oItem.price * oItem.quantity;
		var sNewPrice = (parseFloat(iCurrTotalPrice) - parseFloat(iCurrItemPrice)).toFixed(2);

		// Calculate the new total amount of items in the order
		var iNewTotalNumber = iCurrTotalNr - oItem.quantity;

		// Update the values
		$('cartTotalNr').set('html', iNewTotalNumber);
		$(sHTMLelem).set('html', fConvertCurrency(sNewPrice));

		if (sCase == "big") {
			// Update the total quantity at the top of the overview
			$('overviewTotalNr').set('html', iNewTotalNumber);

			// Update the shipping cost and total cost of this order
			fUpdOverviewPrices();
		}
	// *******************************************************************
}


// A function which increments the quantity of an item which resides
// in the shopping cart by one and updates shopping cart details
//
// Arguments:
// @iProductID - an integer which references the product to be incremented
// @sCase - a string which tells the function what type of shopping cart is invoking the function
function fIncrementItem(iProductID, sCase) {
	// Retrieve the cookie values for this item
	var oItem = fGetCookieItem(iProductID);
	
	// Retrieve the current quantity values
	var iCurrItemNumber = oItem.quantity;
	var iCurrTotalNumber = parseInt($('cartTotalNr').get('html'));

	// Incrememt quantity values
	var iNewItemNumber = iCurrItemNumber + 1;
	var iNewTotalNumber = iCurrTotalNumber + 1;

	// Display the new quantity values for the user
	$('item' + iProductID + '_nr').set('html', iNewItemNumber);
	$('cartTotalNr').set('html', iNewTotalNumber);


	// Update the display of the total cost
	var iCurrTotalCost, sNewTotalCost, sOverviewTotalCost, sHTMLelem, sSubtotalElem;
	switch (sCase) {
		case "small":
			sHTMLelem = "totalPrice";
			sSubtotalElem = "";
			break;

		case "big":
			sHTMLelem = "subPrice";
			sSubtotalElem = "item" + iProductID + "_subtot";

			// Update the total quantity at the top of the overview
			$('overviewTotalNr').set('html', iNewTotalNumber);
			break;
	}

	if (sSubtotalElem != "") {
		// Update the visual presentation of this product's subtotal price
		var iCurrSubtotal = parseFloat((($(sSubtotalElem).get('html')).replace(/\./, '')).replace(/,/, '.')).toFixed(2);
		var sNewSubtotal = (parseFloat(iCurrSubtotal) + parseFloat(oItem.price)).toFixed(2);
		$(sSubtotalElem).set('html', fConvertCurrency(sNewSubtotal));
	}

	// Retrieve the total price of the order
	iCurrTotalCost = parseFloat((($(sHTMLelem).get('html')).replace(/\./, '')).replace(/,/, '.')).toFixed(2);

	// Set the new cost and display it after re-formatting it
	sNewTotalCost = (parseFloat(iCurrTotalCost) + parseFloat(oItem.price)).toFixed(2);
	sOverviewTotalCost = fConvertCurrency(sNewTotalCost);

	$(sHTMLelem).set('html', sOverviewTotalCost);

	// Update the cookie with the new quantity for this product
	var cartCookie = Cookie.write(
		'item' + iProductID, 
		'{' + 
			'"id":"' + iProductID + '",' + 
			'"image":"' + oItem.image + '",' + 
			'"name":"' + oItem.name + '",' + 
			'"size":"' + oItem.size + '",' + 
			'"price":"' + oItem.price + '",' + 
			'"quantity":"' + iNewItemNumber + '"' + 
		'}', 
		{duration: 2}
	);

	if (sCase == "big") {
		// Update the shipping cost and total cost of this order
		fUpdOverviewPrices();
	}
}


// A function which decrements the quantity of an item which resides
// in the shopping cart by one and updates shopping cart details
//
// Arguments:
// @iProductID - an integer which references the product to be decremented
// @sCase - a string which tells the function what type of shopping cart is invoking the function
function fDecrementItem(iProductID, sCase) {
	// Retrieve the cookie value for this item
	var oItem = fGetCookieItem(iProductID);
	
	// Retrieve the current quantity values
	var iCurrItemNumber = oItem.quantity;
	var iCurrTotalNumber = parseInt($('cartTotalNr').get('html'));

	// Incrememt quantity values
	var iNewItemNumber = iCurrItemNumber - 1;
	var iNewTotalNumber = iCurrTotalNumber - 1;

	// If the new quantity number for the item is above zero, just change
	// the quantity values for the user on the screen
	// Otherwise, this item should be deleted completely from the shopping cart
	if (iNewItemNumber > 0) {
		// Display the new quantity values for the user
		$('item' + iProductID + '_nr').set('html', iNewItemNumber);
		$('cartTotalNr').set('html', iNewTotalNumber);

		// Update the display of the total cost
		var iCurrTotalCost, sNewTotalCost, sOverviewTotalCost, sHTMLelem, sSubtotalElem;
		switch (sCase) {
			case "small":
				sHTMLelem = "totalPrice";
				sSubtotalElem = "";
				break;

			case "big":
				sHTMLelem = "subPrice";
				sSubtotalElem = "item" + iProductID + "_subtot";

				// Update the total quantity at the top of the overview
				$('overviewTotalNr').set('html', iNewTotalNumber);
				break;
		}

		if (sSubtotalElem != "") {
			// Update the visual presentation of this product's subtotal price
			var iCurrSubtotal = parseFloat((($(sSubtotalElem).get('html')).replace(/\./, '')).replace(/,/, '.')).toFixed(2);
			var sNewSubtotal = (parseFloat(iCurrSubtotal) - parseFloat(oItem.price)).toFixed(2);
			$(sSubtotalElem).set('html', fConvertCurrency(sNewSubtotal));
		}
		
		// Retrieve the total price of the order
		iCurrTotalCost = parseFloat((($(sHTMLelem).get('html')).replace(/\./, '')).replace(/,/, '.')).toFixed(2);

		// Set the new cost and display it after re-formatting it
		sNewTotalCost = (parseFloat(iCurrTotalCost) - parseFloat(oItem.price)).toFixed(2);
		sOverviewTotalCost = fConvertCurrency(sNewTotalCost);
		
		$(sHTMLelem).set('html', sOverviewTotalCost);

		// Update the cookie with the new quantity for this product
		var cartCookie = Cookie.write(
			'item' + iProductID, 
			'{' + 
				'"id":"' + iProductID + '",' + 
				'"image":"' + oItem.image + '",' + 
				'"name":"' + oItem.name + '",' + 
				'"size":"' + oItem.size + '",' + 
				'"price":"' + oItem.price + '",' + 
				'"quantity":"' + iNewItemNumber + '"' + 
			'}',
			{duration: 2}
		);

		if (sCase == "big") {
			// Update the shipping cost and total cost of this order
			fUpdOverviewPrices();
		}
	} else {
		// Determine what the cost is of one single instance of this item
		var oItem = fGetCookieItem(iProductID);
		var iItemPrice = oItem.price;
		
		// Invoke the function which will remove this item from the shopping cart entirely
		fRemoveFromCart(iProductID, sCase);
	}
}


// A function which is called whenever the shopping cart overview page is used to
// increment, decrement or remove a product's quantity; the shipping cost is re-calculated
// and the total cost of the order is re-calculated as well
function fUpdOverviewPrices() {
	var iSubtotal = parseFloat((($('subPrice').get('html')).replace(/\./, '')).replace(/,/, '.')).toFixed(2);

	// If the subtotal is larger than 50, leave the shipping cost to
	// be zero, otherwise it should be 3.95
	var iShippingCost = parseFloat(0.00).toFixed(2);
	if (iSubtotal < 50) { iShippingCost = 3.95; }
	$('shippingCost').set('html', fConvertCurrency(iShippingCost));

	// Calculate the total order cost and display it on-screen
	var iTotalCost = (parseFloat(iSubtotal) + parseFloat(iShippingCost)).toFixed(2);
	$('orderPrice').set('html', fConvertCurrency(iTotalCost));
}


// A function which checks whether the cart is empty or not and if so,
// it changes the appearance to supply the user feedback
function fCheckEmptyCart(sCase) {
	// If the shopping cart is now empty, display feedback for the user
	if (($('cartTotalNr').get('html')) == "0") {
		if (sCase == "small") {
			$('cartItems').set('html', '<em>Uw winkelmandje is nog leeg.</em>');
			$('cartContent').removeChild($('orderDetails'));
		} else if (sCase == "big") {
			if (bKathmandu) {
				$$('#productenContent div.content').empty();
				$$('#productenContent div.content').set('html', '<em>Uw winkelmandje is nog leeg.</em>');
			} else {
				$('productsCart').empty();
				$('productsCart').set('html', '<em>Uw winkelmandje is nog leeg.</em>');
			}
		}
	}
}


// A function which returns the values stored of an item in its cookie,
// formatted so that they can be used straight away for this page
//
// Arguments:
// @iProductID - an integer which references the ID of an item stored in the cookie
function fGetCookieItem(iProductID) {
	// Retrieve the cookie value and store its parts into an array
	var cartCookie = Cookie.read('item' + iProductID);
	var oItemDetails = JSON.decode(cartCookie);

	// [0] = id, [1] = image, [2] = name, [3] =  size, [4] = price, [5] = quantity
	// Format the quantity and price values for use in calculations
	oItemDetails.price = parseFloat(oItemDetails.price);
	oItemDetails.quantity = parseInt(oItemDetails.quantity);

	return oItemDetails;
}