window.addEvent('domready', function() {
	var Navigation = {};
	Navigation.activeContainer = null;
	Navigation.activeMenuEntry = null;
	Navigation.waitTimer = null;
	Navigation.initUrl = window.location.href;
	Navigation.homeUrl = $$('#home ul li a')[0].get('href') || '';
	Navigation.activate = function(newMenuEntry, oldMenuEntry) {
		if (oldMenuEntry) {
			oldMenuEntry.removeClass('active').removeClass('trail');
			oldMenuEntry.getChildren('a').removeClass('active').removeClass('trail');
		}
		if (newMenuEntry) {
			newMenuEntry.addClass('active');
			newMenuEntry.getChildren('a').addClass('active');
		}
	};
	Navigation.fetch = function(url, noHistory) {
		// Show waiting panel if loading takes more than 1 sec
		if (!Navigation.waitTimer) {
			Navigation.waitTimer = window.setTimeout(function() {
				$$('body .waiting').setStyle('display', 'none').dispose();
				var wait = new Element('div', {'class': 'waiting', 'html': '<span class="text"></span>'});
				wait.inject($('wrapper'), 'before');
			}, 1000);
		}
		
		var request = new Request.HTML({
			url: url,
			evalScripts: false,
			onSuccess: Navigation.load
		})
		request.send();
		
		if (!noHistory) {
			if (window.history && window.history.pushState) {
				window.history.pushState(url, '', url);
			} else if (Navigation.hashListener) {
	  			Navigation.hashListener.updateHash(url);
			}
		}
	};
	Navigation.load = function(responseTree, responseElements, responseHTML, responseJavaScript) {
		if (Navigation.waitTimer) {
			window.clearTimeout(Navigation.waitTimer);
		}
		$$('body .waiting').setStyle('display', 'none').dispose();
		
		var title = responseHTML.match(/<title>([^<]+)<\/title>/im);
		if (title && title.length > 0) {
			$$('title').set('html', title[1]);
		}
		
		var container = null;
		var menuEntry = null;

		var mainMenu = responseElements.filter('#menu')[0];
		var inMainMenu = -1;
		mainMenu.getElements('ul.level_1 > li').each(function(item, position) {
			if (item.hasClass('trail') || item.hasClass('active')) {
				inMainMenu = position;
			}
		});
		if (inMainMenu >= 0) {
			menuEntry = $$('#menu > ul.level_1 > li')[inMainMenu];
			container = menuEntry.getElement('.main');
		} else {
			var footerMenu = responseElements.filter('#footer')[0];
			var inFooterMenu = -1;
			footerMenu.getElements('a.link').each(function(item, position) {
				if (item.hasClass('trail') || item.hasClass('active')) {
					menuEntry = item;
					inFooterMenu = position;
				}
			});
			if (inFooterMenu >= 0) {
				menuEntry = $$('#footer a.link')[inFooterMenu];
				container = $('footer').getElement('.main');
			}
		}
		
		/*if (!container) {
			window.location = window.location;
		}*/

		if (Navigation.activeContainer == container) {
			Navigation.activate(menuEntry, Navigation.activeMenuEntry);
			Navigation.activeContainer = container;
			Navigation.activeMenuEntry = menuEntry;
			Navigation.finalize(responseElements, responseJavaScript);
		} else {
			var slideInCallback = function(element) {
				var scroll = new Fx.Scroll(window);
				scroll.toElement(Navigation.activeContainer.getParent('li') || Navigation.activeContainer.getParent('#footer'));
			};
			if (Navigation.activeContainer) {
				var slideOut = new Fx.Slide(Navigation.activeContainer.getParent('.mainAccordion'), {
					onComplete: (function(oldContainer, newContainer, newMenuEntry, elements, javaScript) {
						return function() {
							Navigation.activeContainer = newContainer;
							Navigation.activeMenuEntry = newMenuEntry;
							if (newContainer) {
								Navigation.activate(Navigation.activeMenuEntry, null);
								Navigation.finalize(elements, javaScript);
								var slideIn = new Fx.Slide(Navigation.activeContainer.getParent('.mainAccordion'), {
									resetHeight: true,
									onComplete: slideInCallback
								});
								slideIn.slideIn();
							}
							oldContainer.empty();
						}
					})(Navigation.activeContainer, container, menuEntry, responseElements, responseJavaScript)
				});
				slideOut.slideOut();
				Navigation.activate(null, Navigation.activeMenuEntry)
			} else {
				Navigation.activeContainer = container;
				Navigation.activeMenuEntry = menuEntry;
				if (container) {
					Navigation.activate(Navigation.activeMenuEntry, null)
					Navigation.finalize(responseElements, responseJavaScript);
					var slideIn = new Fx.Slide(Navigation.activeContainer.getParent('.mainAccordion'), {
						resetHeight: true,
						onComplete: slideInCallback
					});
					slideIn.slideIn();
				}
			}
		}
	};
	Navigation.finalize = function(responseElements, responseJavaScript) {
		if (!Navigation.activeContainer) return;

		var content = responseElements.filter('#container');
		
		Navigation.activeContainer.empty();
		content.inject(Navigation.activeContainer);

		Navigation.activeContainer.set('class', 'main ' + responseElements.filter('#wrapper').get('class'));
		
		Navigation.activeContainer.getElements('a').each(function(link) {
			link.addEvent('click', function(event) {
				var href = this.get('href');
				var base = $$('base')[0].get('href');
				if ((!href.match(/(\w+\:\/\/)/) || href.substr(0, Math.min(base.length, href.length)) == base) && href.match(/\.html/) && !href.match(/file=/i)) {
					Navigation.fetch(href);
					event.stop();
				}
			});
		});

		// Salespoints loaded dynamically
		Navigation.activeContainer.getElements('.mod_salespointstree select')
			.set('onchange', '')
			.addEvent('change', function(event) {
				var select = this;
				Navigation.fetch(select.get('value'));
				event.stop();
			});

		// Execute Javascript chunks and re-fire Mediabox auto scan
		var jsChunks = responseJavaScript.replace(/\/\/--><!\]\]>/img, '').split(/<!\-\-\/\/\-\-><!\[CDATA\[\/\/><!\-\-/img);
		for (var c = 0; c < jsChunks.length - 1; c++) {
			eval(jsChunks[c]);
		}
		Mediabox.scanPage();
	};

	if (window.history && window.history.pushState) {
		window.onpopstate = function(event) {
			Navigation.fetch(window.location.href || event.state || Navigation.initUrl, true);
		};
	} else {
		if (HashListener) {
			Navigation.hashListener = new HashListener();
			Navigation.hashListener.addEvent('hashChanged', function(url) {
				Navigation.fetch(url || Navigation.initUrl, true);
			});
	    	Navigation.hashListener.start();
		}
	}

	// Main menu actions
	$$('#menu ul.level_1 > li').each(function(mainMenuItem) {
		// Init each main menu item with a accordion container
		var accordionContainer = new Element('div', {'class': 'mainAccordion'});
		level1Container = new Element('div', {'class': 'main'});
		level1Container.inject(accordionContainer);
		accordionContainer.inject(mainMenuItem);

		if (mainMenuItem.hasClass('trail') || mainMenuItem.hasClass('active')) {
			// Move the content of the page from the #container to the right accordion container
			Navigation.activeMenuEntry = mainMenuItem;
			Navigation.activeContainer = level1Container;
			Navigation.finalize($$('#wrapper', '#container'), '');
			$$('body,#wrapper').removeClass('twocol');
		} else {
			accordionContainer.slide('hide');
		}
	
		mainMenuItem.getChildren('a').addEvent('click', function(event) {
			var link = this;
			var href = link.get('href');
			if (!href.match(/(\w+\:\/\/)/)) {
				if (Navigation.activeMenuEntry == link.getParent('li')) {
					// Slide out
					Navigation.fetch(Navigation.homeUrl);
				} else {
					// Fetch URL
					Navigation.fetch(href);
				}
				event.stop();
			}
		});
	});
	

	// Footer menu actions
	var footerAccordionContainer = new Element('div', {'class': 'mainAccordion'});
	footerContainer = new Element('div', {'class': 'main'});
	footerContainer.inject(footerAccordionContainer);
	footerAccordionContainer.inject($('footer'));
	
	var inFooter = false;
	$('footer').getElements('a.link').each(function(footerMenuLink) {
		if (footerMenuLink.hasClass('trail') || footerMenuLink.hasClass('active')) {
			// Move the content of the page from the #container to the right accordion container
			Navigation.activeMenuEntry = footerMenuLink;
			Navigation.activeContainer = footerContainer;
			Navigation.finalize($$('#wrapper', '#container'), '');
			$$('body,#wrapper').removeClass('twocol');
			
			inFooter = true;
		}
	
		footerMenuLink.addEvent('click', function(event) {
			var link = this;
			var href = link.get('href');
			if (!href.match(/(\w+\:\/\/)/)) {
				if (Navigation.activeMenuEntry == link) {
					// Slide out
					Navigation.fetch(Navigation.homeUrl);
				} else {
					// Fetch URL
					Navigation.fetch(href);
				}
				event.stop();
			}
		});
	});
	if (!inFooter) {
		footerAccordionContainer.slide('hide');
	}
});

