window.addEvent("domready", function() {
	$(document.body).removeClass("cssanim");
	
	// Start up search box.
	(function() {
		var search = $E("#top-header .search-box");
		var initial = search.value;
		if (!search) {
			return;
		}
		
		search.addEvent('focus', function() {
			if (search.value == initial) {
				search.value = "";
				search.addClass("active");
			}
		});
		search.addEvent('blur', function() {
			search.value = initial;
			search.removeClass("active");
		});
	})();
	
	// Start up javascript menu.
	(function() {
		var mouseOutCloseDelay = 1000;
		
		function closeTree(root) {
			var all = $ES("ul", root);
			for (var i=all.length-1; i>=0; i--) {
				all[i].setStyle("display", "none");
			};
		}
		
		function closeSiblings(self) {
			self.parentNode.getChildren().each(function(child) {
				if (child !== self && child.tagName === "LI") {
					closeTree(child);
				}
			});
		}
		
		// Stores the delayed close event. Will be cancelled if mouse
		// re-enters the menu before it closes.
		var closeEvent;
		var offsetEl = $("page-header");
		
		var products = {};
		
		$$("#navigation-bot li").each(function(li) {
			var ul = $E("ul", li);
			
			// Now onto the actual dropdown menu code.
			li.addEvent("mouseover", function(e) {
				var e = new Event(e);
				e.stop();
				
				$clear(closeEvent);
				
				closeSiblings(li);
				
				if (ul) {
					ul.setStyle("display", "block");
					
					var pos = ul.getPosition();
					var oePos = offsetEl.getCoordinates();
					
					if (pos.x-oePos.left+140 > oePos.width) {
						// Open to the left if it would go past the end of the screen.
						ul.setStyles({
							left: "-138px",
							top: "4px",
							width: "140px"
						});
					}
				}
			});
		});
		
		// Exiting the menu entirely it treated as a special case with
		// a delay.
		var menu = $E("#navigation-bot .menu");
		var rootUL = $E("#navigation-bot ul");
		
		if (!menu) {
			return;
		}
		
		menu.addEvent("mouseout", function(e) {
			var e = new Event(e);
			
			if (!menu.hasChild(e.relatedTarget)) {
				closeEvent = (function() {
					closeTree(rootUL);
				}).delay(mouseOutCloseDelay);
			}
		});
	})();
	
	// Start up language selector.
	(function() {
		var lang = $("langSelect");
		
		lang.addEvent("change", function() {
			lang.form.submit();
		});
	})();
});

