var webContextPath = '';

addLoadEvent(function() {
					  if ($('web-context-path'))
						  webContextPath =  $('web-context-path').innerHTML;
					  //Hide the empty results so the first Toggle works (Menu Search)
					  sr1 = $('search-results');
  					  if (sr1)
					  	  sr1.style.display = 'none';
					  sr2 = $('search-results2');
					  if (sr2)
					  	  sr2.style.display = 'none';

					  // (Toggle Navigation)
					  var toggleTab = $('toggle-nav');
					  if (toggleTab) {
						  toggleTab.onclick = function() { return toggleEntireMenuPanel(); };
					  }

   				   	  var favouritesList = $('favourites');

					  var panelUpLinks = $A(getElementsByClassName('panel-up'));
					  panelUpLinks.each(function(panelUpLink) {
												 panelUpLink.title="Drag n Drop panel to new location";
												 panelUpLink.onclick = function() { return false; };
												 panelUpLink.style.display = 'none';
												 });

					  //Add 2 Favs link from header
					  var add2FavsFromHeader = $('add-favourite');
					  if (add2FavsFromHeader) {
							add2FavsFromHeader.onclick= function() { addFavourite(this, true); return false; };
					  }

					  javascriptImageControls(favouritesList);
					  ajaxifyNavigationMenuItems();

					  //Add 2 Favs links inside History
					  var add2FavsLinks = $A(getElementsByClassName('add-favourite'));
					  add2FavsLinks.each(function(add2FavLink) {
												  //Skip the add 2 fav link inside the H1
												  if (add2FavLink.id.indexOf('add-favourite-') == 0) {
														add2FavLink.onclick = function() {
																				addFavourite(this, false);
																				return false;
														};
														//Hide the link unless hover
														add2FavLink.style.display = 'none';
														add2FavLink.parentNode.onmouseover = function() {
															add2FavLink.style.display = 'inline';
														};
														add2FavLink.parentNode.onmouseout = function() {
															add2FavLink.style.display = 'none';
														};
												  }
										});

					  //Add Instructions Show/Hide
					  var infoPanels = $A(document.getElementsByClassName('infopanel'));
					  infoPanels.each(function(infoPanel) {
										   var header4 = infoPanel.getElementsByTagName('h4')[0];
										   if (header4) {
											   	//Check to see whether they are visible or not
											   instructionsContentClass = $('instructions-content').className;
											   var canSeeIt = instructionsContentClass == 'instructions'; //instructions-toggle if hidden
											   if (instructionsContentClass == 'instructions-toggle') {
												   //set this to none by hand because firefox initalises styles to ''
												   $('instructions-content').style.display = 'none';
											   }

											   var pic = document.createElement('img');
											   pic.setAttribute('alt', (canSeeIt ? 'Hide' : 'Show') + ' Instructions');
											   pic.setAttribute('src', webContextPath + '/icons/' + (canSeeIt ? 'minimise_negative' : 'maximise_negative') + '.gif');
											   var toggler = document.createElement('a');
											   toggler.setAttribute('title','Toggle Instructions');
											   toggler.setAttribute('href',webContextPath + '/toggleInstructions.do');
											   toggler.setAttribute('id', 'toggle-instructions');
											   toggler.onclick= function () { toggleInstructions(this); return false; };
											   toggler.appendChild(pic);
											   header4.appendChild(toggler);

										   }

										   });

					  var signOutLink = $('quick-link-signout');
					  if (signOutLink) {
						  //Get authority.ocx to clear the details from the registry
						  signOutLink.onclick = function() {
													if (opener)
														opener.unregisterMe();
						  };
						  if (parent.frames.length > 0)
							signOutLink.setAttribute('target', '_top');

					  }


                 var printerLink = $('quick-link-print');
					  if (printerLink) {
						  printerLink.onclick = function() {
                              printerSelectionPopup = new lightbox(null);
                              printerSelectionPopup.content = webContextPath + "/printerPreference.do?ajax=true";
                              printerSelectionPopup.activate();
                              return false;
                          }
                    }

				//104137 - unique-content needs new class after maximiseNavigation has been executed
				if (window.location.href.indexOf('maximiseNavigation') > 0) {
					menuHidden = $A(getElementsByClassName('unique-content-maximised'));
					if (menuHidden.length > 0) {
						menuHidden[0].className = 'unique-content';	
					}
				}

			});

