/*
	Persistent search and main navigation JavaScript utilities
	Created 19 November 2008 by C Anderson
	
	28 April 2009: CDA - added functions to clear default text from text fields on rambler guide pages
*/

/*global variables - used by personalisation*/
var xmlHttp; 
var defaultLink = "<a href='http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/mypage/'>MyPage (not signed in)</a>";

function initPersonalisation() {
	// PERSONALISATION SWITCH
	
	// DO NOT SHOW PERSONALISATION HEADER FOR RECORDCOPYING AND A2A APPs
	/*27 November 2008 C Anderson
		Amended personalisation div name
		Removed date output 'else' clause
		Amended detection/matching of URLs for which to supress Personalisation
	*/
	/*2008_03_18 acurry.
		Note, recordCopying on Dev SHOULD include Personalisation as they have been integrated.
		Above Dev, RecordCopying should still exclude Personalisation until integration occurs.
	*/
	var PERSONALISATION_ACTIVE = true;
	var pageURL = document.location.href;
	var persArr = new Array("http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/recordcopying/", "http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/a2a/", "http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/ufos/")
	
	for(var i=0; i<persArr.length; i++) {
		if(pageURL.match(persArr[i]))
			PERSONALISATION_ACTIVE = false;
	}
	// rollback switch to false
	// var PERSONALISATION_ACTIVE = false; 
	
	var requestURL = 'http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/mypage/personalisation/personalisation.aspx'; 

	if (PERSONALISATION_ACTIVE)
	{
		//Read the requestURL 
		var url = requestURL;
		
		//Create the xmlHttp object to use in the request 
		//stateChangeHandler will fire when the state has changed, i.e. data is received back 
		// This is non-blocking (asynchronous)
		xmlHttp = GetXmlHttpObject(stateChangeHandler); 
		
		//Send the xmlHttp get to the specified url
		try
		{
			// display MyPage dynamic header
			xmlHttp_Get(xmlHttp, url); 
		}
		catch (e)
		{
			// provide a simple MyPage link
			document.getElementById('hdr-personalisation').innerHTML = defaultLink;
		}
	}
	else {
		// hide personalisation links completely
		var persDiv = document.getElementById("hdr-personalisation");
		persDiv.innerHTML = "&nbsp;";
	}
}

//stateChangeHandler will fire when the state has changed, i.e. data is received back 
// This is non-blocking (asynchronous) 
function stateChangeHandler() 
{ 
	//readyState of 4 or 'complete' represents that data has been returned 
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{ 
		//Gather the results from the callback 
		var str = xmlHttp.responseText;
		
		if(str.match("Server"))
			str = defaultLink;
		
		//write Personalisation header 
		document.getElementById('hdr-personalisation').innerHTML = str;
	} 
} 

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) 
{ 
	xmlhttp.open('GET', url, true); 
	xmlhttp.send(null); 
} 

function GetXmlHttpObject(handler)
{   
	var objXmlHttp = null;    //Holds the local xmlHTTP object instance
	var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
	var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
	var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
	//netscape, safari, mozilla behave the same??? 
	var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 

	//Depending on the browser, try to create the xmlHttp object 
	if (is_ie)
	{ 
	   //The object to create depends on version of IE 
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object 
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
		 
		//Attempt to create the object 
		try{ 
			objXmlHttp = new ActiveXObject(strObjName); 
			objXmlHttp.onreadystatechange = handler; 
		} 
		catch(e){ 
			//Object creation errored
			return;
		} 
	} 
	else if (is_opera){ 
		//Opera has some issues with xmlHttp object functionality 
		return;
	} 
	else{ 
		// Mozilla | Netscape | Safari 
		objXmlHttp = new XMLHttpRequest(); 
		objXmlHttp.onload = handler; 
		objXmlHttp.onerror = handler; 
	} 
	
	//Return the instantiated object 
	return objXmlHttp; 
}

function displayDate() {
	// simply generates a date in day:date:month format
	// looks for a header div called hdr-date-display
	// if the above div is found, writes the date to it
	
	var dateHolder = document.getElementById("hdr-date-display");
	if(dateHolder) {
		var d=new Date();
		var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
		var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
		var dateString = weekday[d.getDay()] + " " + d.getDate() + " " + monthname[d.getMonth()];

		dateHolder.innerHTML = dateString;
	}
}

