

jQuery(document).ready(function(){

	jQuery('ul#topNavMain li:last').addClass('navLast');
	
	var masthead = jQuery('#masthead');
	var navContainer = jQuery('#topNavContainer');
	var mNav = jQuery('ul#topNavMain');
	var tNav = jQuery('li#mainNavOn');
	var sNav = jQuery('ul#subNavOn');
	var ie6Padding = 0;
	
	var mastheadShortHeight = 120;
	var halfOfBgWidth = 23; // half the width of the "on" background image
	var mainPaddingDifference = 18; // amount of offset required to negate padding on right side of last main nav item
	var subPaddingDifference = 8; // difference between left padding on the main nav and left padding on the subnav
	
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 ) {
		ie6Padding = 20;
	}
	
	
	if ( sNav.is(':empty') ) {
		masthead.height(mastheadShortHeight);
		
		if (tNav.length != 0) {
			sNav.animate({ top: -1000 }, 0);
		
			sNav.animate({
				top: -1000
			}, 200, function(){
				navContainer.width( Math.floor(mNav.width() - mainPaddingDifference) + 1 + ie6Padding);
				var centerOfTopNavItemWithoutSubnav = Math.floor(tNav.position().left + ( tNav.width() / 2 ) );
				mNav.css( {backgroundPosition: (centerOfTopNavItemWithoutSubnav - halfOfBgWidth) + "px 0" } );
			});
		}
			
	} else {
	
		sNav.animate({ top: -1000 }, 0);
	
		sNav.animate({
			top: -1000
		}, 200, function(){
		
			if (tNav.length != 0) {
			
				navContainer.width( Math.floor(mNav.width() - mainPaddingDifference) + 1 + ie6Padding);
				var centerOfTopNavItem = Math.floor(tNav.position().left + ( tNav.width() / 2 ) );
				var offsetOfSubNav = (centerOfTopNavItem - Math.floor( sNav.width() / 2 )) + ie6Padding;
		
				if (offsetOfSubNav < subPaddingDifference) {
					// main nav item is too far left for subnav to be centered
					sNav.css('left', (subPaddingDifference + ie6Padding));
				} else {
				
					if ( (offsetOfSubNav + sNav.width() ) > mNav.width() ) {
						// subnav is too wide to be positioned by its left side
						sNav.css('right', (0 - subPaddingDifference) );
						//while (sNav.height() > 30) {
						//	sNav.width( sNav.width() + 5 );
						//}
					} else {
						// default positioning
						sNav.css('left', offsetOfSubNav);
					}
				
				}
				sNav.animate({ top: 90 }, 0);
				
				mNav.css( {backgroundPosition: (centerOfTopNavItem - halfOfBgWidth) + "px 0" } );
			
			}
			
			
		});
	}
	
});