// Required :: jQuery

//	This points to the xml resource that defines the menu structure.
//	(This could point to a dynamically generated XML file)
var menuDefinition = "/iacpnet/members/includes/menus.xml";
var menuAutoSelectItem = true;

// Add extension methods to JavaScript objects
String.prototype.endsWith = function(str) { return (this.match(str+"$")==str); }
String.prototype.trim = function () { return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }

// Create a holder for query string args
var queryArgs = null;
var selectedMenuItemId = null;

// Create a holder for the Help URL
var _helpUrl = null;

// Named "constants"
var BOTTOM = 'b';
var MIDDLE = 'm';
var TOP = 't';
var LEFT = 'l';
var CENTER = 'c';
var RIGHT = 'r';
var AUTO = 'a';

// This is called by body.onload and takes care of any setup work
// that needs to be done 
function init()
{
	extend();
	buildMenus();
	initCallouts('callout', '#callout');
	initWatermarks('watermark');
	initAccordions('accordion');
	setHelpUrl(_helpUrl);
}

// Call this with an XML item ID to select that menu item
function menu(itemId)
{
	if (itemId)
		selectedMenuItemId = itemId;
}

// Call this to set any query string args to be globally 
// applied to links in the menus
function args(args)
{
	if (args)
		queryArgs = args;
}

function buildMenus()
{
	$.ajax(
		{
			url: menuDefinition,
			async: false,
			type: "GET",
			cache: false,
			dataType: "xml",
			success: function(xml)
				{
					var userXml = $('user', xml);
					var mainXml = $('main', xml);
					var footerXml = $('footer', xml);
								
					buildMenu(userXml.attr('container'), userXml.children().children(), BOTTOM, LEFT, null);
					buildMenu(mainXml.attr('container'), mainXml.children().children(), BOTTOM, AUTO, null, menuAutoSelectItem);
					buildMenu(footerXml.attr('container'), footerXml.children().children(), TOP, LEFT, null);
					
					initMenuPositions(mainXml.attr('container'), BOTTOM, AUTO);
				}
		});
}

function buildMenu(container, items, subMenuVertical, subMenuHorizontal, itemParent, autoSelectItem)
{
	var ul = document.createElement('ul');
	for(var i = 0; i < items.length; i++)
	{
		var id = $(items[i]).attr('id');
		var title = $('> title', items[i]).text();
		var link = $('> link', items[i]).text();
		var target = $('> link', items[i]).attr('target');
		var isHelpItem = $(items[i]).attr('help');
		
		// Create the link
		var a = document.createElement('a');
		//a.title = title; (removed by request from Diane 10.28.2009)
		
		if (link)
		{
			if (queryArgs != null)
				a.href = appendQueryArgs(link);
			else			
				a.href = link;
				
			if (target)
				$(a).attr('target', target);
		}

		// Check if this item is selected
		var selected = false;
		if (selectedMenuItemId)
		{
			if (id == selectedMenuItemId)
			{
				selected = true;
			}
			else if (autoSelectItem)
			{
				selected = isMenuItemCurrentPage(a);
			}
			else
			{
				selected = $(items[i]).attr('selected');
			}
		}
		
		// Handle help item
		if (isHelpItem)
			$(a).addClass('help');
		
		$(a).append(title);
				
		var li = document.createElement('li');
		$(li).append(a);
		$(li).attr('id', getSubMenuId(container, i));		
		
		var submenu = null;
		var subitems = $('subitems', items[i]).children();
		if (subitems.length > 0)
		{	
			$(li).mouseenter(function() { showHideMenu('show', this, subMenuVertical, subMenuHorizontal); });
			$(li).mouseleave(function() { showHideMenu('hide', this); });						
			
			submenu = buildSubMenu(container, i, subitems, li, autoSelectItem);
			$(submenu).mouseenter(function() { showHideMenu('show', this, subMenuVertical, subMenuHorizontal); });
			$(submenu).mouseleave(function() { showHideMenu('hide', this); });
		}

		if (selected)
		{
			selectItem(li);
			selectItem(container);
			if (itemParent)
			{						
				selectItem(itemParent);
			}
		}
		
		$(ul).append(li);
	}
	$(container).append(ul);
}

