
function fontSizeUp() {
	var active = getActiveStyleSheet();
	enableLink('increaseFont');
	enableLink('decreaseFont');
	switch (active) {
		case 'A--' :
			setActiveStyleSheet('A-');
			break;
		case 'A-' :
			setActiveStyleSheet('A');
			break;
		case 'A' :
			setActiveStyleSheet('A+');
			break;
		case 'A+' :
			setActiveStyleSheet('A++');
			break;
		case 'A++' :
			setActiveStyleSheet('A+++');
			disableLink('increaseFont');
			break;
		case 'A+++' :
			disableLink('increaseFont');
			break;
		default :
			setActiveStyleSheet('A');
			break;
	}
}

function fontSizeDown() {
	var active = getActiveStyleSheet();
	enableLink('increaseFont');
	enableLink('decreaseFont');
	switch (active) {
		case 'A+++' :
			setActiveStyleSheet('A++');
			break;
		case 'A++' :
			setActiveStyleSheet('A+');
			break;
		case 'A+' :
			setActiveStyleSheet('A');
			break;
		case 'A' :
			setActiveStyleSheet('A-');
			break;
		case 'A-' :
			setActiveStyleSheet('A--');
			disableLink('decreaseFont');
			break;
		case 'A--' :
			disableLink('decreaseFont');
			break;
		default :
			setActiveStyleSheet('A');
			break;
	}
}

function defaultFontSize() {
	var defaultFont = getPreferredStyleSheet();
	enableLink('increaseFont');
	enableLink('decreaseFont');
	setActiveStyleSheet(defaultFont);
}

function setActiveStyleSheet(title) {
	var i, a, main;
	for (i=0; (a=document.getElementsByTagName('link')[i]); i++) {
		if (a.getAttribute('rel').indexOf('style') != -1 && a.getAttribute('title')) {
			a.disabled = true;
			if (a.getAttribute('title') == title) a.disabled = false;
		}
	}
}

function macUnixTest() {
	var agent = navigator.userAgent.toLowerCase();
	var isMacOrUnix  = ((agent.indexOf('mac')!=-1) || 
						(agent.indexOf('x11')!=-1) || (agent.indexOf('sunos')!=-1) || 
						(agent.indexOf('irix')!=-1) || (agent.indexOf('hp-ux')!=-1) || 
						(agent.indexOf('sco')!=-1) || (agent.indexOf('unix_system_v')!=-1) || 
						(agent.indexOf('ncr')!=-1) || (agent.indexOf('reliantunix')!=-1) || 
						(agent.indexOf('dec')!=-1) || (agent.indexOf('sinix')!=-1) || 
						(agent.indexOf('aix')!=-1) || (agent.indexOf('inux')!=-1) || 
						(agent.indexOf('bsd')!=-1) || (agent.indexOf('freebsd')!=-1));
	return (isMacOrUnix);
}

function getActiveStyleSheet() {
	var i, a;
	for (i=0; (a=document.getElementsByTagName('link')[i]); i++) {
		if (a.getAttribute('rel').indexOf("style") != -1 && a.getAttribute('title') && !a.disabled) {
			return a.getAttribute('title');
		}
	}
	return null;
}

function getPreferredStyleSheet() {
	if (macUnixTest()) {
		return ('A+');
	} else {
		return ('A');
	}
}

/*----------------------------------------------------
   Create cookie
-----------------------------------------------------*/
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		var expires = '; expires=' + date.toGMTString();
	} else {
		expires = '';
	}
	document.cookie = name + "=" + value + expires + '; path=/';
}

/*----------------------------------------------------
   Read cookie details with given name
-----------------------------------------------------*/
function readCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for (var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}

/*----------------------------------------------------
   Set given link class to 'enabled'
-----------------------------------------------------*/
function enableLink(linkId) {
	var link = document.getElementById(linkId);
	link.className = 'fontSize enabled';
}

/*----------------------------------------------------
   Set given link class to 'disabled'
-----------------------------------------------------*/
function disableLink(linkId) {
	var link = document.getElementById(linkId);
	link.className = 'fontSize disabled';
}

