// menu manipulator function
// note that the three variables at the beginning are required and will be overwritten by the script once prepare() in called
var uM_menu = {
	menu_id: "nav ul:first",
	default_index: '/index.html',
	use_get_variables: false,
	parent_path: null,
	controls: true,
	expand_all: false,
	breadcrumbs: true,
//	expand_url: 'http://www.unimelb.edu.au/template-assets/07/images/menu/plus.gif',
//	collapse_url: 'http://www.unimelb.edu.au/template-assets/07/images/menu/minus.gif',
	collapse_siblings: true,

	// generate a clickable link for replacing and change the class
	// todo: should separate this functionality and just alter the existing links (move this into expand/collapseSection functions)
	newLink: function (prnt, action)
	{
		var new_link = $('<a class="control"></a>');
//		var new_image = $('<img />');
		// generate some alt text
		var link_text = prnt.children('a:last').text() + ' section';
		switch (action)
		{
			case "expand":
//				new_image.attr('src', uM_menu.expand_url);
//				new_image.attr('alt', 'Expand ' + link_text);
//				new_image.attr('title', 'Expand ' + link_text);
				new_link.attr('title', 'Expand ' + link_text);
				// clicking the link will cause the menu to expand
				new_link.click(
					function ()
					{
						uM_menu.expandSection($(this));
					}
				);
				// todo: should investigate toggleClass here
				prnt.removeClass('expand');
				prnt.addClass('collapse');
//				new_image.appendTo(new_link);
			break;
			case "collapse":
//				new_image.attr('src', uM_menu.collapse_url);
//				new_image.attr('alt', 'Collapse ' + link_text);
//				new_image.attr('title', 'Collapse ' + link_text);
				new_link.attr('title', 'Collapse ' + link_text);
				// clicking the link will cause the menu to collapse
				new_link.click(
					function ()
					{
						uM_menu.collapseSection($(this));
					}
				);
				prnt.removeClass('collapse');
				prnt.addClass('expand');
//				new_image.appendTo(new_link);
			break;
		}
		if (uM_menu.controls)
		{
			return new_link;
		}
		else
		{
			return $('<span></span>').addClass('bullet');
		}
	},

	prepare: function()
	{
		// check for options specified as classes
		if ($('#' + uM_menu.menu_id).hasClass('no-breadcrumbs'))
		{
			uM_menu.breadcrumbs = false;
		}
		if ($('#' + uM_menu.menu_id).hasClass('no-controls'))
		{
			uM_menu.controls = false;
		}
		if ($('#' + uM_menu.menu_id).hasClass('expand-all'))
		{
			uM_menu.expand_all = true;
		}
		if ($('#' + uM_menu.menu_id).hasClass('use-get-variables'))
		{
			uM_menu.use_get_variables = true;
		}
		if ($('#' + uM_menu.menu_id).hasClass('no-collapse-siblings'))
		{
			uM_menu.collapse_siblings = false;
		}
		// insert default spans for bullet image (controlled by css)
		$('#' + uM_menu.menu_id + ' li').each(
			function ()
			{
				$('<span></span>').addClass('bullet').prependTo($(this));
			}
		);

		// replace the bullets where the list item contains an unordered list with a link
		if (!uM_menu.expand_all)
		{
			$('#' + uM_menu.menu_id + ' ul').each(
				function ()
				{
					// the first sibling is the bullet span
					$(this).siblings(':first').replaceWith(uM_menu.newLink($(this).parent(), 'expand'));
				}
			);
		}
		// highlight current link and create breadcrumbs if required
		uM_menu.highlightCurrentLink();
	},

	expandSection: function(link)
	{
		// collapse the currently expanded sibling
		if (uM_menu.collapse_siblings)
		{
			var exp = link.parent().siblings('.expand');
			exp.children(':first').replaceWith(uM_menu.newLink(exp, 'expand'));
		}
		// replace the link with a collapser
		link.replaceWith(uM_menu.newLink(link.parent(), 'collapse'));
	},

	collapseSection: function(link)
	{
		// replace the link with an expander
		link.replaceWith(uM_menu.newLink(link.parent(), 'expand'));
	},

	highlightCurrentLink: function()
	{
		// collect all the anchors with links in the menu
		var ans = $('#' + uM_menu.menu_id + ' a[href]');
		var breadcrumb = $('#breadcrumbs ul');
		// determine the path of the current page todo: see if this can be optimised at all
		var path = window.location.pathname;
		path = path.replace(/\/$/, uM_menu.default_index);
		var domain_path = window.location.protocol + '//' + window.location.hostname;
		var path_IE = domain_path;
		if (window.location.port)
		{
			path_IE += ':' + window.location.port;
		}
		if (uM_menu.use_get_variables)
		{
			path += window.location.search;
		}
		path_IE += path;
		if (uM_menu.parent_path)
		{
			uM_menu.parent_path = uM_menu.parent_path.replace(/\/$/, uM_menu.default_index);
		}
		// Checking for a successful highlight
		var highlighted = false;
		// loop through all the anchors to set the higlighting classes and add breadcrumbs
		ans.each(
			function ()
			{
				var ref = $(this).attr('href');
				ref = ref.replace(/\/$/, uM_menu.default_index);
				// does the path match the link we're currently in?
				if ((ref == path || ref == path_IE || ref == uM_menu.parent_path || ref == domain_path + uM_menu.parent_path) && !$(this).hasClass('duplicate'))
				{
					// if our best fit has a referrer class, check to see if there's a better referrer further down the list
					var best_fit = $(this);
					if (best_fit.hasClass('referrer'))
					{
						var referrers = ans.filter('.referrer');
						referrers.each(
							function ()
							{
								// todo make this check for relative paths as well
								if ($(this).attr('rev') == document.referrer)
								{
									best_fit = $(this);
								}
							}
						);
					}
					// add an id to this link for use as the best fit
					highlighted = true;
					best_fit.attr('id', 'uM_menu-best-fit');
					// only one item needs highlighting (as we have an exact match) so exit the each() loop
					return false;
				}
			}
		);
		if (!highlighted)
		{
			// go through each menu item again and find a best fit
			var best_length = 0;
			ans.each(
				function ()
				{
					var ref = $(this).attr('href');
					// note that we use a different variable for the default index here in case we can match a directory link
					var re = new RegExp(uM_menu.default_index + "$");
					var ref_index = ref.replace(re, '');
					// does the path match the link we're currently in?
					//if (this is the best fit && ref.length > best_length)
					if ((path.match(ref) || path_IE.match(ref) || path.match(ref_index) || path_IE.match(ref_index)) && ref.length > best_length)
					{
						highlighted = true;
						best_length = ref.length;
						// unset the previous best fit
						$('#uM_menu-best-fit').removeAttr('id');
						// reset it to this one
						$(this).attr('id', 'uM_menu-best-fit');
						// we don't return here (as we did in the previous each() loop) because there might be a better fit
					}
				}
			);
		}
		// if we found a link to highlight do the magic
		if (highlighted)
		{
			// mark the current link
			$('#uM_menu-best-fit').addClass("current_link");
			// add its text to the breadcrumbs
			if (uM_menu.breadcrumbs)
			{
				var new_crumb = $('<li></li>');
				$(document.createTextNode($('#uM_menu-best-fit').text())).appendTo(new_crumb);
				new_crumb.appendTo(breadcrumb);
			}
			// add links from ancestors to the breadcrumbs and expand them
			$('#uM_menu-best-fit').parents('li').each(
				function (index)
				{
					if (index == 0)
					{
						$(this).addClass("parent");
					}
					else
					{
						$(this).addClass("ancestor");
					}
					if ($(this).hasClass("collapse"))
					{
						$(this).children(':first').replaceWith(uM_menu.newLink($(this), 'collapse'));
						if (uM_menu.breadcrumbs)
						{
							var ul_kids = $(this).find('ul');
							if (ul_kids.length > 0 && !$(this).hasClass('parent'))
							{
								var child_index = 0;
								if (uM_menu.controls)
								{
									child_index = 1;
								}
								new_crumb = $('<li></li>');
								$(this).children('a').eq(child_index).clone().appendTo(new_crumb);
								new_crumb.insertAfter(breadcrumb.children(':first'));
							}
						}
					}
				}
			);
		}
	}
};