/***************************************************************
************************** MENU SEARCH *************************
****************************************************************/
addLoadEvent(function() {
		searchBox = $('search');
		searchBox2 = $('search2');
		//Add clear event to search boxes
		if (searchBox)
			searchBox.onfocus = function() { this.value= ''; };
		if (searchBox2)
			searchBox2.onfocus = function() {this.value = ''; };

		//Override submit of Go buttons and form.onSubmit
		var menuSearchSubmitButton = $('menu-search-submit');
		if (menuSearchSubmitButton) {
			//SUBMIT button is child of P which is child of FORM
			menuSearchSubmitButton.parentNode.parentNode.onsubmit = function() {
										 	menuSearch($F('search'), '');
										 	return false;
										  };
		}
		var menuSearchSubmitButton2 = $('menu-search-submit2');
		if (menuSearchSubmitButton2) {
			menuSearchSubmitButton2.parentNode.parentNode.onsubmit = function() {
										 	menuSearch($F('search2'), $F('menu-search-hierarchy'));
										 	return false;
										  };
		}
		
		if (searchBox) {
			//Autocompleter for AJAX
			new Ajax.Autocompleter('search', 'search-autocomplete', webContextPath + '/menuSearch.do', {paramName: 'search', minChars: 2, updateElement:  menuSearchAutocompleteSelected, parameters: 'autocompleter=true'});
		}

});


function menuSearch(searchValue, searchHierarchy) {
	if (searchValue == '' || searchValue == 'Menu Search') {
		window.alert("Please enter something to search on");
	} else {
		var navigationDisplayStatus = $('scrollingMenuContainer').style.display;
		if (searchHierarchy != '') {
			$('menu-search-loading2').style.display = "inline";
			navigationDisplayStatus = $('scrollingMenuContainer2').style.display;
		} else
			$('menu-search-loading').style.display = "inline";

		//Incase they haven't pressed Clear, clear out the old search results
		if (navigationDisplayStatus == "none" || navigationDisplayStatus == ' '){
			var searchValueEscaped = '';
			var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
			for (var i = 0; i < searchValue.length; i++) {
		  		if (iChars.indexOf(searchValue.charAt(i)) != -1) {
					searchValueEscaped = searchValueEscaped + "\\" + searchValue.charAt(i);
				} else {
					searchValueEscaped = searchValueEscaped + searchValue.charAt(i);
				}
			}
			searchValue = searchValueEscaped;
			if (searchHierarchy != '') {
				Effect.toggle('search-results2', 'slide', {duration: .2});
				setTimeout("runSearch('" + searchValue + "', " + searchHierarchy+ ")", 1000);
			} else {
				Effect.toggle('search-results', 'slide', {duration: .2});
				setTimeout("runSearch('" + searchValue + "')", 1000);
			}
		} else {
			runSearch(searchValue, searchHierarchy);
		}
	}
}

function runSearch(searchValue, searchHierarchy) {
	var url = webContextPath + '/menuSearch.do';
	var params = 'search=' + searchValue;
	if (!searchHierarchy)
		searchHierarchy = ''; //second search becomes [undefined], so default it to ''
	if (searchHierarchy != '') {
		params = params + '&hierarchy=' + searchHierarchy;
	}

	var myAjax = new Ajax.Request(
	url,
	{
		method: 'get',
		parameters: params,
		onFailure: function(request) {
			var searchResultsArea = $('search-results') ;
			if (searchHierarchy != '')
				searchResultsArea = $('search-results2') ;
			searchResultsArea.innerHTML = "Error " + request.responseText;
			searchResultsArea.style.display = "block";
		}
		,
		onComplete: function(request) {
			var hierarchyChooser = "";
			if (searchHierarchy != '')
				hierarchyChooser = "2";
			var responseText = request.responseText;

			$('menu-search-loading' + hierarchyChooser).style.display = "none";
			var searchResultsArea = $('search-results' + hierarchyChooser);
			searchResultsArea.innerHTML = responseText;
			$('scrollingMenuContainer' + hierarchyChooser).style.display = 'none';

		  	 //Hide scrolling arrows as well (.scroll class is not recognised by IE, so much search by id)
			 hierarchyModifier = "";
			 if (searchHierarchy != '')
			 	hierarchyModifier = '2';

			 var scrollUpArrow = $('scroll-up-navigation' + hierarchyModifier);
			 var scrollDownArrow = $('scroll-down-navigation' + hierarchyModifier);
			 if (scrollUpArrow)
			 	scrollUpArrow.style.display = 'none';
			 if (scrollDownArrow)
			 	scrollDownArrow.style.display = 'none';

			//Create a clear link and append
			var clearLink = document.createElement('input');
			clearLink.setAttribute('value','Clear');
			clearLink.setAttribute('type','button');
			clearLink.setAttribute('class','button');
			clearLink.onclick= function () { clearSearch(searchHierarchy == ''); return false; };
			searchResultsArea.insertBefore(clearLink, searchResultsArea.childNodes[0]);

			Effect.toggle('search-results' + hierarchyChooser, 'slide');
		}
	});
}

