/*  
- Loosely based on "Simple jQuery Collapsing menu" by Marco van Hylckama Vlieg
- NWS modifications © 2008
- HTML structure to use:
   <ul id="menu">
     <li><a href="#">Sub menu heading</a>
     <ul>
       <li><a href="http://site.com/">Link</a></li>
       <li><a href="http://site.com/">Link</a></li>
     </ul>
     <li><a href="#">Sub menu heading</a>
   </ul>
*/

function InitNavMenu() {
	var $ = window.jQuery;
	
	if(InitNavMenu.bDone) return; else InitNavMenu.bDone = true; 		// prevent running more than once

	// create 'linkTxt' SPAN, for wrapping around the text of expandable links, so can tell if text itself clicked
	var jqLinkSpan = $(document.createElement('A')).addClass('linkTxt').attr('href','javascript:void(0)');
	// OLD: var jqLinkSpan = $(document.createElement('SPAN')).addClass('linkTxt');

	// Assign "blankLink" class to menu links starting with #. Disabled pages with child items should be pointed to
	// 		URL "#?http://", as HouseMenu doesn't enforce disabled status in this case, just shows a normal item!
	$('#menu A[href^=#]').addClass('blankLink').click( function(e) { e.preventDefault(); } );
	//alert($('#menu A').length);
	
	window.bBasicMenuToggle = true;			// don't slide menu when expand active link
	FindActiveLink();
	window.bBasicMenuToggle = false;		// re-enable menu sliding

	// OLD (this would be better than below, but seems to ignore the has() test?!): 	$('#menu LI:has(UL) A')

  $('#menu LI:has(UL)').children('A').addClass('expandable').click(
    function(e) {
			// if user clicked on the actual link text (i.e., 'linkTxt' SPAN), instead of menu item background,
			// 		allow the link itself to trigger. Otherwise, toggle the sub-menu
			if(e && e.target && (e.target.className != "linkTxt")) {
				// toggle sub-menu that follows clicked link (using basic/pretty toggle, depending on flag)
				Toggle( $(this) );
				e.stopPropagation();		// cancel event bubble (so navigation listener doesn't fire)
			}
			else 
				if(e.target.className == "linkTxt") {
					$(this).addClass("activeLink");
					window.location = this.href; 
				}

			// cancel event bubble / navigate to link (jQuery bug means if page has BASE href, isn't auto cancelled)
			e.preventDefault(); 
		}
	).not('.blankLink, .activeLink').wrapInner(jqLinkSpan);
	// ^ Wrap 'linkTxt' around expandable link text (except blank / active links)

  // listen for clicks on navigable links (not expanding a menu)
	$('#menu').click(ChangeActiveLink);
	
	setTimeout( FinishMenuInit, 10 );		// call FinishMenuInit() after timeout, to allow above to render
}


// Finish initialising menu (less important stuff like custom icons, etc)
function FinishMenuInit() {
	var $ = window.jQuery;

	TargetNonPageLinks($, $('#menu'));
	// also add "pdfLink" classes to DNN fileticket links
	$('#menu A[href*=fileticket=]').addClass('pdfLink').attr('target', '_blank');
	// OLD:  $('#menu A[href$=.pdf], #menu A[href*=fileticket=]').addClass('pdfLink').attr('target', '_blank');

	$('#menu A:has(IMG)').addClass('hasIcon');				// add "hasIcon" class to links containing images
}


function ChangeActiveLink(e) {
	if(e && e.target && (e.target.tagName == "A")) {
		jQuery('.activeLink').removeClass('activeLink'); 
		var jqLink = jQuery(e.target);
		if(jqLink.hasClass("linkTxt")) jqLink = jqLink.parent("A");
		jqLink.addClass('activeLink');
	}
}


