function setActiveStyleSheet(name) 
{
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == name) a.disabled = false;
    }
  }
}

function changeStyleSheet(name,value)
{
	setProfileCookie(name,value);
	setActiveStyleSheet(value);
}


function setProfileCookie(name,value) 
{
  	var expiration_date = new Date();
	expiration_date.setTime((expiration_date.getTime()+ 315360000000));
 	expiration_date = expiration_date.toGMTString();
	setCookie(name, value, expiration_date);
}

// for some reason the cookies initally set when a user first visits (which are done by the java profile class) are
// not picked up by this javascript code and hence when you click to go to text only mode you end up with two cookies
// both called TextCookie. One is true and one is false - the browser just takes the value of the first one. So anyway
// I have changed this so the initial cookie value set by the java expires when our javascript adds its new updated one.
function setCookie(name, value, expires)
{
	// remove spaces then spliot at semi-colons to get individual name=value pairs
	var cookiestr = document.cookie.replace(/ /g, "");
	var cookiebits = cookiestr.split(';');	

	var i;
	for(i = 0; i < cookiebits.length; i++)
	{
		var cname = cookiebits[i].split('=')[0];
		if(cname == name)
		{
			// match found - expire the entry in the cookies collection for this name (this was made by the profile class)
			document.cookie = name + "=-1;";
			break;
		}
	}
	
	document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + "; path=/";
}

function setRouterSize(i)
{
	setProfileCookie("RouterCookie",i);
	
//	thisMovie("routerswf").SetVariable("largetext", sendTextL);
//	thisMovie("routerswf").SetVariable("smalltext", sendTextS);
	
	if(window.routerswf) window.document["routerswf"].SetVariable("strSize", i);
	else if(document.routerswf) document.routerswf.SetVariable("strSize", i);

	//setFlashVariables('routerswf','largetext=' + sendTextL +'&'+'smalltext='+sendTextS);
	//setFlashVariables('routerswf','largetext=14&smalltext=13');
}
var originalHeight;
function forceMinHeight(targetDiv)
{		
		var newTargetDiv 				= document.getElementById(targetDiv);
		var footerDiv					= document.getElementById('footer');
		var mastheadHeight				= 353;
		newTargetDiv.style.height 		= originalHeight+5+"px";		
		if (document.height > Number(newTargetDiv.offsetHeight  + footerDiv.offsetHeight + mastheadHeight))
		{
			newTargetDiv.style.height 		= Number(document.height - footerDiv.offsetHeight - mastheadHeight) + 'px';
		}
}

function textResizePageReload(iSize)
{
	var strSize = '';
	
	switch(iSize)
	{
		case 1:	
		strSize = 'small';
		break;
		case 2:		
		strSize = 'medium';		
		break;
		case 3:		
		strSize = 'large';		
		break;		
	}
	
	changeStyleSheet('SizeCookie',strSize);
	setRouterSize(iSize);
	
	sIFR.rollback();
	do_sIFR();
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


function addBookmark(url,title) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( document.all ) {
 window.external.AddFavorite( url, title);
 } else if( window.opera && window.print ) {
 return true;
}
}

function openPicture(url, width, height)
{
	var str 	= "height=" + (height+30) + ",innerHeight=" + height + ",width=" + (width+30) + ",innerWidth=" + width + ",statusbar=no,scrollbars=yes";
	var xpos	= (screen.availWidth-width)/2;
	var ypos	= (screen.availHeight-height)/2;
	newWindow 	= window.open(url,"pic",str);
	newWindow.focus();
	return newWindow;
}

function openURL(url, name, width, height)
{
	var str 	= "height=" + height + ",innerHeight=" + height + ",width=" + width + ",innerWidth=" + width + ",statusbar=no,scrollbars=no";
	var xpos	= (screen.availWidth-width)/2;
	var ypos	= (screen.availHeight-height)/2;
	newWindow 	= window.open(url,"pic",str);
	newWindow.focus();
	//return newWindow;
	
}