function clearSearch(usingDefaultHierarchy){
	searchResultsPanel = 'search-results' + (usingDefaultHierarchy ? '' : '2');
	Effect.toggle(searchResultsPanel, 'slide', {duration: .2});
	$(searchResultsPanel).value = '';
	$('search' + (usingDefaultHierarchy ? '' : '2')).focus();

	//If there are scrolling arrows, don't use Effect.Slide as it will not position at the top of the list
	var scrollerFound = false;
	hierarchyModifier = "";
	if (!usingDefaultHierarchy)
		hierarchyModifier = '2';
	var scrollUpArrow = $('scroll-up-navigation' + hierarchyModifier);
	 var scrollDownArrow = $('scroll-down-navigation' + hierarchyModifier);
	 if (scrollUpArrow) {
		scrollUpArrow.style.display = 'block';
		scrollerFound = true;
	 }
	 if (scrollDownArrow)
		scrollDownArrow.style.display = 'block';

	if (scrollerFound)
		$('scrollingMenuContainer' + (usingDefaultHierarchy ? '' : '2')).style.display = 'block';
	else
		Effect.toggle('scrollingMenuContainer' + (usingDefaultHierarchy ? '' : '2'), 'slide');

}

/**
	After the user has clicked/<enter> an autocomplete suggestion, send them to that hyperlink.
	Had to override the autocompleter updateElement because the contents of the LI wasn't plain text.
*/
function menuSearchAutocompleteSelected(selectedItem) {
	itemContent = $A(selectedItem.getElementsByTagName('a'));
	if (itemContent.length > 0) {
		$('menu-search-loading').style.display = "inline";
		$('search').value = itemContent[0].innerHTML;
		location.href = itemContent[0].href;	
	}
}

/***************************************************************************
********************** HIDE/SHOW ENTIRE NAVIGATION *************************
****************************************************************************
1. Hide/Show the nav
 2. Alter the unique-content class
 3. Alter the title on the toggle-nav hyperlink
 4. Alter the image within toggle-nav
 5. Record in session the new state
 */
function toggleEntireMenuPanel(){
	if ($('site-access'))  { //wont appear if page has been fully refreshed
		Effect.toggle('site-access','appear');
		var toggleTab = $('toggle-nav');
		
		menuVisible = $A(getElementsByClassName('unique-content'));		
		menuHidden = $A(getElementsByClassName('unique-content-maximised'));
		if (menuHidden.length > 0) {
			menuHidden[0].className = 'unique-content';
			toggleTab.title = 'Hide Menu';
			var image = toggleTab.getElementsByTagName('img')[0];
			image.src = webContextPath + '/icons/nav-hide.gif';
			image.alt = 'Hide';
			var myAjax = new Ajax.Request(webContextPath + '/maximiseNavigation.do', {method: 'get'	});
		} else if (menuVisible.length > 0) {
			toggleTab.title = 'Show Menu';
			setTimeout("($A(getElementsByClassName('unique-content')))[0].className = 'unique-content-maximised'", 1000);
			var image = toggleTab.getElementsByTagName('img')[0];
			image.src = webContextPath + '/icons/nav-show.gif';
			image.alt = 'Show';
			var myAjax = new Ajax.Request(webContextPath + '/minimiseNavigation.do', {method: 'get'	});
		}
	} else {
		//use the full page refresh since the navigation has been lost during a refresh
		return true;
	}
	return false;
}
/***************************************************************************
************************ HIDE/SHOW PANEL AT A TIME *************************
****************************************************************************/
addLoadEvent(function() {
	var minmaxLinks = $A(getElementsByClassName('panel-min-max'));
	minmaxLinks.each( function(minmaxLink) {
						 minmaxLink.onclick = function() { return toggleIndividualPanel(this.id);  };
					});
	});

