﻿(function($) {
	var sfTimer;
	var $$;
	var latestAnchor;

	$$ = $.fn.popupMenu = function() {
		$(this)
        				.children("li:has(div)")
        				.children("a")
        				.each(function() {
        					$(this)
        						.mouseover(function() {
        							clearTimeout(sfTimer);
        							var hidden = $(this).data("hidden");
        							if (hidden != null && !hidden)
        								return;
        							var hasOpened;
        							$(this).closest("ul")
				        				.children("li:has(div)")
        								.children("a")
        								.each(function() {
        									hidden = $(this).data("hidden");
        									hasOpened = hasOpened | !(hidden == null || hidden);
        									$(this).hideSubMenu();
        								});
        							latestAnchor = $(this);

        							if (hasOpened)
        								latestAnchor.showSubMenu();
        							else
        								sfTimer = setTimeout(function() { latestAnchor.showSubMenu(); }, 150);
        						})
      							.mouseout(function() {
      								clearTimeout(sfTimer);
      								latestAnchor = $(this);
      								sfTimer = setTimeout(function() { latestAnchor.hideSubMenu(); }, 500);
      							});
        					$(this).parent().children("div")
        						.mouseover(function() {
        							clearTimeout(sfTimer);
        							latestAnchor = $(this).parent().children("a");
        							sfTimer = setTimeout(function() { latestAnchor.showSubMenu(); }, 150);
        						})
      							.mouseout(function() {
      								clearTimeout(sfTimer);
      								latestAnchor = $(this).parent().children("a");
      								sfTimer = setTimeout(function() { latestAnchor.hideSubMenu(); }, 500);
      							});
        				});
		return this;
	};
	$$.showSubMenu = $.fn.showSubMenu = function() {
		var hidden = $(this).data("hidden");
		if (hidden != null && !hidden)
			return;

		$(this).data("hidden", false);
		var jthis = $(this).parent().children("div");
		jthis.fadeIn(100);
		jthis.css("display", "block");
	};
	$$.hideSubMenu = $.fn.hideSubMenu = function() {
		var hidden = $(this).data("hidden");
		if (hidden == null || hidden)
			return;

		$(this).data("hidden", true);
		var jthis = $(this).parent().children("div");
		jthis.fadeOut(100, function() { jthis.css("display", "none"); });
	};
	return $$;
})(jQuery);