function showHideMenu(action, item, valign, halign)
{	
	var isPopup = false;
	if (item.id && item.id.endsWith('_c')) 
	{
		isPopup = true;
		var i = item.id.lastIndexOf('_c');
		var parentId = item.id.substring(0, i);
		item = document.getElementById(parentId);
	}

	var menuItem = $(item);
	var relPos = menuItem.position();
	var relW = menuItem.outerWidth();
	var relH = menuItem.outerHeight();
	
	var popItem = $('#' + item.id + '_c');
	var popPos = popItem.position();
	var popW = popItem.outerWidth();
	var popH = popItem.outerHeight();
	
	var hcenter = ((relW - popW) / 2) + relPos.left;
	var vcenter = ((relH - popH) / 2) + relPos.top;

	if (action == 'hide')
	{
		$(popItem).hide();
		deactivateItem(item);
	}
	else if (action == 'show')
	{
		activateItem(item);
		switch(valign)
		{
			case TOP:
				popItem.css('top', -popH + 'px');
				break;
			case MIDDLE:
				popItem.css('top', vcenter + 'px');
				break;
			case BOTTOM:
				popItem.css('top', relPos.top + relH + 'px');
				break;
		}
		
		switch(halign)
		{
			case LEFT:
				popItem.css('left', relPos.left + 'px');
				break;
			case CENTER:
				popItem.css('left',  hcenter + 'px');
				break;
			case RIGHT:
				popItem.css('left', relPos.left - (relW - popW) + 'px');
				break;
			case AUTO:										
				$(popItem).show(); // need to show it early to calculate dimensions properly
				var subItem = $('> ul', popItem);				
				var subPos = subItem.position();
				var subW = subItem.childWidth('> li');
				var subH = subItem.childHeight('> li');				
				var subhcenter = ((relW - subW) / 2) + relPos.left;
				var subvcenter = ((relH - subH) / 2) + relPos.top;				

				var l = subhcenter;	
				if (popPos && l + subW > popW) l = popW - subW;
				l = l - 5; // experimental adjustment
				if (l < 0) l = 0;				
				subItem.css('left', l + 'px');
				break;
		}	
		$(popItem).show();
	}
}

function initMenuPositions(container, valign, halign)
{	
	var menuItems = $('> ul > li', $(container));
	for (var i = 0; i < menuItems.length; i++)
	{
		var menuItem = menuItems[i];
		if (menuItem != null && $(menuItem).hasClass('selected'))
		{	
			showHideMenu('show', menuItem, valign, halign);
			showHideMenu('hide', menuItem);
		}
	}
}

function getSubMenuId(container, index, postfix)
{
	var disallow = new Array(' ', '.', '#');
	var id = (container + '_' + index);
	
	for (var i in disallow)
		id = id.replace(disallow[i], '');
	
	if (postfix)
		id += postfix;
	
	return id;
}

function selectItem(item)
{
	$(item).addClass('selected');
}

function deselectItem(item)
{
	$(item).removeClass('selected');
}

function activateItem(item)
{
	$(item).addClass('active');
}

function deactivateItem(item)
{
	$(item).removeClass('active');
}

function buildSubMenu(container, index, items, parent, autoSelectItem)
{
	var div = document.createElement('div');
	$(div).attr('class', 'subMenu');	
	$(div).attr('id', getSubMenuId(container, index, '_c'));
	
	buildMenu(div, items, '', '', parent, autoSelectItem);
	$(container).append(div);
	
	return div;
}

function preloadImage(url)
{
	var img = new Image(); 
	img.src = url;
}

function initCallouts(cssClass, template)
{
	var callouts = $('.'+cssClass);	
	// Set the necessary template CSS properties
	$(template).css('display', 'none');
	$(template).css('z-index', 3000);
	$(template).css('position', 'absolute');
	
	callouts.mouseenter(function()
	{
		var titleElement = $(template + " .title");
		var bodyElement = $(template + " .body");
		
		var title = $(this).text();
		var body = $(this).attr('callout');
		
		titleElement.text(title+':');
		bodyElement.text(body);
		
		title.length > 0 ? titleElement.show(): titleElement.hide();
		body.length > 0 ? bodyElement.show(): bodyElement.hide();
		
		var callout = $(template);
		var position = $(this).position();		
		callout.css('top', position.top + ($(this).outerHeight() / 2));
		callout.css('left', position.left - callout.outerWidth());
		callout.show();
	});
	
	callouts.mouseleave(function()
	{
		$("#callout").hide();
	});
}