/*
	panelId will be in the form panel-min-max-4
	Hide any child of div.menu-group apart from H3 and p.menu-handlers
	Return true if you want the full page refresh version to run
*/
function toggleIndividualPanel(panelId) {
	var panelType = panelId.substring(14);
	url = webContextPath + '/togglePanel.do'
	//Update new state
	var myAjax = new Ajax.Request(url,	{
				method: 'get',
				parameters: "id=" + panelType,
				onFailure: function(request) { window.alert("Panel State could not be saved.\n" + request.responseText); }
				});

	if (panelType == "1") {
		if (toggleMenuPanel(""))
			return true;
	} else if (panelType == "2") {
		toggleHistoryPanel();
	} else if (panelType == "3") {
		toggleGenericPanel(2, $('siteaccesspanel_2').getElementsByTagName('div')[0], 'favourites','/userpreference/favouritesBody.jsp', 'Favourites' );
	} else if (panelType == "4") {
		toggleGenericPanel(4, $('siteaccesspanel_4').getElementsByTagName('div')[0], 'selectRoleForm', '/roles/change_role_tile.jsp', 'Role');
	} else if (panelType == "5") {
		if (toggleMenuPanel("2"))
			return true;
	}

	return false;
}



function toggleGenericPanel(panelType, panelContainer, specialId, uri, description){
	iconPanelType = panelType;
	if (specialId == 'favourites')
		iconPanelType ++;
	if ($('menu-group-data-' + panelType)) {
		Effect.toggle('menu-group-data-' + panelType, 'slide');
		toggleMaxMinHyperlinkAndImage(iconPanelType, ($(specialId).style.display == 'none'));
	} else if ($(specialId)) {
		Effect.toggle(specialId, 'slide');
		toggleMaxMinHyperlinkAndImage(iconPanelType, ($(specialId).style.display == 'none'));
	} else {
		getPanelDataFromServer(uri, panelType, description, panelContainer);
		toggleMaxMinHyperlinkAndImage(iconPanelType, true);
	}
}