/*----------------------------------------------------
   Create containing box and links for font size
   widget
-----------------------------------------------------*/
function fontChanger(divId) {
	var div, linkDecrease, linkReset, linkIncrease;
	div = createHtmlElement('div', {'id' : 'fontBox', 'text' : 'Font size:'});
	document.getElementById(divId).appendChild(div);
	
	linkDecrease  = createHtmlElement('a', {'class' : 'fontSize enabled', 'title' : 'Decrease font size', 'href' : '', 'text' : '-', 'id' : 'decreaseFont'});
	div.appendChild(linkDecrease);
	linkDecrease.onclick = function() { fontSizeDown(); return false; }
	
	linkReset  = createHtmlElement('a', {'class' : 'fontSize enabled', 'title' : 'Reset to default font size', 'href' : '', 'text' : 'A', 'id' : 'defaultFont'});
	div.appendChild(linkReset);
	linkReset.onclick = function() { defaultFontSize(); return false; }
	
	linkIncrease  = createHtmlElement('a', {'class' : 'fontSize enabled', 'title' : 'Increase font size', 'href' : '', 'text' : '+', 'id' : 'increaseFont'});
	div.appendChild(linkIncrease);
	linkIncrease.onclick = function() { fontSizeUp(); return false; }
	return true;
}

// Output HTML element
function createHtmlElement(name, attributes) {
	var element = (typeof document.createElementNS != 'undefined') ? document.createElementNS('http://www.w3.org/1999/xhtml',name) : document.createElement(name);
	if (typeof attributes != 'undefined') {
		for (var i in attributes) {
			if (i == 'text') {
				element.appendChild(document.createTextNode(attributes[i]));
			} else if (i == 'class') {
				element.className = attributes[i];
			} else {
				element.setAttribute(i, attributes[i]);
			}
		}
	}
	return(element);
}

/*----------------------------------------------------
   Remove (trim) white-space from beginning and end
   of strings. Also remove line breaks and tabs.
-----------------------------------------------------*/
function trim(sString) {
	while ((sString.indexOf('\r') > 0) || (sString.indexOf('\n') > 0) || (sString.indexOf('\t') > 0)) {
		sString = sString.replace(/\r/, '');
		sString = sString.replace(/\n/, '');
		sString = sString.replace(/\t/, '');
	}
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0, sString.length-1);
	}
	return sString;
}

/*----------------------------------------------------
	Find elements with a given class beneath a 
	given node
-----------------------------------------------------*/
function getElementsByClassName(node, className) {
	var result = [];
	if (document.getElementsByTagName('*').length > 0) {
		var elems = node.getElementsByTagName('*');
	} else if (document.all) {
		// ie5 does not support wildcard (*) argument above
		var elems = node.all;
	}
	for (var i=0; i < elems.length; i++) {
		if (elems[i].className == className) {
			// ie5 doesn't support array.push()
			result[result.length] = elems[i];
		}
	}
	return(result);
}

/*----------------------------------------------------
	 Determine height of a given html element
-----------------------------------------------------*/
function getHeight(elem) {
	if (elem.style.height) {
		return (elem.style.height);
	}
	if (elem.style.pixelHeight) {
		return (elem.style.pixelHeight);
	}
	if (elem.offsetHeight) {
		return (elem.offsetHeight);
	}
	if (document.defaultView && document.defaultView.getComputedStyle) {
		return (document.defaultView.getComputedStyle(elem,'').getPropertyValue('height'));
	}
}

/*----------------------------------------------------
	 Determine width of a given html element
-----------------------------------------------------*/
function getWidth(elem) {
	if (elem.style.width) {
		return (elem.style.width);
	}
	if (elem.style.pixelWidth) {
		return (elem.style.pixelWidth);
	}
	if (elem.offsetWidth) {
		return (elem.offsetWidth);
	}
	if (document.defaultView && document.defaultView.getComputedStyle) {
		return (document.defaultView.getComputedStyle(elem,'').getPropertyValue('width'));
	}
}

/*----------------------------------------------------
	Given array of html elements, set them all the
	same height as the element with the maximum height
-----------------------------------------------------*/
function normaliseHeights(elements) {
	var maxHeight = 0;
	for (var i=0; i < elements.length; i++) {
		var elemHeight = parseInt(getHeight(elements[i]).toString().replace(/px/g, ''));
		if (elemHeight > maxHeight) {
			maxHeight = elemHeight;
		}
	}
	for (var i=0; i < elements.length; i++) {
		elements[i].style.height = maxHeight + 'px';
	}
}

