﻿var site = function () {
    this.navLi = $('#mainNav > li');
    this.init();
};

site.prototype = {

	init: function () {
		this.setMenu();
	},

	// Enables the slidedown menu, and adds support for IE6

	setMenu: function () {

		function isIe() {
			var test = navigator.userAgent.toString().search(/MSIE 6/gi) > -1 ? true : false;
			return test;
		}
		// runs through each node and gets its offset
		// to collect the full number - for ie6
		function totalOffset(node) {
			var offset = 0;
			while (node.offsetParent) {
				offset += node.offsetLeft;
				node = node.offsetParent;
			}
			return offset;
		}
		// absolute positioning disallows width
		// retrieval in ie6, so we'll build
		// the width with the child li elements
		function buildWidth($ulNode) {
			var newWidth = 0;
			$ulNode.children('li').each(function () {
				newWidth += $(this).outerWidth();
			});
			return newWidth;
		}
		this.navLi.children('ul').addClass('subNav');
		var currentLi = this.navLi.filter('.current'),
			parentUl = $('#mainNav'),
			parentOffset = isIe() ? totalOffset(document.getElementById('mainNav')) : parentUl.offsetLeft;
		//currentLi.children('ul').css('top', '30px');

		$.each(this.navLi, function () {
			var self = $(this),
				subMenu = self.find('> ul'),
				tabWidth = self.width(),
				menuWidth = isIe() ? buildWidth(subMenu) : subMenu.width(),
				// a little browser sniffing for offset retrieval
				tabOffset = isIe() ? (totalOffset(this) - parentOffset) : self.position().left,
				centerPoint = self.children('ul').children('li').length > 1 ? (tabOffset + (tabWidth / 3) - (menuWidth / 2)) : (tabOffset + (tabWidth / 3) - (menuWidth / 3));

				subMenu.css({ 'width': menuWidth + 'px' });

			if (isIe()) {
				if (centerPoint < 0) {
					subMenu.css({
						'left': '0'
					});
				}
				else if ((tabOffset + menuWidth) > 980 + parentOffset || self.hasClass('last')) {
					subMenu.css({
						'right': '0',
						'left': 'auto'
					});
				}
				else {
					subMenu.css({
						'left': centerPoint + 'px'
					});
				}
			}
			else {
				if (centerPoint < 0) {
					subMenu.css({
						'left': '0'
					});
				}
				else if ((tabOffset + menuWidth) > 980 || self.hasClass('last')) {
					subMenu.css({
						'right': '0',
						'left': 'auto'
					});
				}
				else {
					subMenu.css({
						'left': centerPoint + 'px'
					});
				}
			}

			if (self.children('ul').length > 0) {
				self.bind('mouseenter', function () {
					self.addClass('hover');
					subMenu.css('top', '30px');
				});
				self.bind('mouseleave', function () {
					self.removeClass('hover');
					subMenu.css('top', '-9999px');
				});
			}
		});
	}

}


new site();