function getPanelDataFromServer(uri, panelType, panelDescription, panelContainer) {
	loadingElement = buildLoadingImage();
	panelContainer.appendChild(loadingElement);

	var myAjax = new Ajax.Request(
			webContextPath + uri,
			{
				method: 'get',
				onFailure: function(request) {
					window.alert(panelDescription + " Panel could not be restored.\n" + request.responseText);
				},
				onComplete: function(request) {
					dataContainer = document.createElement('div');
					dataContainer.innerHTML = request.responseText;
					dataContainer.setAttribute('id', 'menu-group-data-' + panelType);
					dataContainer.style.display = 'none';
					panelContainer.appendChild(dataContainer);
					Effect.toggle('menu-group-data-' + panelType, 'slide');
					panelContainer.removeChild(loadingElement);
				}
			});
}
/*
	Toggle history has its own method as the LI#siteaccesspanel_3 is included historyTile.jsp
	and you need to extract just the UL#recentlyIsed from it
*/
function toggleHistoryPanel(){
	if ($('menu-group-data-3')) {
		Effect.toggle('menu-group-data-3', 'slide');
		toggleMaxMinHyperlinkAndImage(2, ($('menu-group-data-3').style.display == 'none'));
	} else if ($('recently-used')) {
		Effect.toggle('recently-used', 'slide');
		toggleMaxMinHyperlinkAndImage(2, ($('recently-used').style.display == 'none'));
	} else {
		loadingElement = buildLoadingImage();
		$('siteaccesspanel_3').getElementsByTagName('div')[0].appendChild(loadingElement);

		var myAjax = new Ajax.Request(
			webContextPath + '/navigation/historyTile.jsp',
			{
				method: 'get',
				parameters: 'hidePanelUp=false',
				onFailure: function(request) {
					window.alert("History Panel could not be restored.\n" + request.responseText);
				}
				,
				onComplete: function(request) {

					var newhtml = request.responseText;
					newhtml = newhtml.substring(newhtml.indexOf('<ul'), newhtml.indexOf('</ul>') + 5);
					dataContainer = document.createElement('div');
					dataContainer.innerHTML = newhtml;
					dataContainer.setAttribute('id', 'menu-group-data-3');
					dataContainer.style.display = 'none';

					var destinationDiv = $('siteaccesspanel_3').getElementsByTagName('div')[0];
					destinationDiv.appendChild(dataContainer);
					Effect.toggle('menu-group-data-3', 'slide');
					destinationDiv.removeChild(loadingElement);
				}
			});
		toggleMaxMinHyperlinkAndImage(2, true);
	}
}
//Re-apply javascript toggle and change image state
function toggleMaxMinHyperlinkAndImage(panelId, maximised) {
		toggleHyperlink = $('panel-min-max-' + panelId);
		if (toggleHyperlink) {
			toggleHyperlink.onclick = function() { toggleIndividualPanel(this.id); return false; };
			toggleHyperlink.title = maximised ? "Minimise Panel" : "MaximisePanel";
			toggleImage = toggleHyperlink.getElementsByTagName('img')[0];
			toggleImage.src = webContextPath + (maximised ? '/icons/minimise.gif' : '/icons/maximise.gif');
		}
}
function toggleMenuPanel(modifier){
	menuData = $('navigation' + modifier);
	searchData = $('menu-search' + modifier);
	if (menuData && searchData) {
		searchResults = $('search-results' + modifier);
		if (searchResults.getElementsByTagName('ul').length > 0 && searchResults.style.display != 'none') {
			//Only search results are visible, so only toggle them
			Effect.toggle('menu-search' + modifier, 'slide');
		} else {
			//Toggle the scroll container. It seems to exist regardless of whether there are scroll bars
			scroller = $('scrollingMenuContainer' + modifier);
			upScroll = $('scroll-up-navigation' + modifier);
			downScroll = $('scroll-down-navigation' + modifier);
			resetScroller(modifier);
			if (scroller) {
				Effect.toggle('scrollingMenuContainer' + modifier, 'slide');
			} //else
				//Effect.toggle('navigation' + modifier, 'slide');

			if (upScroll)
				Effect.toggle('scroll-up-navigation' + modifier, 'slide');
			if (downScroll)
				Effect.toggle('scroll-down-navigation' + modifier, 'slide');
			Effect.toggle('menu-search' + modifier, 'slide');
		}
		toggleMaxMinHyperlinkAndImage(modifier == "" ? 1 : 5, (searchData.style.display == 'none'));

	} else {
		//Data needs to be refreshed from server (too hard to pass the nodeNum)
		return true;
	}
	return false;
}
function buildLoadingImage(){
	loadingElement = document.createElement('img');
	loadingElement.setAttribute('src', webContextPath + '/icons/loading.gif');
	loadingElement.setAttribute('alt', 'loading');
	loadingElement.setAttribute('class', 'loading');
	loadingElement.setAttribute('id','temp-loading-image');
	loadingElement.style.display = 'inline';
	return loadingElement;
}
/***************************************************************************
****************************** MY FAVOURITES *******************************
****************************************************************************/
function addFavourite(fullPageRefreshUrl, isHeader) {
	url = fullPageRefreshUrl + ""; //convert to string
	pageId = url.substring(url.indexOf('pageID='), url.length);
	url = webContextPath + '/addToFavourites.do?' + pageId;
	if (isHeader)
		Effect.Fade('add-favourite');
	removeHistoryFavourite(pageId);

	var myAjax = new Ajax.Request(url,	{
				method: 'get',
				onFailure: function(request) {
					window.alert("There was an error adding the Favourite");
				},
				onComplete: function(response) {
					addFavouriteUpdate(response);
				}
				});
}
// Add the new Favourite to the list
function addFavouriteUpdate(request){

	var newFavouritesList = request.responseText;

	newFavouritesList = trimString(newFavouritesList);
	var existingFavourites = $('favourites').innerHTML;



	if (existingFavourites.indexOf("empty") > 0){ //No Favourites exist yet
		$('favourites').innerHTML = newFavouritesList;
	} else { //Add to existing favourites
		$('favourites').innerHTML = existingFavourites + newFavouritesList;
	}

	if (request.responseXML){
		var xmldoc = request.responseXML;
		var root_node = xmldoc.getElementsByTagName('li').item(0);
		var listItemID = root_node.getAttribute("id"); //ID will be of the format favourites_9999999
		var favouriteID = listItemID.substring(11, listItemID.length);

		new Effect.Highlight(listItemID, {startcolor:'#FF6699', endcolor:'#FFFFFF'})

		//Reapply all javascript modifications cause they have been wiped
		javascriptImageControls($('favourites'));

	} else {
		window.alert("Unable to display the new Favourite");
	}
}
function removeHistoryFavourite(pageId){
	var historyItemsWithFavourites = $A(getElementsByClassName('add-favourite'));
	historyItemsWithFavourites.each(function (hiwf) {
											  if (hiwf.href.indexOf(pageId) > 0)
											  		Effect.Fade(hiwf.id);
											  });
}
function deleteFavourite(fullPageRefreshUrl, parentListItem) {
	url = fullPageRefreshUrl + ""; //convert to string
	pageId = url.substring(url.indexOf('id='), url.length);
	url = webContextPath + '/deleteFavourite.do?' + pageId;
	//85230 put try/catch in for untrackable sporadic IE bug
	try {
		Effect.SlideUp(parentListItem);
	} catch (e) {
		$(parentListItem).style.display = 'none';
	}
	var myAjax = new Ajax.Request(url,	{
				method: 'get',
				onFailure: function(request) {
					window.alert("There was an error deleting the Favourite");
				},
				onComplete: function(response) {
					favsList = $('favourites');
					favsList.removeChild($(parentListItem));
					//check to see whether there are any other items in favs now - insert empty thing
					var countOfFavourites = favsList.getElementsByTagName('li').length;
					if (countOfFavourites == 0) {
						emptyListItem = document.createElement('li');
						emptyListItem.setAttribute('id', 'empty');
						emptyListItem.appendChild(document.createTextNode("You have no favourites recorded."));
						emptyListItem.style.display = 'none';
						favsList.appendChild(emptyListItem);
						Effect.BlindDown('empty');
					}
				}
				});
	return false;
}

