﻿/* TODO:
*/

BF.megaNav = {

	init: function () {
		var self = this;

		// element references
		self.parentChannels = $('ul#megaNav > li');
		//self.childLists = self.parentChannels.find('ul');

		// variables
		self.showTimer = 0;
		self.hideTimer = 0;
		self.targetIndex = 0;
		self.currentIndex = 0;
		self.delayAmt = 300;

		// setup
		self.equalizeHeights();

		// event handlers
		self.parentChannels.hover(
			function () {
				self.targetIndex = $(this).index();
				self.showSubNav();
			},
			function () {
				self.currentIndex = $(this).index();
				self.hideSubNav();
			}
		);
		delete BF.megaNav.init;
	},

	equalizeHeights: function () {
		var self = this;
		self.parentChannels.each(function () { // equalize subnav list heights for even column borders
			var subNavLists = $(this).find('ul:not(.special)');
			var maxListHeight = 0;

			subNavLists.each(function () {
				var currentListHeight = $(this).height();
				if (currentListHeight > maxListHeight) {
					maxListHeight = currentListHeight;
				}
			});

			subNavLists.each(function () {
				$(this).height(maxListHeight);
			});
		});
		self.parentChannels.find('div.megaSubNav').hide(); // hide wraps once inner lists are sized
	},

	showSubNav: function () {
		var self = this;
		var parentHover = self.parentChannels.eq(self.targetIndex);

		if (parentHover.hasClass('hover')) { // if target hover item already has hover state (currently open), don't hide item/do anything at all (using class instead of indexes because user might roll off then back on the same link after it closes, in that case we want it return false and open again)
			clearTimeout(self.hideTimer);
			self.hideTimer = 0; // reset hide timeout so it will attempt to run again on mouse out

		} else {
			self.showTimer = setTimeout(function () {
				parentHover.addClass('hover');
				parentHover.find('div.megaSubNav').stop(true, true).fadeIn();
			}, self.delayAmt);
		}

	},

	hideSubNav: function () {
		var self = this;
		var parentLeave = self.parentChannels.eq(self.currentIndex);

		clearTimeout(self.showTimer);

		if (self.hideTimer === 0) { // only execute if the timeout function is not already running elsewhere (any other timeouts are complete and reset)
			self.hideTimer = setTimeout(function () {
				parentLeave.removeClass('hover');
				parentLeave.find('div.megaSubNav').stop(false, true).hide();
				self.hideTimer = 0; // reset timeout
			}, self.delayAmt);
		}
	}

};