function initMenu() {
	// initialise the menu for keyboard access
	// uses ye olde CSS/JavaScript class name change trick
	// when an element receives focus, its class name is changed to make it visible
	var el, li, x;
	el = document.getElementById("main-menu").getElementsByTagName("li");
	for (x in el) {
		li = el[x];

		// add hover functionality for ie6
		// (ie6 only applies :hover pseudoclass to links)
		li.onmouseover = openSubMenu;
		li.onmouseout = closeSubMenu;
		
		// add focus functionality for ie7
		// (ie7 does not implement addEventListener)
		li.onfocusin = openSubMenu;
		li.onfocusout = closeSubMenu;
		if (li.addEventListener) {  // focus for ff, safari, konquerer, etc.
			li.addEventListener('focus', openSubMenu, true);
			li.addEventListener('blur', closeSubMenu, true);
		}
	}
}

function openSubMenu() {
	// change the class name to force visibility
	this.className = "js-show";
}

function closeSubMenu() {
	if(/\bjs-show\b/.test(this.className))
		this.className = null;
}

function initSearch() {
	var hideSearch = false; // set this to true to hide the search form, or false to show it
	var searchField = document.getElementById("search_text");
	var searchDefaultText = "Search the archives";
	var searchLinkJsEnabled = "http://collections.europarchive.org/tna/20090615141934/http://www.nationalarchives.gov.uk/search/advanced_search.aspx?homepage=ad-search&javascriptenabled=True&j=t";
	var searchLink = document.getElementById("hdr-advanced-search");

	if (!hideSearch) {
		// attach default text highlight functionality to persistent search form field
		// (default text is highlighted when user clicks in field)
		if(searchField && searchField.value==searchDefaultText) {
			searchField.onfocus = function() {
				searchField.value="";
			}
		}
		
		// replaces the default link to Advanced Search 
		// default link includes querystring information indicating that JavaScript is disabled
		// this replaces that link with the one specified below (searchLinkJsEnabled)
		// the advanced search application will then know that JavaScript is enabled
		if(searchLink) {
			searchLink.href = searchLinkJsEnabled;
		}
	}
	else {
		var searchForm = document.getElementById("hdr-searchform-holder");
		searchForm.style.display="none";
	}
}

function extractPageName(hrefString) {
	// helper function for setPage()
	
	var arr = hrefString.split('/');
	
	return  (arr.length<2) ? hrefString : arr[arr.length-2].toLowerCase() + arr[arr.length-1].toLowerCase();               
}
	
function setActiveMenu(arr, crtPage) {
	// helper function for setPage()
	
	for (var i=0; i<arr.length; i++) {
		if(extractPageName(arr[i].href) == crtPage) {
			if (arr[i].className == "parent-link") {
				arr[i].className = "current";
			}
		}
	}
}
	
function setPage() {
	// works with extractPageName and setActiveMenu fucntions
	// highlights the top level menu item if the top level page is currently being viewed
	// eg. if about/default.htm is viewed, 'About us' remains highlighted on the main menu
	
	var hrefString = document.location.href ? document.location.href : document.location;
	
	if (document.getElementById("main-menu"))
		setActiveMenu(document.getElementById("main-menu").getElementsByTagName("a"), extractPageName(hrefString));
}

function initPageSearch() {
	// Clears text field default content on focus
	// Works on fields within the main body area
	// Uses function setFieldBehaviour
	
	// Create arrays of all input elements
	var inputsArray = document.getElementsByTagName("input");

	// for input fields - to clear clicked value
	if(inputsArray) {
		for(var i=0; i<inputsArray.length; i++) {
			// Manipulate only text fields in the main body area of 'rambler guides' pages
			// Exclude the header and catalogue search fields 
			if(inputsArray[i].type=="text" && inputsArray[i].className=="clear-on-select") {
				// Extract id attribute from each text field and pass it to the helper function
				var fieldID = inputsArray[i].id;
				setFieldBehaviour(fieldID);
			}	
		}
	}
}

function setFieldBehaviour(fid) {
	// Helper function for initPageSearch
	var textField = document.getElementById(fid);
	
	textField.onfocus = function() {
		textField.value="";
	}
}


function addLoadEvent(func) {
	// executes JavaScript functions after browser window has loaded
	// another copy of this function is used in content-rotate.js
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent(initSearch);
addLoadEvent(initMenu);
addLoadEvent(displayDate);
addLoadEvent(initPersonalisation);
addLoadEvent(setPage);
addLoadEvent(initPageSearch);