//Remove the Move image control for Favourites.
//AJAX the Delete control for Favourites.
//Hide the Delete unless mouse over
function javascriptImageControls(favouritesList) {
	if (favouritesList) {
			favouriteListItems = $A(favouritesList.getElementsByTagName('li'));
			favouriteListItems.each(function (listItem) {
					//Find the Delete hyperlink
					controls = listItem.getElementsByTagName('a');
					for (var cnt = 0; cnt < controls.length; cnt++) {
						controlWidget = controls[cnt];
						if (controlWidget.href.indexOf('deleteFavourite') >= 0) {
							controlWidget.onclick = function() {
												return deleteFavourite(this, listItem.id);
											};
							controlWidget.style.display = 'none';
							var currentId = controlWidget.id;
							controlWidget.parentNode.onmouseover = function() {
								$(currentId).style.display = 'inline';
							};
							controlWidget.parentNode.onmouseout = function() {
								$(currentId).style.display = 'none';
							};
						} else if (controlWidget.href.indexOf('moveFavourite') >= 0) {
							controlWidget.style.display = 'none';
						}
					}
									});
	  }
}

/*****************************************************************
********************* HIDE/SHOW INSTRUCTIONS *********************
*****************************************************************/
function toggleInstructions(toggleLink) {

	var instructionsContent = $('instructions-content');
	var currentlyHidden = instructionsContent.className == 'instructions-toggle';

	//Update the class to visible immediately, but when hiding, don't update the class until after the Effect
	if (currentlyHidden)
		instructionsContent.className = 'instructions';

	Effect.toggle('instructions-content', 'blind', {duration: .5});

	toggleLink.setAttribute('title',(currentlyHidden ? 'Hide' : 'Show') + ' Instructions');
	var toggleImage = toggleLink.getElementsByTagName('img')[0];
	//toggleImage.src = webContextPath + '/icons/' + (currentlyHidden ? 'minimise' : 'maximise') + '.gif';
	toggleImage.setAttribute('src', (webContextPath + '/icons/' + (currentlyHidden ? 'minimise_negative' : 'maximise_negative') + '.gif'));
	toggleImage.alt = (currentlyHidden ? 'Hide' : 'Show') + ' Instructions';

	//Need time to give the Effect time to BlindUp
	if (!currentlyHidden)
		setTimeout("$('instructions-content').className = 'instructions-toggle'",600);

	var params = "show=" + currentlyHidden;
	var myAjax = new Ajax.Request(webContextPath + '/toggleInstructions.do',	{
				method: 'post',
				parameters: params,
				onFailure: function(request) {
					window.alert("There was an error storing the Instructions state.");
				}
				});
}
/*****************************************************************
**********************  PHONE BOOK SEARCH  ***********************
*****************************************************************/

