function addLoadEvent(func){
	var oldonload = window.onload;
	if(typeof window.onload != 'function'){
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

// ============================ GLOBAL VARIABLES ==============================================================

var _register = 0; // bit to determine if the user is 
var _searchPg = 0; // bit to determine if user is going to search results page after clicking the search enter btn
var _verity = 0;

// ============================ GLOBAL VARIABLES ==============================================================


// ============================ ONLOAD FUNCTIONS ==============================================================

addLoadEvent(getHTTPObject);
addLoadEvent(setAjaxDivisions);

/*if (document.getElementById('searchResultsLink')){turnDisplayOn (document.getElementById('searchResultsLink'));}
if (document.getElementById("bottomNavigation")){turnDisplayOn (document.getElementById("bottomNavigation"));}
if (document.getElementById("ajaxBlockLeftLink")){turnDisplayOn (document.getElementById("ajaxBlockLeftLink"));}
if (document.getElementById("ajaxBlockRightLink")){turnDisplayOn (document.getElementById("ajaxBlockRightLink"));}
*/
// ============================ AJAX FUNCTIONS ==============================================================

// Find out if there is a suppor for Ajax across all browsers
// by Jerremy Keith

function getHTTPObject() 
{
	var xhr = false;
	if(window.XMLHttpRequest) 
	{
		// If IE7, Mozilla, Safari, etc: Use native object
		xhr = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		try 
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
			//xhr.async = false;
		} 
		catch(e) 
		{
				try 
				{
					// ActiveX control for IE6
					xhr = new ActiveXObject("Microsoft.XMLHTTP");
				} 
				catch(e) 
				{
					xhr = false;
				}	
		}
	}
		return xhr;
}


// Grab the file - this link target - and insert it into displayResponse function
function grabFile(file, linkID) 
{
	// make the ajax loader gif file visible
	turnDisplayOn(document.getElementById('ajaxLoaderImg'));
	
	// determine if a link was clicked in the search results so that the 'Back to Search Results' button is visible
	if (linkID == 'verity')
	{
		turnDisplayOn(document.getElementById('searchResultsLink'));
		_verity = 1; // used to manually input data for LINK1 on breadcrumb
	}
	else
	{
		turnDisplayOff(document.getElementById('searchResultsLink'));
		_verity = 0;
	}
	
	if (linkID == "ajaxBlockRightLink" || linkID == "ajaxBlockBottomRightLink")
	{
		getNextPages('ajaxBlockContent');
		
		// LOG: 04.06.2008 by Roman - fixed the IE7 problem
		// _timer = setTimeout('setCookie()', 500);		
	}
	else if (linkID == "ajaxBlockLeftLink" || linkID == "ajaxBlockBottomLeftLink") 
	{
		getPrevPage();

		// LOG: 04.06.2008 by Roman - fixed the IE7 problem
		// _timer = setTimeout('setCookie()', 500);
	}
	else
	{
		if (_pgID != "")
		{
			// check if the url (file) sent contains '?pgID='
			if (file.substring(file.indexOf('?'), (file.indexOf('=') + 1)) == '?pgID=')
			{
				// if true, grab the directory
				file = file.substring((file.indexOf('=') + 1), file.indexOf('/'));
			}
			else
			{
				file = file.substring(file.indexOf('=') + 1);		
			}
		}
		else if (file)
		{
			if (file.substring(file.indexOf('?'), (file.indexOf('=') + 1)) == '?pgID=')
			{				
				file = file.substring(file.indexOf('=') + 1);
			}
		}
		
		//alert(file);
		
		// once all url formatting has been applied, extract the chapter name after hash symbol
		// first check to see that the file url has a hash sign, if so, it has a chapter name following the £
		if (file.indexOf('$') > -1)
		{			
			var chapterName = file.substring(file.indexOf('$') + 1);
			
			if (chapterName != "") {setCurChapter(chapterName); };
			
			file = file.substring(0, file.indexOf('$')); 
			
			switch (chapterName)
			{
				case 'startShortlisting':
					document.getElementById('bradcrumbLink1').innerHTML = '<a title="Start Shortlisting" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aaaba__1_your_choice_start_here.cfm$startShortlisting\')">Start Shortlisting</a>';
					break;
				case 'searchLists':
					document.getElementById('bradcrumbLink1').innerHTML = '<a title="Search Lists" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aacm__abyda__search_lists.cfm$searchLists\')">Search Lists</a>';
					break;
				case 'gettingIn':
					document.getElementById('bradcrumbLink1').innerHTML = '<a title="Getting in &amp; Surviving there" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abab__191_getting_in_and_surviving_there.cfm$gettingIn\')">Getting In</a>';
					break;
				case 'whereToStudy':
					document.getElementById('bradcrumbLink1').innerHTML = '<a title="Where to Study" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abeb__351_where_to_study.cfm$whereToStudy\')">Where To Study</a>';
					break;
				default:
					// do nothin

			}
		}
		
		if (_verity == 1)
		{
			document.getElementById('bradcrumbLink1').innerHTML = 'University Search';
		}
		
		// do not try to decipher what page index it is if a search is being done
		if (file.substr(0, 6) != 'verity')
		{		
			// call to method which deciphers which index to give the global _currentPageIndex in nav.js for the prev/next buttons
			decipherPageIndex(file, 'ajaxBlockContent');
			_searchPg = 0;
		}
		else
		{
			_searchPg = 1;
		}
		
		if (file != undefined)
		{
			// check to see if the user has clicked a button with the 'register' prefix to avoid an overlay of content in the response function
			if (file.substr(0, 6) == 'regist')
			{
				_register = 1;
			}
			else
			{
				_register = 0;
			}
		}
									 
		
		var request = getHTTPObject();
		
		//request.CacheControl = "no-cache"
		
		if (request) 
		{					
			request.onreadystatechange = function() 
										 {
											 displayResponse(request);
										 }; 			
			
			request.open("GET", file, true); 
			
			request.send(null); //alert("ie7");
		}
		
		// reset the javascript url parameter to nothing
		_pgID = "";
		_sID = "";
	}
	
	getSubChapterBreadcrumb(file);
}

function getSubChapterBreadcrumb(file)
{
	//alert(file);
	// get the subchapter of this file for the breadcrumbs
	var numList = "0123456789";
	var numberStr = "";
	var fileName = file.substring(file.indexOf('/') + 1);
	
	//alert(fileName);
	
	// loop through the actual html file name extracting the double digit number in the file name and appending it to a string
	for (var i = 0; i < fileName.length - 8; i++)
	{
		for (var x = 0; x < numList.length; x++)
		{
			if (fileName.charAt(i) == numList.charAt(x))
			{
				numberStr += fileName.charAt(i);
			}
		}
	}
	
	if (numberStr != "")
	{
		// convert the extracted number string to an int
		var num = parseInt(numberStr);
		var subChapter = "";
		
		if (num >= 20 && num <= 49)
		{			
			// subject and courses shortlist
			subChapter = '<a title="Points to consider" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aaabb__22_points_to_consider_1.html$startShortlisting\')">Subject &amp; Courses Shortlist</a>';
		}
		else if (num >= 50 && num <= 68)
		{
			// university shortlist
			subChapter = '<a title="University Shortlist" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aabba__50_university_shortlist_1.html$startShortlisting\')">University Shortlist</a>';
		}
		else if (num >= 69 && num <= 73)
		{
			// get more detail
			subChapter = '<a title="Get More Detail" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aabsa__69_get_more_detail_1.html$startShortlisting\')">Get more Detail</a>';
		}
		else if (num >= 74 && num <= 79)
		{
			// entrance requirements & offers
			subChapter = '<a title="Entrance Requirements &amp; Offers" href="javascript:grabFile(\'search_results.cfm?pgID=Content/aabwa__74_entrance_requirements_offers_1.html$startShortlisting\')">Entrace Requirements &amp; Offers</a>';
		}
		else if (num >= 80 && num <= 88)
		{
			// and if...
			subChapter = '<a title="And if ..." href="javascript:grabFile(\'search_results.cfm?pgID=Content/aacca__80_and_if_1.html$startShortlisting\')">And If...</a>';
		}
		else if (num >= 192 && num <= 215)
		{
			// how to apply
			subChapter = '<a title="How to apply" href="javascript:grabFile(\'search_results.cfm?pgID=Content/ababa__192_how_to_apply_1.html$gettingIn\')">How to Apply</a>';
		}
		else if (num >= 216 && num <= 233)
		{
			// cash for courses
			subChapter = '<a title="Cash for Courses" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abaoza__216_cas_ for_courses_1.html$gettingIn\')">Cash for Courses</a>';
		}
		else if (num >= 234 && num <= 285)
		{
			// surviving your first year a-z
			subChapter = '<a title="Surviving Your First Year A-Z" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abbea__234_surviving_your_first_year_1.html$gettingIn\')">Surviving Your First Year A-Z</a>';
		}
		else if (num >= 286 && num <= 291)
		{
			// gap years & long summers
			subChapter = '<a title="Gap Years &amp; Long Summers" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abdea__286_gap_years_long_summers_1.html$gettingIn\')">Gap Years &amp; Long Summers</a>';
		}
		else if (num >= 511 && num <= 1222)
		{
			// university profiles
			subChapter = '<a title="University &amp; College Profiles" href="javascript:grabFile(\'search_results.cfm?pgID=Content/abfaa__university_list.cfm$whereToStudy\')">University Profiles</a>';
		}
		
		document.getElementById('bradcrumbLink2').innerHTML = subChapter;
	}
	else
	{
		document.getElementById('bradcrumbLink2').innerHTML = "";
	}
}

var _timer = null;

function displayResponseRest()
{		
		callAjax ("yourChoiceListB"); 			// Main section in your_choice_start_here.cfm		
		callAjax ("categoriesBlock");			// Main section in how_to_shortlist_1.html	
		
		// Define the elements which has to be removed when the ajax content loads
		var removeDiv = document.getElementById("searchBlock");
		
		if (removeDiv) {
			removeElement (removeDiv);
		}

		var uniblock = document.getElementById("uniBlock");
		var categoryContent = document.getElementById("categoryContent");
		var bottomNavigation = document.getElementById("bottomNavigation");
		var searchResultsLink = document.getElementById("searchResultsLink");
		var registerFormContent = document.getElementById("registerFormContent");
		var azblock = document.getElementById("azBlock");
		var categoriesblock = document.getElementById("categoriesBlock");

		// Links left and right around the main ajax area
		var backLink = document.getElementById("ajaxBlockLeftLink");
		var nextLink = document.getElementById("ajaxBlockRightLink");


		// when the Universities Search results are displayed then show the bottom navigation
		// show the "back to search results" link as well
		if (uniblock) {
			turnDisplayOn (bottomNavigation);
			if (_lIn == 1){ turnDisplayOn (searchResultsLink); }
		}
		
		// define the elements for which the "back to search results" navigation should not be displayed
		else if (categoryContent || azblock || categoriesblock) {
			//turnDisplayOff (searchResultsLink);
			turnDisplayOn (bottomNavigation);
			turnDisplayOn (backLink);
			turnDisplayOn (nextLink);
		}

		// define the elements for which the "back to search results" &  "the side arrows"  & "the bottom" navigation should not be displayed
		else if (registerFormContent) {
			//turnDisplayOff (searchResultsLink);
			turnDisplayOff (bottomNavigation);	
			turnDisplayOff (backLink);
			turnDisplayOff (nextLink);						
		}
		
		// hide loader once content has finished loading
		turnDisplayOff(document.getElementById('ajaxLoaderImg'));
		_timer = setTimeout('timerHandler()', 500);	
}


// Insert the file comming from gragFile function into the specified division - ajaxBlock -
function displayResponse(request) 
{ 			
			
	if(request.readyState == 4) 
	{ 
		var ajaxBlock = document.getElementById("ajaxBlockContent");
		var content = request.responseText;
		
		// breadcrumb handling
		if (content.indexOf('<title>'))
		{
			var titleContent = content.substring(content.indexOf('<title>') + 7, content.indexOf('</title>'));	
			
			if (titleContent != "Search lists" || document.getElementById('bradcrumbLink2').innerHTML != "")
			{
				document.getElementById('bradcrumbLink3').innerHTML = "<b>" + titleContent + "</b>";
			}
			else if (titleContent == "Search lists" || document.getElementById('bradcrumbLink2').innerHTML == "")
			{
				var index1 = content.indexOf('<h2 id=');
				
				var h2Text = content.substring(content.indexOf('">', index1) + 2, content.indexOf('</h', index1));
				
				document.getElementById('bradcrumbLink3').innerHTML = "<b>" + h2Text + "</b>";
			}
		}
		else
		{
			//alert("doesn't have title");
		}
		
		if (_searchPg != 1 && _register != 1)
		{		
			document.getElementById('breadcrumb').style.visibility = 'visible';
		}
		else if (_searchPg == 1 || _register == 1)
		{
			document.getElementById('breadcrumb').style.visibility = 'hidden';
		}
		
		// look for the 'uniBlock' div first, if found - return the entire div cause its a map
		var uniBlockIndex = content.indexOf('uniBlock">');

		if (_lIn == 1)
		{
			ajaxBlock.innerHTML = content;
			
			// determine whether or not to show the Add to Shorlist icon
			if (uniBlockIndex > -1)
			{
				if (document.getElementById('addToShortlistUniImg'))
				{
					document.getElementById('addToShortlistUniImg').style.display = 'block';
				}
			}
			else
			{
				if (document.getElementById('addToShortlistUniImg'))
				{
					document.getElementById('addToShortlistUniImg').style.display = 'none';
				}
			}
		}
		else if (_lIn == 0 && _register == 0)
		{			
			var requestPrev = getHTTPObject();
			var prevFile = 'previewDiv.cfm';
		
			if (requestPrev) 
			{ 
				requestPrev.onreadystatechange = function() 
											 {
												 if (requestPrev.readyState == 4)
												 {
													var prevContent = requestPrev.responseText; 
													ajaxBlock.innerHTML = prevContent;
													var introDiv = document.getElementById('introContent');
													
													if (introDiv)
													{
														if (uniBlockIndex > -1)
														{
															// show the entire div (its the first div in the page)
															var uniBlockDivIndex = content.indexOf('<div');
															
															var uniBlockDivContent = content.substring(uniBlockDivIndex, content.indexOf('</div>'));															
															introDiv.innerHTML = uniBlockDivContent;
															
															if (document.getElementById('addToShortlistUniImg'))
															{
																document.getElementById('addToShortlistUniImg').style.display = 'block';
															}
														}
														else
														{
															//alert("_searchPg = " + _searchPg);
																// Extract the first instance of <h2> to </h2>
															var header = content.substring(content.indexOf('<h2>'), content.indexOf('</h2>'));
															introDiv.innerHTML = header;
													
															/* Extract the text from within the first instance of <p> to </p> */
															var index1 = content.indexOf('<p');
															
															if (index1 > -1)
															{
																var par1 = content.substring(index1, content.indexOf('</p>'));
																introDiv.innerHTML += par1;
															}
															else
															{
																// if no first instance of <p could be found, grab the h3
																var indexH3 = content.indexOf('<h3');
																
																if (indexH3 > -1)
																{
																	var h3Par = content.substring(indexH3, content.indexOf('</h3>'));
																	introDiv.innerHTML += h3Par;
																}
															}
															/* - - */
															/* Extract the text from within the second instance of <p> to </p> */
															var index2 = content.indexOf('<p', content.indexOf('</p>')); // get the index of the second instance of <p>
															if (index2 > -1)
															{
																//alert("index2 = " + index2);
															
																var par2 = content.substring(index2, content.indexOf('</p>', index2));
																introDiv.innerHTML += '<br />' + par2;
															}
															else
															{
																//alert("else index2 executed");
															}
															/* - - */
															
															if (document.getElementById('addToShortlistUniImg'))
															{
																document.getElementById('addToShortlistUniImg').style.display = 'none';
															}
														}
													}
												  }
											 };
				requestPrev.open("GET", prevFile, true);
				requestPrev.send(null);
			}
		}
		else if (_register == 1)
		{
			ajaxBlock.innerHTML = content;
			
			if (document.getElementById('addToShortlistUniImg'))
			{
				// hide the Add To Shortlist button as it will never be shown if the user clicks on a register link
				document.getElementById('addToShortlistUniImg').style.display = 'none';
				
				// display the clear button
				document.getElementById('clearPlaxoBtn').style.visibility = 'hidden';				
			}
			
			if (document.getElementById('breadcrumb'))
			{
				document.getElementById('breadcrumb').style.visibility = 'hidden';
			}
			
			setTimeout("hideBskCtrls()", 1000);
			
		}
		
		// Define the elements which has to be removed when the ajax content loads
		var removeDiv = document.getElementById("searchBlock");
		
		if (removeDiv) {
			removeElement (removeDiv);
		}

		var uniblock = document.getElementById("uniBlock");
		var categoryContent = document.getElementById("categoryContent");
		var bottomNavigation = document.getElementById("bottomNavigation");
		var searchResultsLink = document.getElementById("searchResultsLink");
		var registerFormContent = document.getElementById("registerFormContent");
		var azblock = document.getElementById("azBlock");
		var categoriesblock = document.getElementById("categoriesBlock");

		// Links left and right around the main ajax area
		var backLink = document.getElementById("ajaxBlockLeftLink");
		var nextLink = document.getElementById("ajaxBlockRightLink");

		// when the Universities Search results are displayed then show the bottom navigation
		// show the "back to search results" link as well
		if (uniblock) {
			turnDisplayOn (bottomNavigation);
			//turnDisplayOn (searchResultsLink);
		}
		
		// define the elements for which the "back to search results" navigation should not be displayed
		else if (categoryContent || azblock || categoriesblock) {
			//turnDisplayOff (searchResultsLink);
			turnDisplayOn (bottomNavigation);
			turnDisplayOn (backLink);
			turnDisplayOn (nextLink);						
		}

		// define the elements for which the "back to search results" &  "the side arrows"  & "the bottom" navigation should not be displayed
		else if (registerFormContent) {
			//turnDisplayOff (searchResultsLink);
			turnDisplayOff (bottomNavigation);	
			turnDisplayOff (backLink);
			turnDisplayOff (nextLink);
		}
		
		// hide loader once content has finished loading
		turnDisplayOff(document.getElementById('ajaxLoaderImg'));
		
		_timer = setTimeout('timerHandler()', 500);
		
		// Execute the Ajax function for all divisions which where called by ajax and need to execute
		// ajax. (callAjax() loops true the links when the page is loaded so it does not know about the
		// links which are loaded via ajax later on
		callAjax ("yourChoiceListB"); 			// Main section in your_choice_start_here.cfm		
		callAjax ("categoriesBlock");			// Main section in how_to_shortlist_1.html	
		
		// LOG: 04.06.2008 by Roman - Fixed IE7 problem
		// _timer = setTimeout('setCookie()', 500);
		loadBasket();
		
		// execute all underlying script functions in the response text
		/*if (_searchPg == 1)
		{		
			var div = document.getElementById('ajaxBlockContent');
			
			var x = div.getElementsByTagName('script');
			
			for (var i = 0; i < x.length; i++)
			{
				eval(x[i].text);
			}
		}*/
	}
} 

function refreshWin()
{
	window.location.href = window.location.href;
}

function timerHandler()
{
	// Adjust the height of the links on the left $ right of the main ajax area
	setLinksHeight();
	
	var ajaxBlock = document.getElementById("ajaxBlockContent");
	var backLink = document.getElementById("ajaxBlockLeftLink");
	var nextLink = document.getElementById("ajaxBlockRightLink");
	
	// Basket controls
	var addChapter = document.getElementById('addToCart');
	var addEntireBook = document.getElementById('buyEntireBook');
	
	if (backLink.offsetHeight < 404)
	{
		setLinksHeight();
		_timer = setTimeout('timerHandler()', 500);
	}
	else
	{
		clearTimeout(_timer);
	}
	
	if (_searchPg == 1 || _register == 1)
	{
		// hide the prev/next buttons
		if (nextLink) { nextLink.style.visibility = "hidden"; }
		if (backLink) { backLink.style.visibility = "hidden"; }
		
		addChapter.style.visibility = 'hidden';
		addEntireBook.style.visibility = 'hidden';
		
		hideBskCtrls();
	}
	else
	{
		if (nextLink) { nextLink.style.visibility  = "visible"; }
		if (backLink) { backLink.style.visibility  = "visible"; }
		
		showBskCtrls();
	}
	
}

// Set the height of the links on the same as the ajaxBlock
function setLinksHeight () {
		var ajaxBlock = document.getElementById("ajaxBlockContent");
		var backLink = document.getElementById("ajaxBlockLeftLink");
		var nextLink = document.getElementById("ajaxBlockRightLink");
		
		// Find the height of the ajaxBlock
		var ajaxCoverHeight = ajaxBlock.offsetHeight;

		// Set the height of the "back" and "next" links the same as ajaxBlock
		backLink.style.height = ajaxCoverHeight+"px";
		nextLink.style.height = ajaxCoverHeight+"px";
		//alert("ajaxCoverHeight = " + ajaxCoverHeight);
}

// Define targets for generating onclick events (IDs)
function setAjaxDivisions () {
	callAjax ("yourChoiceList"); 				// left navigation 
	callAjax ("searchList");					// left navigation 
	callAjax ("gettingInList");					// left navigation 
	callAjax ("whereToStudyList"); 				// left navigation 
	callAjax ("searchBlock");					// search results page
	callAjax ("ajaxBlock");						// Center (main) area of the search result page
	callAjax ("signUp");						// registration section (top right) 
	callAjax ("navAToZList");					// main navigation area az
	callAjax ("navSectionsList");				// top navigation - Sections
	callAjax ("ajaxHeaderChoiceList");			// left navigation header Choice list
	callAjax ("ajaxHeaderSearchList");			// left navigation header Search list
	callAjax ("ajaxHeaderGettingInList");		// left navigation header Getting in ...
	callAjax ("ajaxHeaderWhereToStudyList");	// left navigation header Where to Study ...
	
	callAjax ("howToSurvivelist");
}

// Loops true the links in specified locations and asign them onclick event which calls ajax grab file function
function callAjax(division)
{
	var navList = document.getElementById(division);
	
	if (navList)
	{
		var anchors = navList.getElementsByTagName("a");
		
		for (var i=0; i < anchors.length; i++) 
		{
			var file = anchors[i].getAttribute("href"); 
			
			anchors[i].onclick = function() 
			{
				var file = this.getAttribute("href");
			
				// define the id of the link (to be able to separated LEFT & RIGHT links)
				var linkID = this.getAttribute("id");
				
				grabFile(file, linkID);
				
				// Scroll the page on the top. Let the user to see the new content which came by ajax
				// when any of the links in "How to Survive Your First Year A-Z" are clicked" (very long list)
				if (division == "howToSurvivelist")
				{	
					toTop (0,400);
				}
	
				return false;			
			}
		}
	}
}

// REUSABLE FUNCTIONS ============================================================================================

// Remove element from DOM
function removeElement (removeDiv) {
		removeDiv.parentNode.removeChild(removeDiv);
}


// Function displays any hiden element 
function turnDisplayOn (element) {
	element.style.display = "block";
	//alert("turning on, element = " + element.getAttribute("id"));
}

// Function which hides any element 
function turnDisplayOff (element) {
	element.style.display = "none";
	//alert("turning off, element = " + element.getAttribute("id"));
}


// Scroll windows to specified parameters
function toTop (x,y) {
	self.scrollTo(x, y)
}