// depends on the following...
// jQuery 1.3.2

// topNav jQuery plugin
(function($) {

	$.bhTopNav = $.fn.bhTopNav = function(options) {
		var settings = $.extend({
			childTopPositionSelector: '.spotlightWrapper:eq(0)', 
			childMenuBoundrySelector: '.shellContentWrapper:eq(0)',
			isIe6: false, 
			animate: true,
			positionedNodes: [], 
			mousePosition: { pageX:0, pageY:0 }
		}, options);

		var init = function() {
			if($.browser.msie && $.browser.version<7) { settings.isIe6 = true; };
			if($.browser.opera || $.browser.msie) { settings.animate = false; };
			
			// attach a navRoot reference to all the submenus, then hide the submenus
			$('.topNavRoot').each(function(){
				var oRoot = this;
				oRoot._navRoot = oRoot;
				$('[navParent="'+oRoot.id+'"]').each(function(){ this._navRoot = oRoot; });
			});
			$('[navParent]').hide();
			
			renderUpdates();
			attachEvents();
		};

		var renderUpdates = function() {
			// for each submenu
			$('.navChildWrapper').each(function(){
				var initDisplay = $(this).css('display');
				var iGreatestHeight = 0;
				var aCols = [];
				$(this).css({display:'block'}); // have to turn this on so that width and height work
		
				// update heights of all columns in each row to be the same as the tallest
				$(this).find('.topNavChildColumn').each(function(){
					aCols.push(this);
					var iHeight = $(this).height();
					if(iGreatestHeight<iHeight) { iGreatestHeight = iHeight; };
				});
				for(var i=0; i<aCols.length; i++) {
					var oCol = aCols[i];
					$(oCol).css('height', iGreatestHeight+'px');
				};
		
				// leave it how we found it now that we are done with the box model
				$(this).css('display', initDisplay);

				// fix messed up extra left border since there is limited support for 
				// the :first-child psuedo class
				$(this).find('.topNavChildColumn:first').each(function(){
					$(this).css('border-left', 'none');
				});
			});
			
			// remove bottom border (background-image) from last list item
			if($.browser.msie || $.browser.opera) { // fools don't support the :last-child pseudo selector in CSS so we fix it here
				$('.topNavChildColumn').each(function(){
					$(this).find('.topNavItem:last').css('background','none');
				});
			};
		};
		
		var attachEvents = function() {
			// window resize requires repositiong of child nav elements
			$(window).resize(function(){
				settings.positionedNodes = [];
			});
			
			// folow the mouse so we can test when it is over an element
			//$(document).mouseMove(function(e){
			//	settings.mousePosition.pageX = e.pageX;
			//	settings.mousePosition.pageY = e.pageY;
			//});
			
			// attach events
			$('.topNavRoot').hover(function(){
				this._isMouseOver = true;
				showChildren(this);
			}, function(){
				this._isMouseOver = false;
				//setTimeout(function() {
					hideChildren(this);
				//}, 1);
			});
			$('[navParent]').hover(function(){
				this._isMouseOver = true;
			}, function(){
				this._isMouseOver = false;
				//setTimeout(function() {
					hideChildren(this);
				//}, 1);
			});
			$('[navParent]').each(function(){ // hide on click
				var oParent = this;
				$(this).find('a').click(function(){
					oParent._isMouseOver = false;
					hideChildren(oParent);
				});
			});
		};
		
		var showChildren = function(o) { // expects a root element
			// make the root display as on
			toggleRootItemHighlight(o); // want the curves to render before the menu
			setTimeout(function() { toggleRootItemHighlight(o); }, 1); // fix for the curves dissapearing bug

			setTimeout(function() {
				var oChildWrapper = $('[navParent="'+o.id+'"]').get(0);

				if(isDefined(oChildWrapper)) {
					// have to show it first so we can determine dimensions
					$(oChildWrapper).show();
					
					// position the child menu if it hasn't already been positioned
					if($.inArray(oChildWrapper, settings.positionedNodes) == -1) {
						// add it to the array of positioned children
						settings.positionedNodes.push(oChildWrapper);

						// set the correct width for IE 6 and 7
						if(settings.isIe6 || ($.browser.msie && $.browser.version <= 8)) {
							$(oChildWrapper).each(function(){
								var oContainer = this;
								var iWidth = 0;
								$(oContainer).find('.topNavChildColumn').each(function(){
									iWidth += $(this).outerWidth();
								});
								$(oContainer).css('width', iWidth+'px');
							});
						};
						
						// position the child from the top if a selector is present
						var oTopPosition = $(settings.childTopPositionSelector);
						if(settings.childTopPositionSelector!='' && isDefined(oTopPosition)) {
							var iTop = $(oTopPosition).offset().top;
							$(oChildWrapper).css('top', iTop+'px');
						};
						
						// try to center the submenu below the navRoot
						// but make it fit within the page boundries
						var iNavRootLeft = $(o).offset().left;
						var iNavRootWidth = $(o).outerWidth();
						var iNavRootCenter = Math.round(iNavRootWidth / 2);
						var iBoundryLeft = $(settings.childMenuBoundrySelector).offset().left;
						var iBoundryWidth = $(settings.childMenuBoundrySelector).outerWidth();
						var iBoundryCenter = Math.round(iBoundryWidth / 2);
						$(oChildWrapper).each(function(){
							var oChild = this;
							var iChildLeft = $(oChild).offset().left;
							var iChildWidth = $(oChild).outerWidth();
							var iChildCenter = Math.round(iChildWidth / 2);
							
							// begin by centering the child menu below its nav root
							$(oChild).css('left', Math.round(iNavRootLeft+iNavRootCenter-iChildCenter)+'px');

							// check for menus out of boundaries
							var bOverlapsLeft = ((iNavRootLeft+iNavRootCenter-iChildCenter) < iBoundryLeft);
							var bOverlapsRight = ((iNavRootLeft+iNavRootCenter+iChildCenter) > (iBoundryLeft+iBoundryWidth));
							
							// if it overlaps the left side make it fit
							if(bOverlapsLeft) {
								$(oChild).css('left', Math.round(iBoundryLeft)+'px');
							};
							
							// if it overlaps the right side make it fit
							if(bOverlapsRight && !bOverlapsLeft) {
								$(oChild).css('left', Math.round(iBoundryLeft+iBoundryWidth-iChildWidth)+'px');
							};
						});
					}
				}
				
				// use bgIframe if it is present for the sake of stupid IE
				if(typeof($.fn.bgIframe)!='undefined') { $(oChildWrapper).bgIframe(); };
			}, 2);
		};
		
		var hideChildren = function(o) { // expects a root or child element
			// we use timeouts so that the menu has a chance to render before executing actions here
			if($('[navParent="'+o._navRoot.id+'"]').length>0) {
				setTimeout(function(){ 
					var oChild = $('[navParent='+o._navRoot.id+']').get(0);
					if(!o._navRoot._isMouseOver && !oChild._isMouseOver) {
						if(settings.animate) {
							$(oChild).animate({height:'hide', opacity:'hide'}, 150);
						}
						else { $(oChild).hide(); }; // no animation for laymo IE 6 or busted Opera
					};
				}, 1);
			};
			setTimeout(function() { toggleRootItemHighlight(o); }, 1);
		};
		
		var isMouseOverMenu = function(o) { // expects a root or a child element
			var bIsMouseOverChild = false;
						
			// check the passed in object first
			if(o._isMouseOver) { return true; };
			
			// only do one level for now
			$('[navParent="'+o._navRoot.id+'"]').each(function(){
				if(this._isMouseOver || this._navRoot._isMouseOver) { 
					bIsMouseOverChild = true; 
					return false; // break the each loop
				};
			});
			
			return bIsMouseOverChild
		};
		
		var toggleRootItemHighlight = function(o) {
			setTimeout(function() {
				if(isMouseOverMenu(o)) {				
					// show highlight
					$('.topNavRoot').removeClass('topNavRootHover');
					$(o._navRoot).addClass('topNavRootHover');
					$(o._navRoot).find('a').addClass('topNavRootHover');
					
					// show inverted curves
					//if(!settings.isIe6) {
						$('.topNavRoot .curve_l').hide();
						$('.topNavRoot .curve_r').hide();
						$(o._navRoot).find('.curve_l').show();
						$(o._navRoot).find('.curve_r').show();
					//};
				}
				else {
					// hide highlight
					$(o._navRoot).removeClass('topNavRootHover');
					$(o._navRoot).find('a').removeClass('topNavRootHover');
	
					// hide inverted curves
					//if(!settings.isIe6) {
						$(o._navRoot).find('.curve_l').hide();
						$(o._navRoot).find('.curve_r').hide();
					//};
				};
			}, 1);
		};

		// everything is defined so run it
		init();

		return $;
	};
	
})(jQuery);
