﻿// Function to remove white space from between tags
jQuery.fn.cleanWhitespace = function () {
	var html = this.html();
	var stripped = html.replace(/>\s+</g, '><');

	this.html(stripped);
}

// Set up main menu
$(function () {
	var mainNav = $('#mainNav');
	var navWidth = mainNav.innerWidth();
	var navHeight = mainNav.innerHeight();

	// Remove extra spaces between menu list items
	mainNav.cleanWhitespace();

	// Stop menu from wrapping by shortening the width of the longest items
	var topLevelItems = mainNav.find('>li');
	var lastItem = mainNav.find('>li:last');
	var timesAdjusted = 0;

	while (lastItem.position().top > navHeight) {
		// Find widest <li> and adjust its width and font settings
		var widestLi = mainNav.find('>li:first');

		topLevelItems.each(function () {
			if ($(this).width() > widestLi.width()) widestLi = $(this);
		});

		var anchorWidth = widestLi.find('>a')
			.css('position', 'absolute')
			.css('top', 0)
			.css('left', 0)
			.css('width', Math.floor(navWidth / topLevelItems.length))
			.css('line-height', Math.floor((navHeight / 2)) + 'px')
			.css('font-size', '10px')
			.outerWidth();

		widestLi.width(anchorWidth);

		timesAdjusted++;
	}

	if (timesAdjusted > 0) {
		// WebKit and IE 7 don't like this wrapping fix (come on, Chrome, even IE 8 got this right)
		// Oh well, WebKit and IE 7, we'll just float your menu to the left as a workaround
		var isIE7 = (navigator.appVersion.indexOf('MSIE 7.') > -1);
		var isWebKit = /AppleWebKit\/([\d.]+)/.exec(navigator.userAgent);

		isWebKit = (isWebKit) ? parseFloat(isWebKit[1]) : false;

		if (isIE7 || isWebKit) {
			topLevelItems.css('float', 'left');
		}
	}

	// Add touch-based support to drop-downs
	if (typeof TouchEvent != 'undefined') {
		// Add click event handlers to top-level menu to show drop-downs
		mainNav.find('>li>a').each(function () {
			$(this).click(function (e) {
				var parentLi = $(this).parent();

				if (!parentLi.hasClass('active') && parentLi.find('ul').length > 0) {
					mainNav.find('>li').removeClass('active');
					$(this).parent().addClass('active');

					e.preventDefault();
					return false;
				}
			});
		});

		// Add click event handler to hide drop-down menus
		$(document).click(function (e) {
			if (e.target.nodeName.toLowerCase() != 'a') {
				mainNav.find('>li').removeClass('active');
			}
		});
	}
});

