/*global $, pngfix */
$(function () {
	var div, ul, li, getInt, getVPad, getHPad, alphaFilter, ie, ie6;
	
	getInt = function (number) {
		return parseInt(number, 10) || 0;
	};
	
	getVPad = function (element) {
		return getInt(element.css('padding-top')) + getInt(element.css('padding-bottom'));
	};

	getHPad = function (element) {
		return getInt(element.css('padding-left')) + getInt(element.css('padding-right'));
	};

	// Parse the URL out of a css background property and build an alphaImageLoader filter.
	alphaFilter = function (css, sizing) {
		var url;
		url = css.replace(/^url\("(.+?)"\)$/gi, '$1');
		return 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + url + ',sizingMethod=' + sizing + ')';
	};
	
	// For all the lovely hacks.
	ie = $.browser.msie;
	ie6 = ie && getInt($.browser.version) < 7;

	// Grab some elements we'll need repeatedly.
	div = $('.header-nav-subnav');
	ul = $('#header-nav li ul');
	li = $('#header-nav li li');

	// Flag the top-level nav elements that don't have subnavs.
	$('#header-nav li').addClass('header-nav-no-subnav');
	div.each(function () {
		$(this).parent().removeClass('header-nav-no-subnav');
	});
	
	//identify first and last top-level nav elements
	$('.header-nav-primary > li:first-child').addClass('first-nav-elem');
	$('.header-nav-primary > li:last-child').addClass('last-nav-elem');
	

	// Hack a bottom rule onto each menu
	div.append('<div class="header-nav-hr"></div>');
	
	// Calculate centered positioning of primary nav
	(function () {
		var space = 960;
		$('li.header-nav-primary').each(function () {
			space -= $(this).outerWidth();
		});
		$('ul.header-nav-primary').css({
			'padding-left': Math.floor(space / 2)
		});
	}());

	// Make subnavs visible temporarily while dimensional calculations are made.  This happens
	// synchronously with making them invisible again, so they shouldn't actually get displayed
	// during this phase.
	div.css({display: 'block'});


	// Do some hacks in IE.
	if(ie) {
		// Move the nav to the bottom of the document to force it to hover over everything.
		$('#header-nav').each(function () {
			var nav, navPos, site, sitePos, top, left;
			
			// Stash the nav and its position.
			nav = $(this);
			navPos = nav.offset();
			
			// Stash the main site container and its position.
			site = $('#main-inner');
			sitePos = site.offset();
			
			// Calculate the nav's position relative to the site container.
			left = navPos.left - sitePos.left;
			top = navPos.top - sitePos.top;
			
			// Move the nav to the bottom of the site container.
			nav.remove().appendTo(site);
			
			nav.css({
				top: top,
				left: left
			});
			
		});
	
		// Gain Layout
		$('#header-nav ul').css(
		ie6 ? {
			height: 1
		} : {
			zoom: 1
		});
		
		pngfix('.header-nav-thumb img');
	}

	// The timeouts are no longer a hack for an IE flicker problem.  (The extra overs and outs
	// seem to happen synchronously, so the fix was to make the class change asynchronously
	// after IE is done with its jittering.)
	// 
	// These timeouts are now to allow "mouse-through" without triggering submenus.
	//
	$('#header-nav li').each(function () {
	
		var update, self, selects, timeout, delay;
		
		self = $(this);
		selects = $('select'); // Selects hover over everything, so hide 'em.

		if (self.parent().parent()[0] === $('#header-nav')[0]) {
			// top-level items:
			delay = 100;
		} else {
			// sub-menu items
			delay = 0;
		}

		update = function (method, vis) {
			if (timeout) {
				clearTimeout(timeout);
				timeout = null;
			} else {
				timeout = setTimeout(function () {
					timeout = null;
					self[method]('hover');
					selects.css({
						visibility: vis
					});
				}, delay);
			}
		};
		
		self.
		mouseover(function () {
			if(!self.hasClass('InventoryClearance')) {
				update('addClass', 'hidden');
			}
		}).
		mouseout(function () {
			if(!self.hasClass('InventoryClearance')) {
				update('removeClass', '');
			}
		});

// ----< If only 1 item in menu, cut the size in half >----
		if(self.children('div').children('ul').children('li.header-nav-no-subnav').length == 2)
			$('.header-nav-subnav',self).css('width',(parseInt($('.header-nav-subnav',self).css('width')) / 2) + 'px');
	});
	
	// Enhance each submenu item's functionality.
	li.each(function () {
		var item, linkURL;
		
		item = $(this);
		
		if (!item.hasClass('header-nav-view-all')) {
			// Make each whole item clickable.
			$('a', this).each(function () {
				linkURL = this.href;
				item.click(function () {
					location.href = linkURL;
				}).css({
					cursor: 'pointer'
				});
			});
	
		}
	});

	// Keep menus inside the site boundaries.
	(function () {
		var main, limit, offset, left, width, magic=3;
		
		main = $('#main-inner');
		limit = getInt(main.width());
		offset = getInt(main.offset().left);
		div.each(function () {
			var self;
			self = $(this);
			left = getInt(self.offset().left) - offset;
			width = getInt(self.width()) + getHPad(self);
			if (left + width > limit) {
				self.css({
					left: limit - width - left + getInt(self.css('left')) - magic
				});
			}
		});
		
	}());
	
	// Add Drop Shadows
	(function () {
		var piece, gutter, corner;
		
		piece = function (css, className, target) {
			var part;
			part = $('<div class="nav-shadow-piece"></div>')
				.css({
					position: 'absolute',
					fontSize: 0
				})
				.css(css)
				.addClass(className)
				.appendTo(target);
		};
		
		gutter = 5;
		corner = 11;
		
		div.css({
			border: 'none'
		}).each(function () {

			var self, height, sideHeight, width, left, right, bottom, bottomLeft, bottomRight, topLeft, topRight;
			
			self = $(this);
			
			height = getInt(self.height()) + getVPad(self);
			width = getInt(self.width()) + getHPad(self);
			sideHeight = height - 2 * corner + gutter;
			
			left = {
				top: corner,
				left: -gutter,
				height: sideHeight,
				width: gutter
			};
			
			right = {
				top: corner,
				left: width,
				height: sideHeight,
				width: gutter
			};
			
			bottom = {
				top: height,
				left: corner - gutter,
				height: gutter,
				width: width - 2 * (corner - gutter)
			};
			
			topLeft = {
				top: 0,
				left: -gutter,
				height: corner,
				width: gutter
			};

			topRight = {
				top: 0,
				left: width,
				height: corner,
				width: gutter
			};

			bottomLeft = {
				top: corner + sideHeight,
				left: -gutter,
				height: corner,
				width: corner
			};

			bottomRight = {
				top: corner + sideHeight,
				left: width - corner + gutter,
				height: corner,
				width: corner
			};

			piece(left, 'header-nav-shadow-left', self);
			piece(right, 'header-nav-shadow-right', self);
			piece(bottom, 'header-nav-shadow-bottom', self);
			piece(topLeft, 'header-nav-shadow-top-left', self);
			piece(topRight, 'header-nav-shadow-top-right', self);
			piece(bottomLeft, 'header-nav-shadow-bottom-left', self);
			piece(bottomRight, 'header-nav-shadow-bottom-right', self);
			
			pngfix('.nav-shadow-piece');
			
		});
		
	}());

	// Make subnavs invisible again, ready to be hovered and revealed!
	// Use a null value instead of 'none', because element style overrides stylesheet.
	div.css({display: ''}); 

});