// Show/hide UL sub-menu that follows specified link (jQuery object), plus all parent menus, 
// 		and assign/remove CSS class "expanded" to specified link.
function Toggle(jqLink, bPretty) {
	// OLD: if(typeof jqLink != "object") jqLink = $(this);
	if(typeof bPretty == "undefined") bPretty = true;
	
	var jqSubMenuUL = jqLink.next("UL");
	if(jqSubMenuUL.length == 0) return;			// abort if next sibling isn't a UL
	
	// if sub-menu after clicked link is currently closed, open it
	if(!jqSubMenuUL.is(':visible')) {
		
		// close sibling (+ deeper) menus that are already open
		var ulOpenMenus = jqLink.parent().parent().find('UL:visible');
		(bPretty? ulOpenMenus.slideUp('normal') : ulOpenMenus.css('display', 'none'))
			.prev("A").removeClass("expanded");

		// OLD: jqLink.addClass("expanded");		// add "expanded" CSS class to clicked link, so 'open' bullet icon shown
		ShowULandParents(jqSubMenuUL);		// display the sub-menu after the clicked link (+ its parent menus)
	}
	// sub-menu following clicked link is currently open, so close it
	else {
		// OLD: jqLink.removeClass("expanded");
		HideUL(jqSubMenuUL);
	}
}


function FindActiveLink()	{
	var jqActiveLink, jqSubMenuUL, $ = window.jQuery;
	
	var sPagePath = location.pathname;
	// OLD (strip site path): var sPagePath = location.pathname.replace(SITE_PATH, "");
	// DBG: alert(sPagePath);

	if((sPagePath == "") || (sPagePath == "/")) return null;			// abort if home page
	
	// HouseMenu *should* have marked active link with ID "menuCurrentLink", so look for that first
	if(( jqActiveLink = $('#menuCurrentLink:eq(0)') ).length == 1) {
		jqSubMenuUL = jqActiveLink.next('UL');
	}
	// else look for first menu link with href matching current URL (ignoring items with sub-menus initially)
	else if(( jqActiveLink = $("#menu LI:not(:has(UL)) A[href$="+ sPagePath +"]:eq(0)") ).length == 1) {
		jqSubMenuUL = null;
	}
	// if couldn't find an matching link that doesn't have a sub-menu, look at ones *with* sub-menus
	else if(( jqActiveLink = $("#menu LI:has(UL) A[href$="+ sPagePath +"]:eq(0)") ).length == 1) {
		jqSubMenuUL = jqActiveLink.next("UL");
	}
	else {
		// sometimes the initial search fails for some reason; retry (once only) after 100ms
		if(!FindActiveLink.bRetry) { FindActiveLink.bRetry = true; setTimeout(FindActiveLink, 100); }
		// OLD: throw new Error(0, "Couldn't find active link");
		return null;			// active link not found, so abort
	}
	
	// expand active link's parent menus, plus its sub-menu if it has one
	if(jqSubMenuUL && (jqSubMenuUL.length == 1)) {
		// expand active link's parent menus and sub-menu
		ShowULandParents(jqSubMenuUL);
	}
	else {
		// expand active link's parent menus
		var ulParent = jqActiveLink.parent("LI").parent("UL");
		if(ulParent.length == 1) ShowULandParents(ulParent);
	}

	jqActiveLink.addClass("activeLink");		// add "activeLink" CSS class to current page link (if found)
	
	// DBG: alert(jqActiveLink[0].outerHTML);
	return jqActiveLink;										// return reference to active link element (jQuery wrapped)
}


function ShowULandParents(jqUL, bPretty) {
	var ulAndParents = jqUL.parents("UL").andSelf();
	ulAndParents.prev("A").addClass("expanded");			// add 'expanded' class to parent link for each UL
	
	if(!window.bBasicMenuToggle) 
		ulAndParents.slideDown('normal');
	else
		ulAndParents.show();
}

function HideUL(jqUL, bPretty) {
	jqUL.prev("A").removeClass("expanded");
	if(!window.bBasicMenuToggle) 
		jqUL.slideUp('normal'); 
	else
		jqUL.hide();
}


// OLD: 
		// jQuery(document).ready(InitNavMenu);
		// jQuery(document).ready( function(jQuery) { setTimeout(InitNavMenu, 10); });
