// TODO: The selected menu item jumps back without animation when switching to a different menu item after switching the language
// TODO: Replace CSS expression with equivalent JavaScript Code for IE8 standards mode.

window.addEvent('domready', function(){
	
	var MARGIN_LEFT = 235;
	var MARGIN_RIGHT = 135;

	function uriToMenuTitle(uri, level) {
		
		/**
			^	: Match the beginning of a string.
			\/	: A literal /.
			+	: Match one or more occurences of the previous item.
			|	: Mmatch either subexpression to the left or the subexpression to the right.
			$	: Match the end of a string.
			g	: Perform a global match.
		*/
		var TRIM_PATH_SEPARATORS = /^\/+|\/+$/g;
		var TRIM_LANGUAGES = /^en\/|^de\//;
		var PATH_SEPARATOR = '/';

		var menuTitle = ''
		if (uri != null && uri != PATH_SEPARATOR) {
			var pagePath = uri.replace(TRIM_PATH_SEPARATORS, '');  // Remove leading and trailing page-separators from URI.
			pagePath = pagePath.replace(TRIM_LANGUAGES, '');  // Remove languages (if any) from URI.
			pagePath = pagePath.split(PATH_SEPARATOR);
			menuTitle = (pagePath.length < level) ? '' : pagePath[level];
		}
		
		return menuTitle;  // Returns the menu title as string.
	}

	var currentURI = new URI(document.location).get('directory');
	var currentMenuTitle = uriToMenuTitle(currentURI, 0);  //  Get first menu level from URIs.
	
	var referrerURI = new URI(document.referrer).get('directory');
	var referrerMenuTitle = uriToMenuTitle(referrerURI, 0);  //  Get first menu level from URIs.

	//alert(referrerMenuTitle + "->" + currentMenuTitle)
	
	// Slide current menu item out.
	var currentMenuItem = $$('div#global_navigation ul li b');
	if (currentMenuItem.length > 0  /* Is there any menu item currently selected? */
			&& currentMenuTitle != '' /* and was not only the language switched? */
			&& currentMenuTitle != referrerMenuTitle) { /* or any nested menu item? */

		currentMenuItem = currentMenuItem[0];
		var currentMenuItemWidth = currentMenuItem.getSize().x;
		
		currentMenuItem.setStyles({ 'margin-left': MARGIN_LEFT - currentMenuItemWidth + 'px' });
		currentMenuItem.morph({ 'margin-left': MARGIN_LEFT + 'px' });
	}


	// Slide referring menu item in.
	var otherMenuItems = $$('div#global_navigation ul li a');
	otherMenuItems.each(
		
		function(otherMenuItem, index) {
			
			var otherMenuItemURI = new URI(otherMenuItem.get('href')).get('directory');
			var otherMenuTitle = uriToMenuTitle(otherMenuItemURI, 0);
			
			if (otherMenuTitle == referrerMenuTitle) {

				var otherMenuItemWidth = otherMenuItem.getSize().x;
				if (Browser.Engine.trident) { otherMenuItemWidth -= MARGIN_RIGHT; } // FIX: Internet Explorer is returning a wrong width value.

				otherMenuItem.setStyles({ 'margin-right': MARGIN_RIGHT - otherMenuItemWidth + 'px' });
				otherMenuItem.morph({ 'margin-right': MARGIN_RIGHT + 'px' });
			}
		}
	);
});
