(function($) {
	var menuTimeout;
	var menuFadeoutTime = 650; // in miliseconds

	$.fn.SetupMenu = function() {
		$('#mainnav_sleeve>ul>li>div>ul>li>a').bind('mouseover', {focused:false}, showMenu)
											  .bind('focus', {focused:true}, showMenu);
		$('#mainnav_sleeve>ul>li>div>ul>li').bind('mouseleave', {focused:false}, hideMenu);
	}

	function showMenu(event) {
		if($('#mainnav .over').length > 0) {
			clearTimeout(menuTimeout);
			$('#mainnav_sleeve>ul>li>div>ul>li').removeClass('over').children('div').css({left:'-9999px', zIndex:'99'});
		}

		// add class of over
		$(this.parentNode).addClass('over');

		// stop menu going off screen and bring into focus
		if($(this.parentNode).children('div').length > 0) {
			if ($.browser.msie && $.browser.version < 7) $(this.parentNode).children('div').bgiframe();
			
			$(this.parentNode).children('div').css({left:'auto', zIndex:'100'});

			var wrapperWidth = $('#wrapper').get(0).offsetWidth;
			var wrapperOffset = $('#wrapper').offset();
			var dropdownWidth = $(this.parentNode).children('div').get(0).offsetWidth;
			var dropdownOffset = $(this.parentNode).children('div').offset();

			// move drop down menu if running off of screen
			if((dropdownWidth + dropdownOffset.left) > (wrapperOffset.left + wrapperWidth)) {
				$(this.parentNode).children('div').css({marginLeft:'-'+((dropdownWidth + dropdownOffset.left)
														   -(wrapperOffset.left + (wrapperWidth-parseInt($('#wrapper').css('padding-left')))))
														   +'px'});
			}
		}
	}

	function hideMenu(event) {
		if(!event.data.focused) {
			var menuItem = this;

			// if menu item has drop down then set a timeout else just remove over class
			if($(menuItem).children('div').length > 0) {
				menuTimeout = setTimeout(function() {
					$(menuItem).removeClass('over').children('div').css({left:'-9999px', zIndex:'99'});
				}, menuFadeoutTime);
			} else {
				$(menuItem).removeClass('over');
			}
		}
	}
})(jQuery);
