/*
*	Library of JavaScript functions in use across TNA site(s)
*	Originally created September 2009 by Craig Anderson
*	If adding new or editing existing functions, please try to
*		1. add comment block for each function/function set (description, author's name + creation date, explanations)
*			1.1 where applicable/necessary, add explanatory inline comments (very helpful for complicated stuff!)
*		2. maintain consistent comment/code format
*		3. avoid duplicating functionality
*/
//====================================================================================//

/*
*	Facilitate execution of multiple functions when page loads
*	Originally created by Simon Willison (simonwillison.net)
*	Function calls take the following form:
*		addLoadEvent( functionName );
*	Function calls to be inserted at the foot of this file
*/


function addLoadEvent( func ) {
	var oldonload = window.onload;
	if ( typeof window.onload != 'function' ) {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

/*
*	JQuery collapsible div blocks for education landing (and other) pages
*	Based on 'slickbox', by Karl Swedberg (learningjquery.com)
*	Adapted for TNA September 2009 by Craig Anderson
*/
function initiateHideOrShow() {
	if ( typeof jQuery != 'undefined') {
	  // associate hideOrShow() function with the hide/show buttons
	  $(".hide-button").click(function() {
		  hideOrShow($(this));
	   });
	  
	  $(".show-button").click(function() {
		  hideOrShow($(this));
	   });
	  
	  // next lines cancel default link behaviour (prevents jumping to the top of the page)
	  $(".hide-button:a").click(function() {
		  return false;
	   });
	  
	  $(".show-button:a").click(function() {
		  return false;
	   });
	}
}

function hideOrShow(obj) {
	var hideButtonClass = "hide-button";
	var showButtonClass = "show-button";
	
	obj.toggleClass(hideButtonClass).toggleClass(showButtonClass);
	obj.siblings(".hide-or-show").toggle(400);
	return false;
}

function doInitialHide() {
	if ( typeof jQuery != 'undefined') {
		$(".hide-or-show.hidden").toggle(400);
		return false;
	}
}

/*
*	Dynamic facts/figures list generator
*	Originally created September 2009 by Craig Anderson
*	Reads the from facts-figures.xml and randomly selects a defined number of entries to display in appropriate facts and figures list
*	Relies upon helper function doRandomPopSort() for the random selection
*/
function writeListFromXMLDoc() {
	// first check that the facts/figures list element exists - it is not on all pages
	/* COMMENTED OUT TO PREVENT TEST DATA APPEARING ON LIVE SITE / ERRORS IN IE
	if( document.getElementById( "facts-figures" ) ) {
	  var listLength = 4; //this is the number of items we want to display in the list
	  var familyMember; // will identify which of the family of websites we are on
	  var xmlDoc;
	  var temp;
	  var elemArray = new Array();
	  var outputString = "";
	  
	  familyMember = document.getElementById( "sub-menu-wrapper" ).className;
	  
	  // modern, decent, non-IE6 browsers
	  if ( window.XMLHttpRequest ) {
		  xmlDoc = new window.XMLHttpRequest();
		  xmlDoc.open( "GET", "/xml/facts-figures.xml", false );
		  xmlDoc.send( "" );
		  xmlDoc=xmlDoc.responseXML;
	  }
	  
	  // IE 6
	  else try {
		  xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		  xmlDoc.async = false;
		  xmlDoc.load( "/xml/facts-figures.xml" );
	  }
	  
	  // catch unknown browser error - prevent a JavaScript error being thrown
	  catch(e) {
		  // something bizarre has happened - run away
	   }
  
		if(xmlDoc) {
			temp = xmlDoc.getElementsByTagName( "listItem" );
		}
		else {
			return false;
		}
	  //instatiate the extra counter for the elemArray for loop
	  var j=0;
	  for( i=0; i<temp.length; i++ ) {
		  // select all list items with the same family as the page
		  if( temp[i].getElementsByTagName( "category" )[0].childNodes[0].nodeValue.toLowerCase() == familyMember ) {
			  //add to elemArray array
			  elemArray[j] = temp[i];
			  //increase the count of the new array
			  j++;
		  }
	  }
	  
	  elemArray = doRandomSortPop( elemArray, listLength )
  
	  // create the output string
	  for ( i=0; i<elemArray.length; i++ ) {
		  var itemURL;
		  
		  // only output facts/figures associated with this website family member
		  outputString += "<li>";
		  outputString += "<div class=\"fact-title\">";
		  outputString += elemArray[i].getElementsByTagName( "figure" )[0].childNodes[0].nodeValue;
		  outputString += "</div>" ;
		  outputString += "<div class=\"fact-description\">";
		  try {
			  itemURL = elemArray[i].getElementsByTagName( "url" )[0].childNodes[0].nodeValue;
		  }
		  catch(e) {
			// no URL present
			itemURL = "undefined";
		  }
		  if ( itemURL != "undefined" ) {
			  outputString += "<a href=\"" + itemURL + "\">";
			  outputString += elemArray[i].getElementsByTagName( "fact" )[0].childNodes[0].nodeValue;
			  outputString += "</a>";
		  }
		  else {
			  outputString += elemArray[i].getElementsByTagName( "fact" )[0].childNodes[0].nodeValue;
		  }
		  outputString += ( "</div>" );
		  outputString += ( "</li>" );
	  }
	  
	  // write the output string to the document
	  document.getElementById( "facts-figures" ).innerHTML = outputString;
	}*/
	if( document.getElementById( "your-archives-feed" ) ) {
	  var listLength = 5; //this is the number of items we want to display in the list
	  var familyMember; // will identify which of the family of websites we are on
	  var xmlDoc;
	  var temp;
	  var elemArray = new Array();
	  var outputString = "";
	  
	  familyMember = document.getElementById( "sub-menu-wrapper" ).className;
	  
		// set a variable to the path of the xml
		var XMLurl = "/xml/your-archives-twitter.xml";
		
		// get XML in
		// modern, decent, non-IE6 browsers
		if ( window.XMLHttpRequest ) {
		  try {
			  xmlDoc = new window.XMLHttpRequest();
			  xmlDoc.open( "GET", XMLurl, false );			  
			  xmlDoc.send( "" );
			  xmlDoc=xmlDoc.responseXML;
			  }
		  catch(e) {
		  // something bizarre has happened - run away
		  }
		}	  
		// IE 6
		else try {
		  xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		  xmlDoc.async = false;
		  xmlDoc.load( XMLurl );
		}
		// catch unknown browser error - prevent a JavaScript error being thrown
		catch(e) {
		// something bizarre has happened - run away
		}
		
		// see if the xml has loaded ok, if has continue with function
		try {
			 temp = xmlDoc.getElementsByTagName( "item" );
		  
		  // just populate array with the number of required items from top of list
		  j=0;
		  for( i=0; i<temp.length; i++ ) {
			  // select all list items with the same family as the page
			  if((temp[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue.substring(26,0) == "YourArchives: New article:") || (temp[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue.substring(22,0) == "YourArchives: Article:")) {
				  elemArray[j] = temp[i];
				  //increase the count of the new array
				  j++;
			  }
		  }
		  if(listLength <= elemArray.length){
			var rightLength = listLength;
		  } else {
			var rightLength = elemArray.length ;
		  }
		  // create the output string
		  outputString += "<ul id=\"your-archives-feed\" class=\"small-main-list\">";
		  for ( i=0; i<rightLength; i++ ) {
			  // use a regExp to find the link in the Tweet text
			  var feedLink = /http.*\s/.exec(elemArray[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue);
			  // use a regExp to delete all text from the link onwards (to remove repetition)
			  var feedText = elemArray[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue.replace(/\s\http.*/,'');
			  // use another regExp to remove 'YourArchives: New article'
			  feedText = feedText.replace(/.*Article:\s/,'');
			  // get all items in elemArray
			  outputString += "<li>";
			  outputString += "<a class=\"black-link\" href=\"";
			  outputString += feedLink;
			  outputString += "\">";
			  outputString += feedText;
			  outputString += "<span class=\"red-arrow\"></span><\a>";
			  outputString += "</li>";
		  }
		  outputString += "</ul>";
		  
		  // write the output string to the document - in this case a 'span' tag
			 document.getElementById( "your-archives-feed" ).innerHTML = outputString;
		}
		// if xml has not loaded ok - run away
	  catch(e) {
		  //alert(e);
	  }
	}
	
	if( document.getElementById( "video-holder" ) ) {//video-holder is unique to the Understand the Archives landing page
	  var listLength = 1; //this is the number of items we want to display in the list
	  var familyMember; // will identify which of the family of websites we are on
	  var xmlDoc;
	  var temp;
	  var elemArray = new Array();
	  var outputStringTitle = ""; //for title section
	  var outputStringIntro = ""; //for intro html and video description
	  var outputStringFile = ""; //for file of video
	  var outputStringImage = ""; //for image of video
	  var outputStringCaption = ""; //for captions of video
	  var outputStringResources = ""; //for resources section
	  var outputStringTranscript = ""; //for transcript section
	  
	  //familyMember = document.getElementById( "sub-menu-wrapper" ).className;
	  
	  var XMLurl = "/xml/animated-guide-videos.xml";
	  
	  // get XML in
		// modern, decent, non-IE6 browsers
		if ( window.XMLHttpRequest ) {
		  try {
			  xmlDoc = new window.XMLHttpRequest();
			  xmlDoc.open( "GET", XMLurl, false );			  
			  xmlDoc.send( "" );
			  xmlDoc=xmlDoc.responseXML;
			  }
		  catch(e) {
		  // something bizarre has happened - run away
		  }
		}	  
		// IE 6
		else try {
		  xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		  xmlDoc.async = false;
		  xmlDoc.load( XMLurl );
		}
		// catch unknown browser error - prevent a JavaScript error being thrown
		catch(e) {
		// something bizarre has happened - run away
		}
		
		// see if the xml has loaded ok, if has continue with function
		try {
 	  		temp = xmlDoc.getElementsByTagName( "listItem" );
			//instatiate the extra counter for the elemArray for loop
			var j=0;
			for( i=0; i<temp.length; i++ ) {
			  // select all list items with the same family as the page
			  if( temp[i].getElementsByTagName( "category" )[0].childNodes[0].nodeValue.toLowerCase() == "records" ) {
				  //add to elemArray array
				  elemArray[j] = temp[i];
				  //increase the count of the new array
				  j++;
			  }
			}
			
			elemArray = doRandomSortPop( elemArray, listLength )
			
			
			// create the output strings
			for ( i=0; i<elemArray.length; i++ ) {
			  
			  // get all items in elemArray
			  outputStringTitle += elemArray[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue;
			  outputStringIntro += elemArray[i].getElementsByTagName( "intro" )[0].childNodes[0].nodeValue;
			  outputStringFile += elemArray[i].getElementsByTagName( "file" )[0].childNodes[0].nodeValue;
			  outputStringImage += elemArray[i].getElementsByTagName( "image" )[0].childNodes[0].nodeValue;
			  outputStringCaption += elemArray[i].getElementsByTagName( "captionFile" )[0].childNodes[0].nodeValue;
			  outputStringResources += "<h3>Resources</h3><p>" + elemArray[i].getElementsByTagName( "resource1" )[0].childNodes[0].nodeValue +"</p>";
			  outputStringResources += "<p>" + elemArray[i].getElementsByTagName( "resource2" )[0].childNodes[0].nodeValue + "</p>";
			  outputStringTranscript += "<h3>Transcript</h3>" + elemArray[i].getElementsByTagName( "transcript" )[0].childNodes[0].nodeValue;
			}
			// write the output string to the document
			document.getElementById( "video-title" ).innerHTML = outputStringTitle;
			document.getElementById( "video-intro" ).innerHTML = outputStringIntro;
			document.getElementById( "video-resources" ).innerHTML = outputStringResources;
			document.getElementById( "video-transcript" ).innerHTML = outputStringTranscript;
			
			// overwrite the swfobject already on the page with the random video details
			// d-related resources version commented out
			//var flashvars = {file:outputStringFile,image:outputStringImage,title:outputStringTitle,author:'The National Archives',description:outputStringIntro,stretching:'',logo:'','plugins':'captions-1,drelated-1','captions.fontsize':'12','captions.state':'true','captions.back':'true','captions.file':encodeURIComponent(outputStringCaption),'drelated.dxmlpath':'/script/animated-guides-relatedresources.xml','drelated.dposition':'center','drelated.dskin':	'/swf/drelate-tna-skin.swf','drelated.dtarget': '_parent'};
			var flashvars = {file:outputStringFile,image:outputStringImage,title:outputStringTitle,author:'The National Archives',description:outputStringIntro,stretching:'',logo:'','plugins':'captions-1','captions.fontsize':'12','captions.state':'true','captions.back':'true','captions.file':encodeURIComponent(outputStringCaption)};
			var params = {allowfullscreen:'true',allowscriptaccess:'always',wmode:'transparent'};
			var attributes = {id:'player',name:'player'};
			swfobject.embedSWF("/swf/player.swf", "player", "600", "486", "9.0.0", false, flashvars, params, attributes);
			}
		// if xml has not loaded ok - run away
	  catch(e) {
		  //alert(e);
	  	}
	} 
	  
	if( document.getElementById( "video-holder-small" ) ) {//video-holder is unique to the Understand the Archives landing page
	  var listLength = 1; //this is the number of items we want to display in the list
	  var familyMember; // will identify which of the family of websites we are on
	  var xmlDoc;
	  var temp;
	  var elemArray = new Array();
	  var outputStringTitle = ""; //for title section
	  var outputStringIntro = ""; //for intro html and video description
	  var outputStringFile = ""; //for file of video
	  var outputStringImage = ""; //for image of video
	  var outputStringCaption = ""; //for captions of video
	  
	  familyMember = document.getElementById( "sub-menu-wrapper" ).className;
	  
	  var XMLurl = "/xml/animated-guide-videos.xml";
	  
	  // get XML in
		// modern, decent, non-IE6 browsers
		if ( window.XMLHttpRequest ) {
		  try {
			  xmlDoc = new window.XMLHttpRequest();
			  xmlDoc.open( "GET", XMLurl, false );			  
			  xmlDoc.send( "" );
			  xmlDoc=xmlDoc.responseXML;
			  }
		  catch(e) {
		  // something bizarre has happened - run away
		  }
		}	  
		// IE 6
		else try {
		  xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
		  xmlDoc.async = false;
		  xmlDoc.load( XMLurl );
		}
		// catch unknown browser error - prevent a JavaScript error being thrown
		catch(e) {
		// something bizarre has happened - run away
		}
		
		// see if the xml has loaded ok, if has continue with function
		try {	  
			temp = xmlDoc.getElementsByTagName( "listItem" );
			//instatiate the extra counter for the elemArray for loop
			var j=0;
			for( i=0; i<temp.length; i++ ) {
			  // select all list items with the same family as the page
			  if( temp[i].getElementsByTagName( "category" )[0].childNodes[0].nodeValue.toLowerCase() == familyMember ) {
				  //add to elemArray array
				  elemArray[j] = temp[i];
				  //increase the count of the new array
				  j++;
			  }
			}
			
			elemArray = doRandomSortPop( elemArray, listLength )
			
			
			// create the output strings
			for ( i=0; i<elemArray.length; i++ ) {
			  
			  // get all items in elemArray
			  outputStringTitle += elemArray[i].getElementsByTagName( "title" )[0].childNodes[0].nodeValue;
			  outputStringIntro += elemArray[i].getElementsByTagName( "intro" )[0].childNodes[0].nodeValue;
			  outputStringFile += elemArray[i].getElementsByTagName( "file" )[0].childNodes[0].nodeValue;
			  outputStringImage += elemArray[i].getElementsByTagName( "image" )[0].childNodes[0].nodeValue;
			  outputStringCaption += elemArray[i].getElementsByTagName( "captionFile" )[0].childNodes[0].nodeValue;
			}
			// write the output string to the document
			document.getElementById( "video-title-small" ).innerHTML = outputStringTitle;
			document.getElementById( "video-intro-small" ).innerHTML = outputStringIntro;
			
			// overwrite the swfobject already on the page with the random video details
			var flashvars = {file:outputStringFile,image:outputStringImage,title:outputStringTitle,author:'The National Archives',description:outputStringIntro,stretching:'exactfit',logo:'/images/video/tna-logo.png','plugins':'captions-1','captions.fontsize':'18','captions.state':'false','captions.back':'true','captions.file':encodeURIComponent(outputStringCaption)};
			var params = {allowfullscreen:'true',allowscriptaccess:'always',wmode:'transparent'};
			var attributes = {id:'player',name:'player'};
			swfobject.embedSWF("/swf/player.swf", "player", "278", "175", "9.0.124", false, flashvars, params, attributes);
		}
		// if xml has not loaded ok - run away
		catch(e){
			//alert(e);
	  	}
	}
}
/*
*	Helper function for writeListFromXMLDoc()
*	Originally created September 2009 by Craig Anderson
*	Receives 2 arguments; an array of list items and a value indicating the desired list length
*/
function doRandomSortPop( theArray, requiredLength ) {
	var newArray = new Array();
	
	for( x=0; x<requiredLength; x++ ) {
		// randomly sort the array, take out (pop) the top item, add it to the new array
		theArray.sort( function() { return 0.5 - Math.random() } );
		// with each iteration another randomly selected item is added to newArray
		newArray[x] = theArray.pop();
	}
	
	// return the new array of randomly selected items to the calling function
	return newArray;
}

/*	Random number generator
*	Originally created September 2009 by Craig Anderson
*	Can be called with one or two arguments
*	Returns a random integer between the upper and lower limit (range)
*	By default the range would include 0, which is fine for dealing with arrays, but not if we don't want a zero value!
*	To return only non-zero results, pass a lower limit of 1 (or greater)
*/
function generateRandom( upperLimit, lowerLimit ) {
	if( typeof lowerLimit != 'undefined' ) {
		// we have a lower limit - therefore we do not want 0 returned
		var lower, upper;
		
		lower = lowerLimit;
		upper = upperLimit;
	
		// perform a simple check that the arguments have been passed in the right order (i.e. upper is greater than lower!)
		// if they are in the wrong order, just swap them
		if( lower > upper ) {
			lower = upperLimit;
			upper = lowerLimit;
		}
		 if( lower == upper ) {
			 lowerLimit = 0;
		 }
	}
	else {
		lowerLimit = 0;
	}

	return lowerLimit + Math.floor( Math.random( Math.random() ) * upperLimit );
}

/* 1911 census link function
* Originally created 15 October 2009 by Craig Anderson
* Rewritten 09 February 2010 by Craig Anderson
* When census records page is loaded, checks to see whether it is being viewed within a frameset
* A frameset most likely indicates the page is being viewed from within the reading rooms
* If so, the link to 1911census.co.uk is changed to the correct value for use within TNA
* There is no security risk associated with the alternate URL, as it is meaningless outside of TNA
*/

function do1911LinkCheck() {
	if(document.getElementById("link1911") && self.location!=top.location) {
		var censusLink = document.getElementById("link1911");
		var kewCensusLink = "http://kew.1911census.co.uk/registerlogin.aspx";
	
		censusLink.href=kewCensusLink;
	}
}

addLoadEvent( writeListFromXMLDoc );
addLoadEvent( initiateHideOrShow );
addLoadEvent( doInitialHide );
addLoadEvent( do1911LinkCheck );

$(function(){
    $('#quotes li:gt(0)').hide();
    setInterval(function(){
      $('.#quotes li:first-child').fadeOut()
         .next('li').fadeIn()
         .end().appendTo('#quotes');}, 
      9000);
});



