// A function which retrieves all of the cookies set by this website and returns an 
// array of URL decoded cookies which are prefixed with 'item'
//
// NOTE: this function has been placed here on purpose so that it can also be accessed on pages
// where it is not possible to expand the shopping cart (meaning cart.js is not included)
function fGetItemCookies() {
	// Retrieve all of the cookies the user has which are assigned to this website
	// and put each one separately into an array
	var cookies = document.cookie;
	var aCookies = cookies.split('; ');

	var aItemCookies = new Array();
	for (iCnt = 0; iCnt < aCookies.length; iCnt++) {
		// Only copy cookies of which the name is prefixed by 'item'
		if (aCookies[iCnt].substr(0, 4) == "item") {
			// Get rid of the cookie name so that only the JSON string remains and decode 
			// the JSON string to remove its ASCII hex values (e.g. "%7B" will become "{")
			var aTemp = aCookies[iCnt].split('=');
			aItemCookies[iCnt] = fUrlDecode(aTemp[1]);
		}
	}

	// Return the array of JSON-formatted strings
	return aItemCookies;
}


// A function which receives a US-formatted currency amount (e.g. 1725.95) and
// converts it to European format for displaying on-screen (e.g. 1.725,95)
//
// Arguments:
// @iAmount - an integer which is a currency amount in US formatting
function fConvertCurrency(iCost) {
	// Store the euros and cents separate from each other in an array
	var aAmount = (iCost.toString()).split(".");

	// If the amount is at least a thousand euro, start to iterate through each digit
	var sFormattedAmount = "";
	if (aAmount[0].length > 3) {
		for (iCnt = 0; iCnt < aAmount[0].length; iCnt++) {
			// Add this digit to the formatted amount string
			sFormattedAmount = sFormattedAmount + "" + aAmount[0].charAt(iCnt);

			// If this iteration is a multiplier of 3 and not the final digit, insert a grouping period character
			if (((aAmount[0].length - (iCnt + 1)) % 3 == 0) && ((iCnt + 1) != aAmount[0].length)) {
				sFormattedAmount = sFormattedAmount + ".";
			}
		}

		// After iterating through all the digits, the cents need to be concatenated to the amount
		sFormattedAmount = sFormattedAmount + "," + aAmount[1];
	} else {
		// As the amount is no more than 999, just concatenate the euros and cents together
		sFormattedAmount = aAmount[0] + "," + aAmount[1];
	}

	return sFormattedAmount;
}