// <![CDATA[
    /*------------------------------------------------------------------------------
    Function:       footnoteLinks()
    Author:         Aaron Gustafson (aaron at easy-designs dot net)
    Creation Date:  8 May 2005
    Version:        1.3
    Homepage:       http://www.easy-designs.net/code/footnoteLinks/
    License:        Creative Commons Attribution-ShareAlike 2.0 License
                    http://creativecommons.org/licenses/by-sa/2.0/
    Note:           This version has reduced functionality as it is a demo of 
                    the script's development
    ------------------------------------------------------------------------------*/
    function footnoteLinks(containerID,targetID) {
      if (!document.getElementById || 
          !document.getElementsByTagName ||
          !document.createElement) return false;
      if (!document.getElementById(containerID) ||
          !document.getElementById(targetID)) return false;
      var container = document.getElementById(containerID);
      var target    = document.getElementById(targetID);
      var h2        = document.createElement('h2');
      addClass.apply(h2,['printOnly']);
      var h2_txt    = document.createTextNode('Page Links');
     
      var coll = container.getElementsByTagName('*');
      var ol   = document.createElement('ol');
      addClass.apply(ol,['printOnly']);
      var myArr = [];
      var thisLink;
      var num = 1;
      for (var i=0; i<coll.length; i++) {
		  
		  
        var thisClass = coll[i].className;
        if ( coll[i].getAttribute('href') ||
             coll[i].getAttribute('cite') ) { 
          thisLink = coll[i].getAttribute('href') ? coll[i].href : coll[i].cite;
          var note = document.createElement('sup');
          addClass.apply(note,['printOnly']);
		  
		  
		    // don't want 'links' printed out unless we've actually got some
		 	if(!linksBool)
			{
			 h2.appendChild(h2_txt); 
			 var linksBool = true;
			}
		  
		  
          var note_txt;
          var j = inArray.apply(myArr,[thisLink]);
          if ( j || j===0 ) {
            note_txt = document.createTextNode(j+1);
          } else {
            var li     = document.createElement('li');
            var li_txt = document.createTextNode(thisLink);
            li.appendChild(li_txt);
            ol.appendChild(li);
            myArr.push(thisLink);
            note_txt = document.createTextNode(num);
            num++;
          }
          note.appendChild(note_txt);
          if (coll[i].tagName.toLowerCase() == 'blockquote') {
            var lastChild = lastChildContainingText.apply(coll[i]);
            lastChild.appendChild(note);
          } else {
            coll[i].parentNode.insertBefore(note, coll[i].nextSibling);
          }
        }
      }
      target.appendChild(h2);
      target.appendChild(ol);
      addClass.apply(document.getElementsByTagName('html')[0],['noted']);
      return true;
    }
   /* window.onload = function() {
      footnoteLinks('firstcolumn','footer');
	  alert("hi");
	  originalHeight = 'firstcolumn'.offsetHeight;
	  forceMinHeight('firstcolumn');
    }
	window.onresize = function() {
		forceMinHeight('firstcolumn');
	}
	/*
    // ]]>
    // <![CDATA[
    /*------------------------------------------------------------------------------
    Excerpts from the jsUtilities Library
    Version:        2.1
    Homepage:       http://www.easy-designs.net/code/jsUtilities/
    License:        Creative Commons Attribution-ShareAlike 2.0 License
                    http://creativecommons.org/licenses/by-sa/2.0/
    Note:           If you change or improve on this script, please let us know.
    ------------------------------------------------------------------------------*/
    if(Array.prototype.push == null) {
      Array.prototype.push = function(item) {
        this[this.length] = item;
        return this.length;
      };
    };
    // ---------------------------------------------------------------------
    //                  function.apply (if unsupported)
    //           Courtesy of Aaron Boodman - http://youngpup.net
    // ---------------------------------------------------------------------
    if (!Function.prototype.apply) {
      Function.prototype.apply = function(oScope, args) {
        var sarg = [];
        var rtrn, call;
        if (!oScope) oScope = window;
        if (!args) args = [];
        for (var i = 0; i < args.length; i++) {
          sarg[i] = "args["+i+"]";
        };
        call = "oScope.__applyTemp__(" + sarg.join(",") + ");";
        oScope.__applyTemp__ = this;
        rtrn = eval(call);
        oScope.__applyTemp__ = null;
    	return rtrn;
      };
    };
    function inArray(needle) {
      for (var i=0; i < this.length; i++) {
        if (this[i] === needle) {
          return i;
        }
      }
      return false;
    }
    function addClass(theClass) {
      if (this.className != '') {
        this.className += ' ' + theClass;
      } else {
        this.className = theClass;
      }
    }
    function lastChildContainingText() {
      var testChild = this.lastChild;
      var contentCntnr = ['p','li','dd'];
      while (testChild.nodeType != 1) {
        testChild = testChild.previousSibling;
      } 
      var tag = testChild.tagName.toLowerCase();
      var tagInArr = inArray.apply(contentCntnr, [tag]);
      if (!tagInArr && tagInArr!==0) {
        testChild = lastChildContainingText.apply(testChild);
      }
      return testChild;
    }
    // ]]>