addLoadEvent(function() {
		if ($('phonebook-results'))
	  	  $('phonebook-results').style.display = 'none';

		//Override submit of Go buttons
		phoneBookForm = $('phonebook-form');
		if (phoneBookForm)
			phoneBookForm.onsubmit = function() { phonebookSearch($F('phonebook-search')); return false;  };

		var menuSearchSubmitButton = $('phonebook-submit');
		if ($('phonebook-search'))
			$('phonebook-search').onfocus = function() { this.value= ''; };
});
function phonebookSearch(searchValue) {
	if (searchValue == '') {
		window.alert("Please enter a name to search on");
	} else {
		searchValue = searchValue.replace("'", "\\'");
		$('phonebook-loading').style.display = "inline";

		currentVisibility = $('phonebook-results').style.display;
		//Incase they haven't pressed Clear, clear out the old search results
		if (currentVisibility == "none" || currentVisibility == ' '){
				setTimeout("runPhoneBookSearch('" + searchValue + "')", 1000);
		} else {
			runPhoneBookSearch(searchValue);
		}
	}
}
function runPhoneBookSearch(searchValue) {
	var params = "search=" + searchValue;
	var myAjax = new Ajax.Request(webContextPath + '/quickPhonebook.do',	{
				method: 'post',
				parameters: params,
				onFailure: function(request) {
					alert("A problem has occurred.");
				},
				onComplete: function(response) {
					$('phonebook-loading').style.display = "none";
					var newText = response.responseText + '<input type="button" onClick="clearPhonebook(); return false;" value="Clear" class="button" />';
					$('phonebook-results').innerHTML = newText;
					Effect.SlideDown('phonebook-results');
				}
				});
}
function clearPhonebook(){
	var critBox = document.getElementById('phonebook-search');
	critBox.value='';
	Effect.SlideUp('phonebook-results');
}
function viewAvailability(indexId, display) {
	avail = $('availability-' +  indexId)
	if (display) {
		avail.style.display = 'block';
		avail.style.position = 'absolute';
	} else {
		avail.style.display = 'none';
		avail.style.position = 'relative';
	}
}
/*****************************************************************
*****************  ELECTRONIC DOCUMENT SEARCH  *******************
*****************************************************************/
addLoadEvent(function() {
		if ($('edm-results'))
	  	  $('edm-results').style.display = 'none';

		//Override submit of Go buttons
		var edmForm = $('edm-form');
		if (edmForm)
			edmForm.onsubmit = function() { return false; };

		var menuSearchSubmitButton = $('edm-submit');
		if (menuSearchSubmitButton) {
			menuSearchSubmitButton.onclick = function() {
					electronicDocumentServiceSearch($F('edm-search'), $('edm-modules'));
					return false;
				};
		}
		if ($('edm-search'))
			$('edm-search').onfocus = function() { this.value= ''; };
});
function electronicDocumentServiceSearch(searchValue, searchModule) {
	if (searchValue == '') {
		window.alert("Please enter a Document to search for.");
	} else if (searchModule && searchModule.value == '') {
		alert("Please select a module to search by");
	} else {
		searchValue = searchValue.replace("'", "\\'");
		if (!searchModule)
			searchModule = "";
		else
			searchModule = searchModule.value;
		$('edm-loading').style.display = "inline";

		currentVisibility = $('edm-results').style.display;
		//Incase they haven't pressed Clear, clear out the old search results
		if (currentVisibility == "none" || currentVisibility == ' '){
			setTimeout("runElectronicDocumentServiceSearch('" + searchValue + "','" + searchModule+ "')", 1000);
		} else {
			runElectronicDocumentServiceSearch(searchValue, searchModule);
		}
	}
}
function runElectronicDocumentServiceSearch(searchValue, searchModule) {
	var params = "search=" + searchValue + "&module=" + searchModule;
	var failed = false;
	var myAjax = new Ajax.Request(webContextPath + '/quickEDMSearch.do',	{
				method: 'post',
				parameters: params,
				onFailure: function(request) {
					$('edm-loading').style.display = "none";
					var newText = 'A problem has occurred.';
					$('edm-results').innerHTML = newText;
					Effect.SlideDown('edm-results');
					failed = true;
				},
				onComplete: function(response) {
					if (!failed) {
						$('edm-loading').style.display = "none";
						var newText = response.responseText + '<input type="button" onClick="clearEDM(); return false;" value="Clear" class="button" />';
						$('edm-results').innerHTML = newText;
						Effect.SlideDown('edm-results');
					}
				}
				});
}
function clearEDM(){
	Effect.SlideUp('edm-results');
}