/*----------------------------------------------------
   Check links under given node for filetypes
   If found (pdf, word, powerpoint, excel, zip)
   change class to add relevant icon
-----------------------------------------------------*/
function styleFileLinks(node) {
	var links = node.getElementsByTagName('a');
	var numLinks = links.length;
	for (var i=0; i < numLinks; i++) {
		var currentLink = links[i];
		var images = currentLink.getElementsByTagName('img');
	 	// Make sure link is not an image
		if (images.length == 0) {
			// get extension (if any)
			var urlParts = currentLink.href.split('.');
			var ext = urlParts[urlParts.length - 1];
			// remove any trailing slash
			ext = ext.replace('/', '');
			// change class if match found
			if ((ext == 'doc') || (ext == 'pdf') || (ext == 'ppt') || (ext == 'txt') || (ext == 'xls') || (ext == 'zip')) {
				if (currentLink.className == '') {
					currentLink.className = ext;
				} else {
					// add to existing class
					currentLink.className += ' ' + ext;
				}
			}
		}
	}
}

/*----------------------------------------------------
   Check links under given node for external urls
   If found set class to 'ext' which adds a 
   background link image
-----------------------------------------------------*/
function styleExtLinks(node) {
	var links = node.getElementsByTagName('a');
	var numLinks = links.length;
	// loop through all <a> tags under given node to check href link
	for (var i=0; i < numLinks; i++) {
		var currentLink = links[i];
		// do not change class if an img tag is the link
		if ((!currentLink.firstChild) || (currentLink.firstChild.tagName != 'IMG')) {
			// change class if web link and not edc web link
			if ((currentLink.href.indexOf('http://') == 0) && ((currentLink.href.indexOf('http://www-edc.eng.cam.ac.uk') == -1) && (currentLink.href.indexOf('http://vedclinux.eng.cam.ac.uk') == -1))) {
				currentLink.className = 'ext';
			}
		}
	}
}

/*----------------------------------------------------
   Find figures under given node and set width to the
   width of the figure's image, thus preventing the 
   caption text from making the div too wide
-----------------------------------------------------*/
function sizeFigures(node) {
	var divs = node.getElementsByTagName('div');
	var numDivs = divs.length;
	for (var i=0; i < numDivs; i++) {
		var currentDiv = divs[i];
		// find div's width figure classes
		if ((currentDiv.className == 'figure') || (currentDiv.className == 'figure-l') || (currentDiv.className == 'figure-r')) {
			var images = currentDiv.getElementsByTagName('img');
			var numImages = images.length;
			var figWidth = 0;
			for (var j=0; j < numImages; j++) {
				var imageWidth = getWidth(images[j]);
				if (imageWidth > figWidth) {
					figWidth = imageWidth;
				}
			}
			if (figWidth > 0) {
				//var compStyle = window.getComputedStyle(currentDiv, "");
				//if (compStyle.getPropertyValue('background-color') != 'transparent') {
					// set div width to width of image
					currentDiv.style.width = figWidth + 'px';
				//}
			}
		}
	}
}

/*----------------------------------------------------
   Find figures under given node and set width to the
   width of the figure's image, thus preventing the 
   caption text from making the div too wide

   don't think this is used 
-----------------------------------------------------*/
function styleProjectList(pList) {
	var numLists = pList.length;
	for (var i=0; i < numLists; i++) {
		var listItem = pList[i].getElementsByTagName('li');
		var numItems = listItem.length;
		for (var j=0; j < numItems; j++) {
			var lnkArr = listItem[j].getElementsByTagName('a');
			var lnk = lnkArr[0].href;
			if ((lnkArr != null) && (lnk.indexOf('#') == -1)) {
				var lnkSplit = lnk.split('/');
				var lnkSplitLen = lnkSplit.length;
				var path = lnkSplit[lnkSplitLen - 2];
				listItem[j].style.backgroundImage = 'url("' + path + '/images/thumb.jpg")';
			}
		}
	}
}

function inArray(needle) {
	for (var i=0; i < this.length; i++) {
		if (this[i] === needle) { return i; }
	}
	return false;
}
Array.prototype.inArray = inArray;