function checkDay()
{
	var month 		= document.getElementById("mm").value;
	var dsel 		= document.getElementById("dd");
	var selval		= document.getElementById("dd").value;
	var year 		= document.getElementById("yy").value;
	var leapyear 	= false;
	if (year % 4 == 0) leapyear = true;
	var monthlength = 30;
    switch (parseInt(month))
	{
		case 1: monthlength=31; break;
		case 2: monthlength=(leapyear?29:28); break;
		case 3: monthlength=31; break;
		case 4: monthlength=30; break;
		case 5: monthlength=31; break;
		case 6: monthlength=30; break;
		case 7: monthlength=31; break;
		case 8: monthlength=31; break;
		case 9: monthlength=30; break;
		case 10: monthlength=31; break;
		case 11: monthlength=30; break;
		case 12: monthlength=31; break;
	}
	dsel.options.length 	= monthlength;
	for (i = 0; i < dsel.options.length; i++)
	{
		dsel.options[i].value 	= (i+1);
		dsel.options[i].text 	= (i+1);
	}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

/*
	Author:		Mike Harris
	Purpose:	Whips through the page replacing all specified tags with text
				nodes containing the content of the original tag's alt text
*/
function replaceSpecifiedLinks(strSpecifiedTag)
{
	var imageLinks = document.getElementsByTagName(strSpecifiedTag);
	var imageNames = new Array();

	// loop over all images
	for(var i=0; i < imageLinks.length; i++)
	{
		// check if the link has a valid alt attribute
		var t = imageLinks[i].getAttribute("alt");

		if(t != null)
		{
			imageNames[i] = t;
		}
	}
	
	// items are removed from imageLinks array when replacement takes place hence we need to reference item 0 each time
	for(var i = 0; i < imageNames.length; i++)
	{
		var parent = imageLinks[0].parentNode;
		var oNewTextNode = document.createTextNode("Image: " + imageNames[i]);

		parent.replaceChild(oNewTextNode, imageLinks[0]);
	}
}

function replaceImageLinks()
{
	replaceSpecifiedLinks('img');
}


function replaceInputImages()
{
	var inputLinks = document.getElementsByTagName("input");

	// loop over all inputs
	for(var i=0; i < inputLinks.length; i++)
	{
		// check if it is of type image
		var t = inputLinks[i].getAttribute("type");
		
		if(t != null && t == "image")
		{
			// create a new item (because input type cannot be overwritten)
			var parent		= inputLinks[i].parentNode;
			var oNewNode	= document.createElement("input");
			oNewNode.type	= "submit";
			
			// we want to take its attributes to ... but class isnt working for some reason!
			/*			
			var strClass = inputLinks[i].getAttribute("className");
			if(strClass != null && strClass != "")
			{
				oNewNode.className = strClass;
			}
			strClass = inputLinks[i].getAttribute("class");
			alert(strClass);			
			if(strClass != null && strClass != "")
			{
				oNewNode.class = strClass;
			}*/
			
			var strValue = inputLinks[i].getAttribute("value");
			if(strValue != null && strValue != "")
			{
				oNewNode.value = strValue;
			}
			var strAlt = inputLinks[i].getAttribute("alt");
			if(strAlt != null && strAlt != "")
			{
				oNewNode.alt = strAlt;
			}
			var strName = inputLinks[i].getAttribute("name");
			if(strName != null && strName != "")
			{
				oNewNode.name = strName;
			}
			
			parent.replaceChild(oNewNode, inputLinks[i]);			
		}
	}
}

/*
	Shortlinks
	constrains the length of links displayed to a defined length
	written by Chris Heilmann (http://icant.co.uk/)
*/
function shortenLongLinks()
{
	// defines where the link should be cut off, from the right or the middle
	var mode='right';
	// the maximum length of the links
	var mustlength=42; 
	// the string added to or in the middle of the link text after shortening
	var connector='...';
	// the title added to the link, %url% will be replaced with the real link
	var titleadd=' (Address: %url%)';
	// the links to be shortened
	var contentlinks=document.getElementsByTagName('a');

	// loop over all links
	for(var i=0;i<contentlinks.length;i++)
	{
		// check if the link has an href attribute and content
		if( contentlinks[i].getAttribute('href') != null && 
			contentlinks[i].firstChild != null &&
			contentlinks[i].firstChild.nodeValue != null)
		{
			var t = contentlinks[i].firstChild.nodeValue;

			var bolContinue = false;
			// it is an email address or a web link, we may need to shorten it
			if((t.substring(0, 5) == "http:") || (t.substring(0, 4) == "www.") || (t.indexOf("@") > -1))
			{
				bolContinue = true;	
			}

			// if its a valid link longer than the allowed length, trim it
			if(bolContinue && (t.length > mustlength))
			{	
				// get the text of the link
				// shorten accordingly and add the separator string
				switch(mode)
				{
					case 'middle':
						var newt=t.substr(0,mustlength/2)+connector+t.substr(t.length-mustlength/2-connector.length,t.length);
					break;
					case 'right':
						var newt=t.substr(0,mustlength-connector.length)+connector;
					break;
				}
	
				// set the title, and replace the original link text
				contentlinks[i].title+=titleadd.replace(/%url%/,t);
				contentlinks[i].replaceChild(document.createTextNode(newt),contentlinks[i].firstChild);
			}
		}
	}	
}

/*
	Author:		Mike Harris
	Purpose:	Replaces the existing value of the body class attribute
				or appends to it depending on the bool supplied. 
*/
function rewriteBodyClass(strNewClass, bolAppend)
{
	var bodies = document.getElementsByTagName('body');
	
	if(bodies.length == 1)
	{
		var currentClass = bodies[0]['className'];
		var newClass;
		
		if(bolAppend)
		{
			newClass = currentClass + " " + strNewClass;
		}
		else
		{
			newClass = strNewClass;
		}
		
		bodies[0]['className'] = newClass;
	}
	else
	{
		alert("Strange number of bodies found!");
	}
}

/*
	Author:		Mike Harris
	Purpose:	Corrects the href of the Home link image. 
*/
function writeHomeLink()
{
	document.getElementById('lnkHomeImage').href = "http://www.cranfield.ac.uk";	
	/*document.getElementById('lnkHomeImage').href = document.getElementById('lnkHome').href;*/
	/*if(document.getElementById('lnkHomeImage').href) == "#"
	{
		document.getElementById('lnkHomeImage').href = "http://www.cranfield.ac.uk";	
	}*/
	
	
}

/*
	Author:		Mike Harris
	Purpose:	Does exactly what it sez on the tin
*/
function writeTextOnlyLink(bPreviewing)
{
	var bolTextCookie = getCookie("TextCookie");
	var objTextLink = document.getElementById("lnkTextOnly");
	
	if(bPreviewing)
	{
		var objParent = objTextLink.parentNode;
		objParent.replaceChild(document.createTextNode("Text only"), objParent.firstChild);
	}
	else if(bolTextCookie == "true")
	{
		objTextLink.href		= "javascript:setProfileCookie('TextCookie','false');window.location.reload(true);";
		objTextLink.title		= "View Graphical Version";	
		objTextLink.replaceChild(document.createTextNode("Graphical version"), objTextLink.firstChild);		
	}
	else
	{
		objTextLink.href		= "javascript:setProfileCookie('TextCookie','true');window.location.reload(true);";
		objTextLink.title		= "View Text-Only Version";	
		objTextLink.replaceChild(document.createTextNode("Text only"), objTextLink.firstChild);				
	}
}

/*
	Author:		Mike Harris
	Purpose:	Does exactly what it sez on the tin
*/
function setCurrentTextSize()
{
	var strSizeCookie = getCookie("SizeCookie");

	if(strSizeCookie == "medium" || strSizeCookie == "large")
	{
		setActiveStyleSheet(strSizeCookie);
	}
	else
	{
		setActiveStyleSheet('');
	}	
}

/*
	Author:		Mike Harris
	Purpose:	Redirects users from the dropdowns in the
				top right corner to where they need to be
*/
function redirect(form)
{
	var intSelectedIndex = form.category.selectedIndex;
	
	if(intSelectedIndex > 0)
	{
		var strDestination = form.category.options[intSelectedIndex].value;
		//form.action = strDestination;
		document.location.href = strDestination;
	}

	return false;
}

////////////////////////////////
// Courtesy of QuirksMode.Org //
////////////////////////////////

var BrowserDetect =
{
	init: function ()
	{
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
					|| this.searchVersion(navigator.appVersion)
					|| "An unknown version";
		this.OS 	 = this.searchString(this.dataOS) || "An unknown OS";
	},
	searchString: function (data)
	{
		for (var i=0;i<data.length;i++)
		{
			var dataString			 = data[i].string;
			var dataProp			 = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString)
			{
				if (dataString.indexOf(data[i].subString) != -1)
				{
					return data[i].identity;
				}
			}
			else if (dataProp)
			{
				return data[i].identity;
			}
		}
	},
	searchVersion: function (dataString)
	{
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser:
	[
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS :
	[
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();

/*
	Author:		Mike Harris
	Purpose:	Writes out a reasonably reliable 'bookmark this page' 
				link using the lovely browser detect code above
*/
function writeBookmarkLink()
{
	var strOnClick	= "";
	var bolMac	  	= (BrowserDetect.OS == "Mac");
	var strButton	= (bolMac ? "Command" : "CTRL");
	
	var lnkBookmarker = document.getElementById("lnkBookmark");

	if(lnkBookmarker)
	{
		strUrl	 = location.href;
		strTitle = document.title;

		if(BrowserDetect.browser == "Opera" && parseInt(BrowserDetect.version) >= '7')
		{
			lnkBookmarker.href  = strUrl;
			lnkBookmarker.title = strTitle;			
			lnkBookmarker.rel   = 'sidebar';
		}
		else
		{
			lnkBookmarker.onclick = function()
			{
				switch(BrowserDetect.browser)
				{
					case "Explorer":
						window.external.AddFavorite(strUrl, strTitle);
					break;
					case "Firefox":
						window.sidebar.addPanel(strTitle, strUrl,'');
					break;
					case "Opera":
						alert('To bookmark this page, press ' + strButton + ' + T');
					break;		
					case "Safari":
						alert('To bookmark this page, press ' + strButton + ' + D');
					break;
					case "Netscape":
						alert('To bookmark this page, press ' + strButton + ' + D');
					break;
					case "Konqueror":
						alert('To bookmark this page, press ' + strButton + ' + B');
					break;
					default:
						alert('This page can only be bookmarked via your browser');
					break;
				}			
			}
		}
	}
}