/* ********** DEFAULT MENU NAVIGATION ********** */
function ajaxifyNavigationMenuItems() {
	var menuNodes = $A(getElementsByClassName('parent-node'));
	applyNavigationFunctionToMenuItem(menuNodes);

	menuNodes = $A(getElementsByClassName('nav-return'));
	applyNavigationFunctionToMenuItem(menuNodes);
	updateBreadcrumbs();
}

function applyNavigationFunctionToMenuItem(menuNodes) {
	menuNodes.each(function(nodeItem) {
		var nodeItemLink = nodeItem.getElementsByTagName('a')[0];
		if (nodeItemLink != null && nodeItemLink.id &&
			nodeItemLink.getAttribute("href").indexOf("start.do") > 0) {
			nodeItem.onclick = function() {
			var id = nodeItemLink.id.substring(5);
			displayChildNodesOnNavigationFor(id);
			return false;
			};
		}
	});
}

function displayChildNodesOnNavigationFor(menuItemSelected) {
	$('navigation').innerHTML = "";
	$('navigation').appendChild(buildLoadingImage());

	var scrollUpArrow = $('scroll-up-navigation');
	var scrollDownArrow = $('scroll-down-navigation');
	if (scrollUpArrow)
		$('scrollingMenuContainer').parentNode.removeChild(scrollUpArrow);
	if (scrollDownArrow)
		$('scrollingMenuContainer').parentNode.removeChild(scrollDownArrow);

	var myAjax = new Ajax.Request(webContextPath + '/navigateMenu.do?nodeNum=' + menuItemSelected,
			{
				method: 'get',
				onFailure: function(request) {
					$('navigation').innerHTML = "error with ajax request " + request.responseText;
				},
				onComplete: function(request) {
					Effect.SlideUp('navigation', {duration:0.1});
					setTimeout(function(){
						$('navigation').innerHTML = request.responseText;
						Effect.Appear('navigation');
						ajaxifyNavigationMenuItems();
						setupScrolling('navigation', 'scrollingMenuContainer');
						resetScroller('');
						}, 500);
				}
			});
}

function updateBreadcrumbs() {
	if (webContextPath != '') {
		var myAjax = new Ajax.Request(webContextPath + '/navigation/breadcrumbs.jsp?t=' + Math.random(),
				{
					method: 'get',
					onFailure: function(request) {
						$('breadcrumbs').innerHTML = "error with ajax request for navigation breadcrumbs";
					},
					onComplete: function(request) {
						if (!$('breadcrumbs')) {
							$('wrapper-main-content').insertBefore(buildBreadcrumbElement(), $('wrapper-main-content').firstChild);
						}
						$('breadcrumbs').innerHTML = request.responseText;
					}
			});
	}
}

function buildBreadcrumbElement() {
	breadcrumbElement = document.createElement('ul');
	breadcrumbElement.setAttribute('id', 'breadcrumbs');
	return breadcrumbElement;
}


function selectPrinter(form) {

    printer = 0;
    printerPrompt = false;

	//First, find out what printer is selected.
    for (var i = 0; i < form.printer.length; i++){
       if (form.printer[i].checked){
          printer = form.printer[i].value;
          break;
      }

   }

    //Confirm which printer to use on program launch?
    printerPrompt = form.confirmPrinterOnLaunch.checked;

    now = new Date();
    params = "ajax=true&saved=true&printer=" + printer + "&confirmPrinterOnLaunch=" + printerPrompt + "&time=" + now.getTime();

    myAjax = new Ajax.Request(webContextPath + '/printerPreferenceUpdate.do',
    {
        method: 'get',
        parameters: params,
        onFailure: function(request) {
          searchResultsArea.innerHTML = "Error " + request.responseText;
            return false;

        }
        ,
        onComplete: function(request) {
          $("quick-link-print").innerHTML = "Current Printer: " + request.responseText;
            printerSelectionPopup.deactivate();
            return false;
        }
    });
}