window.addEvent('domready', function() {
	// When the user hovers over a mainnav menu item which has a submenu, display it
	$$('.noPointer').addEvent('mouseover', function() {
		// Extract the numeric part of the ID of the hyperlink which envoked this function
		var iLinkID = this.id.substring(1);

		// Only attempt to display a submenu if it is actually in the DOM
		if ($('submenu' + iLinkID)) {
			// Use the ID to display the submenu which uses the same numeric ID
			$('submenu' + iLinkID).setStyle('display', 'block');
		}
	});
	// When the user leaves a mainnav menu item which has a submenu, hide it
	$$('.noPointer').addEvent('mouseout', function() {
		// Extract the numeric part of the ID of the hyperlink which envoked this function
		var iLinkID = this.id.substring(1);

		// Only attempt to hide a submenu if it is actually in the DOM
		if ($('submenu' + iLinkID)) {
			// Use the ID to display the submenu which uses the same numeric ID
			$('submenu' + iLinkID).setStyle('display', 'none');
		}
	});
	// When the is hovering over a submenu item, keep it visible
	$$('.level1').addEvent('mouseover', function() {
		this.setStyle('display', 'block');
	});
	// When the user leaves a submenu item, hide it
	$$('.level1').addEvent('mouseout', function() {
		this.setStyle('display', 'none');
	});


	// Handle mouseovers for the submenu items
	$$('.level1')[0].set('class', 'level1 submenu1');
	$$('.level1')[1].set('class', 'level1 submenu2');

		
	// Set the background-image for the first footernav menu item to not display
	var aFooterMenuLIs = $('footernav').getElements('li');
	aFooterMenuLIs[0].className = "first";
	
	// Check if the current page displays the stores accordion menu
	if ($('storesAccordion')) {
		// Iterate through all of the accordion's togglers and attach mousehover events to all of them
		var aAccLinks = $('storesAccordion').getElements('p.toggler');
		for (iCnt = 0; iCnt < aAccLinks.length; iCnt++) {
			
			// When the mouse is moved over a toggler, change its background colour
			// and its font colour
			aAccLinks[iCnt].addEvent('mouseover', function() {
				this.setStyles({
					backgroundColor: '#3333ff',
					color: '#ffffff'
				});
			});

			// When the mouse leaves a toggler, change back its background color
			// and its font colour to represent a static state
			aAccLinks[iCnt].addEvent('mouseout', function() {
				// Only change the state back if the toggler's cursor style is set to "pointer",
				// which occurs when a toggler's element becomes active
				if (this.getStyle('cursor') == 'pointer') {
					this.setStyles({
						backgroundColor: '#d4d4d4',
						color: '#2b2b2b'
					});
				}
			});
		}
	}


	// Check if the current page is a product detail page which has more
	// results to show in a JS slider before attempting to create one
	if ($('relatedProducts')) {
		new SlideItMoo({
			overallContainer: 'prContainer',
			elementScrolled: 'prSlider',
			thumbsContainer: 'prItems',
			itemsVisible: 4,
			itemsSelector: '.prElement',
			itemWidth: 104,
			duration: 300,
			showControls: 1
		});
	}


	// Check if the products pagemenu is present on the page
	if ($('pmenuBottom')) {
		// Copy the products pagemenu to display it at the top of the page as well
		var oPageMenu = $('pmenuBottom').cloneNode(true);
		oPageMenu.setAttribute('id', 'pmenuTop');
		oPageMenu.injectBefore($('page0').parentNode);

		// Catch clicks on the (top) page number anchor elements to make the correct numbers active or not
		$$('#pmenuTop ul.pagemenu li a').addEvent('click', function() {
			// First set all of the anchor elements in the pagemenu to appear inactive
			// so that the previous active item will be reset for sure
			$$('#pmenuTop ul.pagemenu li a').set('class', '');
			$$('#pmenuTop ul.pagemenu li a').className = '';
			$$('#pmenuBottom ul.pagemenu li a').set('class', '');
			$$('#pmenuBottom ul.pagemenu li a').className = '';

			var pmenuTopA = $('pmenuTop').getElements('a');
			var pmenuBottomA = $('pmenuBottom').getElements('a');

			for (iCnt = 0; iCnt < pmenuTopA.length; iCnt++) {
				// Look for anchor elements which share the same value for the onclick attribute
				// as the one which was clicked on - these should also appear active onscreen
				if (this.onclick == pmenuTopA[iCnt].onclick) {
					pmenuTopA[iCnt].setAttribute('class', 'active');
					pmenuTopA[iCnt].className = "active";

					pmenuBottomA[iCnt].setAttribute('class', 'active');
					pmenuBottomA[iCnt].className = "active";
				}
			}
		});

		// Catch clicks on the (bottom) page number anchor elements to make the correct numbers active or not
		$$('#pmenuBottom ul.pagemenu li a').addEvent('click', function() {
			// First set all of the anchor elements in the pagemenu to appear inactive
			// so that the previous active item will be reset for sure
			$$('#pmenuTop ul.pagemenu li a').set('class', '');
			$$('#pmenuTop ul.pagemenu li a').className = '';
			$$('#pmenuBottom ul.pagemenu li a').set('class', '');
			$$('#pmenuBottom ul.pagemenu li a').className = '';

			var pmenuTopA = $('pmenuTop').getElements('a');
			var pmenuBottomA = $('pmenuBottom').getElements('a');

			for (iCnt = 0; iCnt < pmenuBottomA.length; iCnt++) {
				// Look for anchor elements which share the same value for the onclick attribute
				// as the one which was clicked on - these should also appear active onscreen
				if (this.onclick == pmenuBottomA[iCnt].onclick) {
					pmenuBottomA[iCnt].setAttribute('class', 'active');
					pmenuBottomA[iCnt].className = "active";
					
					pmenuTopA[iCnt].setAttribute('class', 'active');
					pmenuTopA[iCnt].className = "active";
				}
			}
		});
	}


	// Handling actions for the shopping cart
	if ($('cartContent')) {
		// Make clicking the "toon" anchor element lead to the shopping cart content
		// DIV being toggled open and shut
		$('showCart').addEvent('click', fToggleCartContent);

		// Call the function which will initialise the shopping cart (if the user has
		// items stored in a cookie, they will be loaded into the corresponding DIV)
		fInitCart();
	} else {
		if ($('showCart')) {
			// There is no shopping cart content DIV on this page, so change the "toon"
			// anchor element's HREF attribute to lead to the main shopping cart page
			$('showCart').setAttribute('href', sShoppingCartURL);

			// Visual representation of total quantity of order ******************************
				// Retrieve the total quantity of this user's order
				var aItemCookies = fGetItemCookies();

				// Declare and initialize a variable for the total quantity of the order
				// If the conditional statement below returns false, this will remain zero
				var iTotalNumber = 0;
				
				if (aItemCookies.length > 0) {
					// Iterate through the array of JSON-formatted strings and add the quantity of
					// each item to the total quantity of this order
					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
						iTotalNumber = iTotalNumber + parseInt(oItem.quantity);
					}
				}

				$('cartTotalNr').set('html', iTotalNumber);
			// *******************************************************************************
		}
	}
});