// clear search form function
// note that the three variables at the beginning are required and will be overwritten by the script once prepare() in called
var uM_search = {
	submit: false,
	input: false,
	timer: false,
	prepare: function ()
	{
		// grab the text field and the submit button
		var b = $('#searchform button:submit');
		if (b.attr('type') != 'submit')
		{
			b = $('#searchform input:submit');
		}
		var q = $('#searchform input:text');
		// Make them accessible from within a setInterval function
		uM_search.submit = b;
		uM_search.input = q;
		// give them the default appearance
		b.attr('disabled', 'disabled');
		q.attr('value', q.attr('title'));
		// when the user enters the text field, clear it if it is blank or equivalent to the title text
		// then check every 50 milliseconds to see if the user has entered a search term and activate the submit button
		q.bind('focus',
			function ()
			{
				if ($(this).attr('value') == '' || $(this).attr('value') == $(this).attr('title'))
				{
					$(this).attr('value', '');
				}
				uM_search.timer = setInterval(
					function ()
					{
						if (uM_search.input.attr('value') == '' || uM_search.input.attr('value') == uM_search.input.attr('title'))
						{
							uM_search.submit.attr('disabled', 'disabled');
							uM_search.submit.addClass('disabled');
						}
						else
						{
							uM_search.submit.removeAttr('disabled');
							uM_search.submit.removeClass('disabled');
						}
					},
					50 //the interval for checking in milliseconds
				);
			}
		);
		// when the user leaves the text field check if there's any text. If not, reinstate the title text
		q.bind('blur', function ()
		{
			clearInterval(uM_search.timer);
			if ($(this).attr('value') == '')
			{
				$(this).attr('value', $(this).attr('title'));
				uM_search.submit.attr('disabled', 'disabled');
				uM_search.submit.addClass('disabled');
			}
		});
	}
};