/*----------------------------------------------------
   Gather all external url's under given node and 
   create footnote at bottom, listing url's
-----------------------------------------------------*/
function footnoteLinks(container) {
	// create target footnote container
	var target = createHtmlElement('div', {'id' : 'footnote'});
	// create a heading for the footnotes
	var heading = createHtmlElement('h3', {'class' : 'print', 'text' : 'External Links'});
	// create an <ol> to contain the footnotes
	var ol = createHtmlElement('ol', {'class' : 'print'});
	// create an array to store used links so we can check for duplicates
	var linkArr = [];	// to store all the links
	var thisLink;		// to store each link individually
	// create a variable to keep track of the number used for each
	// link, so we have it for footnote references
	var num = 1;
	// collect all of the elements in the specified container into an array
	if (document.getElementsByTagName('*').length > 0) {
		var elems = container.getElementsByTagName('*');
	} else if (document.all) {
		// ie5 does not support wildcard (*) argument above
		var elems = container.all;
	}
	// cycle through the elements in that array, looking for hrefs and citations
	var numElems = elems.length;
	for (var i=0; i < numElems; i++) {
		if (elems[i].getAttribute('href') || elems[i].getAttribute('cite')) {
			thisLink = elems[i].getAttribute('href') ? elems[i].href : elems[i].cite;
			// only include external links (ie. those beginning with 'http' and not and internal edc links)
			if ((thisLink.indexOf('http') == 0) && (thisLink.indexOf('http://www-edc.eng.cam.ac.uk') != 0) && (thisLink.indexOf('http://vedclinux.eng.cam.ac.uk') != 0)) {
				var n;
				var j = linkArr.inArray(thisLink);
				if (j || j === 0) {
					// duplicate found so get the corresponding number from the array of used links
					n = j + 1;
				} else {
					// not a duplicate so build new footnote link
					n = num;
					// build the <li> and append to the <ol>
					var li = createHtmlElement('li', {'class' : 'print', 'text' : thisLink});
					ol.appendChild(li);
					// store the link in the array
					linkArr[linkArr.length] = thisLink;
					// increment the number variable
					num++;
				}
				// build the <sup> and append after the reference
				var note = createHtmlElement('sup', {'class' : 'print', 'text' : n})
				elems[i].parentNode.insertBefore(note, elems[i].nextSibling);
			}
		}
	}
	// add footnote if external links were found
	if (num > 1) {
		container.appendChild(target);
		target.appendChild(heading);
		target.appendChild(ol);
	}
}

function setOpacity(obj, opacity) {
	opacity = (opacity == 100) ? 99.999 : opacity;
	// IE/Win
	obj.style.filter = "alpha(opacity: "+opacity+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

var fadeTimeoutId;

function fadeIn(objId, opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 20;
			fadeTimeoutId = window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 10);
		}
	}
}

// init function
function init() {
	var cookie = readCookie('edcFontSize');
	var title = cookie ? cookie : getPreferredStyleSheet();
	setActiveStyleSheet(title);
	// Check 4 W3C DOM support
	var W3CDOM = (document.createElement && document.getElementsByTagName);
	if (!W3CDOM) return;
	var fontChange = new fontChanger('mainMenu');
	
	var mainContent = document.getElementById('content');
	var sidebar = document.getElementById('sidebar');
	// Check for links to filetypes and show relevant icons
	styleFileLinks(mainContent);
	if (sidebar != null) styleFileLinks(sidebar);
	// Check for figures and set size
	sizeFigures(mainContent);
	// Check for external link and set appropriate class
	styleExtLinks(mainContent);

	// Check for project lists - wtf? 
//	var pList = getElementsByClassName(mainContent, 'projectList');
//	if (pList.length > 0) {
//		styleProjectList(pList);
//	}

	// make a list of footnotes containing external links when printing
	// footnoteLinks(mainContent);
}

// exit function
function goodbye() { 
	var title = getActiveStyleSheet();
	createCookie('edcFontSize', title, 365);
}

// *** Main code ***

// gecko, safari, konqueror and generic
if (typeof window.addEventListener != 'undefined') {
	window.addEventListener('load', init, false);
	window.addEventListener('unload', goodbye, false);
}
// opera 7
else if (typeof document.addEventListener != 'undefined') {
	document.addEventListener('load', init, false);
	document.addEventListener('unload', goodbye, false);
}
// win/ie
else if (typeof window.attachEvent != 'undefined') {
	window.attachEvent('onload', init);
	window.attachEvent('onunload', goodbye);
}

var cookie = readCookie("edcFontSize");
var title = cookie ? cookie : getPreferredStyleSheet();
if (title == 'null') {
  title = getPreferredStyleSheet();
}

setActiveStyleSheet(title);