function initWatermarks(cssClass)
{
    var watermarks = $(".watermark");
    watermarks.wrap("<p class=\"inFieldWatermark\">").before(
      function() {
        var id = $(this).attr("id");
        var watermarkText = $(this).attr("title");
        var retVal = $(document.createElement("label")).attr("for", id).html(watermarkText)[0];
        return retVal;
      });

      $(".inFieldWatermark").children("label").inFieldLabels();

      var initialFocus = $(".initialFocus");
      if (initialFocus.length > 0)
        setTimeout('$(".initialFocus")[0].focus();', 1);
}


var bodyClicked = false;
function initAccordions(cssClass)
{
	var inputs = $('.'+cssClass+' .expander');
	inputs.disableTextSelect();
	inputs.click(function()
	{		
		if (!bodyClicked)
		{
			var parent = $(this).parent('ul');
			var mode = parent.length > 0 && parent.hasClass('multiple') ? 'multiple' : 'single';
		
			switch(mode)
			{
				case 'single':
					var children = parent.children('.open');
					children.removeClass('open');
					$(this).addClass('open');
					break;
				case 'multiple':
					if ($(this).hasClass('open'))
						$(this).removeClass('open');
					else
						$(this).addClass('open');
					break;
			}
		}
		bodyClicked = false;
	});
	
	$('.body', inputs).click(function()
	{
		bodyClicked = true;
	});
}

function setHelpUrl(helpUrl)
{
	// ensure there's a value to set
	if (helpUrl)
	{
		// store the value for potential future use
		if (_helpUrl == null)
			_helpUrl = helpUrl;
			
		// locate the help menu item(s)
		var helpLink = $('.help');
		if (helpLink)
		{
			helpLink.each(function()
			{
				$(this).attr('href', _helpUrl);
			});
		}
	}
}

function isMenuItemCurrentPage(item)
{
	var url = new Array();
	url.push(window.location.href);
	url.push(window.location.pathname);
	url.push(window.location.href.substr(window.location.href.lastIndexOf('/') + 1, window.location.href.length));
	
	for (var i in url)
	{
		var item = $(item);
		var itemUrl = item.attr('href')
		
		if (itemUrl)
		{
			itemUrl = itemUrl.toLowerCase();
			var matchUrl = url[i].toLowerCase();
			if (itemUrl == matchUrl)
			{
				return true;
			}
		}
	}
	
	return false;
}

function appendQueryArgs(baseUrl)
{
	var leadChar = '?';
	if (baseUrl.indexOf('?') != -1) // already has a query string
		leadChar = '&';
	
	var queryString = queryArgs;
	
	if (queryString.indexOf('?') == 0)
		queryString = queryString.substr(1, queryString.length - 1);

	if (queryString.indexOf('&') == 0)
		queryString = queryString.substr(1, queryString.length - 1);		
	
	return baseUrl + leadChar + queryString;
}

function extend()
{
	$.prototype.childWidth = function(selector)
		{
			var children = $(selector, this);
			var width = 0;
			for (var i = 0; i < children.length; i++)
			{
				var child = children[i];
				if (!child.outerWidth)
					child = $(child);
					
				if (child != null)
				{					
					width += child.outerWidth();
				}
			}			
			return width;
		}
	$.prototype.childHeight = function(selector)
		{
			var children = $(selector, this);
			var height = 0;
			for (var i = 0; i < children.length; i++)
			{
				var child = $(children[i]);
				if (child != null)
				{
					var ow = child.outerHeight();
					if (ow && ow != 0)
					{						
						height += child.outerHeight();						
					}
				}
			}
			return height;
		}		
			
	$.extend($.fn.disableTextSelect = function() 
	{
			return this.each(function()
			{
				if($.browser.mozilla)
				{
					$(this).css('MozUserSelect','none'); //Firefox
				}
				else if($.browser.msie)
				{
					$(this).bind('selectstart',function(){return false;}); //IE
				}
				else
				{
					$(this).mousedown(function(){return false;}); //Opera, etc.
				}
			});
	});
}