// tables with the class 'striped' are given alternating add and even classes
// these classes are configurable
var uM_stripe = {
	odd: 'odd',
	even: 'even',
	prepare: function ()
	{
		$('table.striped tr:even').addClass(uM_stripe.even).removeClass(uM_stripe.odd);
		$('table.striped tr:odd').addClass(uM_stripe.odd).removeClass(uM_stripe.even);
	}
};

// tables with the class 'striped_columns' are given alternating add and even classes
// these classes are configurable
var uM_stripe_columns = {
	odd: 'odd-col',
	even: 'even-col',
	prepare: function ()
	{
		$('table.striped_columns tr').each(
			function ()
			{
				$(this).children('td:even').addClass(uM_stripe_columns.even).removeClass(uM_stripe_columns.odd);
				$(this).children('td:odd').addClass(uM_stripe_columns.odd).removeClass(uM_stripe_columns.even);
			}
		);
	}
};

// set default text for a text input field by adding title-default as a class to the input element
// server-side processing will need to manage the default text (in the event that the user never focusses on the element)
// if you'd like to apply this functionality to inputs with a different class you can, but notice that it only works on type="text"
var uM_title_default = {
	classname: 'title-default',
	reinstate: true,
	timer: false,
	prepare: function ()
	{
		// select all text inputs with the named class
		$('input.' + uM_title_default.classname + ':text').each(
			function ()
			{
				// set the value to the title attribute
				$(this).attr('value', $(this).attr('title'));
				// as soon as the user enters the field clear the text and then abort processing on this element
				$(this).bind('focus',
					function ()
					{
						if ($(this).attr('value') == $(this).attr('title'))
						{
							$(this).attr('value', '');
						}
					}
				);
				if (uM_title_default.reinstate)
				{
					// as soon as the user leaves the field check the text against the title field
					$(this).bind('blur',
						function ()
						{
							if ($(this).attr('value') == '')
							{
								$(this).attr('value', $(this).attr('title'));
							}
						}
					);
				}
			}
		);
	}
};

// replace a link to a map with an iframe containing the map
var uM_map_replace = {
	width: 510,
	height: 390,
	frameborder: 0,
	prepare: function ()
	{
		$('a.map-embed').each(
			function ()
			{
				var new_link = $(this).clone();
				var new_iframe = $('<iframe width="' + uM_map_replace.width + '" height="' + uM_map_replace.height + '" frameborder="' + uM_map_replace.frameborder + '" src="' + $(this).attr('href') + '?SQ_DESIGN_NAME=plain"></iframe>');
				new_link.appendTo(new_iframe);
				$(this).parent().replaceWith(new_iframe);
			}
		);
	}
};

$(document).ready(function () {
	uM_search.prepare();
	uM_stripe.prepare();
	uM_stripe_columns.prepare();
	uM_title_default.prepare();
	uM_map_replace.prepare();
	uM_menu.prepare();
});

