/*-----------------------------------------------------------------------------
Universal Javascript file

version:   1.2
author:    Paul Boag
email:     paul.boag@headscape.co.uk
website:   http://www.headscape.co.uk
-----------------------------------------------------------------------------*/


// Shorthand for seeing if something is in an array
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

// Easy way of adding an event
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
// Solves an IE caching problem
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);





// RESIZING TEXT -------------------------------------------------------

function addResize() {
	if (!document.getElementById) return false;
	var whereAttach = document.getElementById("textSize");
	whereAttach.innerHTML = '<ul><li class="increase"><a href="#" id="stIncrease">Increase text size</a></li><li class="reset"><a href="#" id="stReset">Reset</a></li><li class="decrease"><a href="#" id="stDecrease">Decrease text size</a></li></ul>'
	
	if (!document.getElementsByTagName) return false;
	var bodyTag = document.getElementsByTagName ("body");
	if (readCookie("resize")) {
	bodyTag[0].style.fontSize = ((parseFloat(readCookie("resize"))) + "%");
	}
	
}

function defaultBody() {
	if (!document.getElementsByTagName) return false;
	var bodyTag = document.getElementsByTagName ("body");
	if (navigator.vendor=="Apple") {
	bodyTag[0].style.fontSize = "83.5%";
	alert("safari");
	}
	else {
		bodyTag[0].style.fontSize = "62.5%";
	}
		
}


// Set Body text size
function setSize(iSize) {
	if (!document.getElementsByTagName) return false;
	var bodyTag = document.getElementsByTagName ("body");
		if (!bodyTag[0].style.fontSize) {
		if (!readCookie("resize")) {
		defaultBody();
		}
		else {
		bodyTag[0].style.fontSize = ((parseFloat(readCookie("resize"))) + "%");
		}
		}
		else {
		if (!readCookie("resize")) {
		defaultBody();
		}
		else {
		bodyTag[0].style.fontSize = (((parseFloat(iSize)) + (parseFloat(readCookie("resize")))) + "%");
		}
		}
		cookieValue = bodyTag[0].style.fontSize;
		writeCookie("resize", cookieValue, 10000);
}


// Attaches the onclick event to the correct ids to allow resizing
function resizeT(iID, iDir) {
	if (!document.getElementById) return false;
	var incLink = document.getElementById (iID);
	if (iDir == "decrease") {
	incLink.onclick = function() {
		setSize("-10%");
		return false;
	}
	}
	if (iDir == "increase") {
	incLink.onclick = function() {
		setSize("10%");
		return false;
	}
	}
	if (iDir == "reset") {
	incLink.onclick = function() {
		var bodyTag = document.getElementsByTagName ("body");
		defaultBody();
		var currentVal = bodyTag[0].style.fontSize;
		writeCookie("resize", currentVal, 10000);
		return false;
	}
	}
}

// Writes cookie
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.

function writeCookie(name, value, hours) {
  var expire = "";
  if(hours != null)  {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire;
}


// Read Cookie
// alert( readCookie("myCookie") );
function readCookie(name){
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)  {
    offset = document.cookie.indexOf(search);
    if (offset != -1)    {
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))    }
  }
  return cookieValue;
}

//Get Element by Class Name from: http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

//Function for converting title tags on images into caption
function addCaption(xClass) {
	var allImages = getElementsByClassName(document, "img", xClass);
	for ( var i=0; i < allImages.length; i++) {
		var imageCaption = document.createTextNode(allImages[i].title);
		var imageContainer = document.createElement("div");
		var imagePara = document.createElement("p");
		var imageWidth = allImages[i].getAttribute("width");
		var spareSpan = document.createElement("span"); //This adds an extra span. Useful for curved corners
		imagePara.appendChild(imageCaption);
		allImages[i].parentNode.insertBefore(imageContainer, allImages[i]);
		imageContainer.appendChild(allImages[i]);
		if ( allImages[i].title != "" ) {
		imageContainer.appendChild(imagePara); 
		}
		imageContainer.appendChild(spareSpan);		
		imageContainer.className = xClass
		spareSpan.className = "spareSpan"
		allImages[i].className = "imgCaption"
		imageContainer.style.width = imageWidth + "px";
		
    }
}

/*
Sweet Titles (c) Creative Commons 2005
http://creativecommons.org/licenses/by-sa/2.5/
Author: Dustin Diaz | http://www.dustindiaz.com
*/
var sweetTitles = { 
	xCord : 0,				// @Number: x pixel value of current cursor position
	yCord : 0,				// @Number: y pixel value of current cursor position
	tipElements : ['a','abbr','acronym'],	// @Array: Allowable elements that can have the toolTip
	obj : Object,			// @Element: That of which you're hovering over
	tip : Object,			// @Element: The actual toolTip itself
	active : 0,				// @Number: 0: Not Active || 1: Active
	init : function() {
		if ( !document.getElementById ||
			!document.createElement ||
			!document.getElementsByTagName ) {
			return;
		}
		var i,j;
		this.tip = document.createElement('div');
		this.tip.id = 'toolTip';
		document.getElementsByTagName('body')[0].appendChild(this.tip);
		this.tip.style.top = '0';
		this.tip.style.visibility = 'hidden';
		addEvent(document,'mousemove',this.updateXY);
		if ( document.captureEvents ) {
				document.captureEvents(Event.MOUSEMOVE);
		}
		var tipLen = this.tipElements.length;
		for ( i=0; i<tipLen; i++ ) {
			var current = document.getElementsByTagName(this.tipElements[i]);
			var curLen = current.length;
			for ( j=0; j<curLen; j++ ) {
				addEvent(current[j],'mouseover',this.tipOver);
				addEvent(current[j],'mouseout',this.tipOut);
				current[j].setAttribute('tip',current[j].title);
				current[j].removeAttribute('title');
			}
		}
	},
	updateXY : function(e) {
		if ( document.captureEvents ) {
			sweetTitles.xCord = e.pageX;
			sweetTitles.yCord = e.pageY;
		} else if ( window.event.clientX ) {
			sweetTitles.xCord = window.event.clientX+document.documentElement.scrollLeft;
			sweetTitles.yCord = window.event.clientY+document.documentElement.scrollTop;
		}
	},
	tipOut: function() {
		if ( window.tID ) {
			clearTimeout(tID);
		}
		if ( window.opacityID ) {
			clearTimeout(opacityID);
		}
		sweetTitles.tip.style.visibility = 'hidden';
	},
	checkNode : function() {
		var trueObj = this.obj;
		if ( this.tipElements.inArray(trueObj.nodeName.toLowerCase()) ) {
			return trueObj;
		} else {
			return trueObj.parentNode;
		}
	},
	tipOver : function() {
		sweetTitles.obj = this;
		tID = window.setTimeout("sweetTitles.tipShow()",500)
	},
	tipShow : function() {		
		var scrX = Number(this.xCord);
		var scrY = Number(this.yCord);
		var tp = parseInt(scrY+15);
		var lt = parseInt(scrX+10);
		var anch = this.checkNode();
		var addy = '';
		var access = '';
		if ( anch.nodeName.toLowerCase() == 'a' ) {
			addy = (anch.href.length > 25 ? anch.href.toString().substring(0,25)+"..." : anch.href);
			var access = ( anch.accessKey ? ' <span>Access key: ['+anch.accessKey+']</span> ' : '' );
		} else {
			addy = anch.firstChild.nodeValue;
		}
		if (addy.indexOf(window.location.hostname) == -1) {
		this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"<em>"+addy+"</em></p>";
		}
		else {
			this.tip.innerHTML = "<p>"+anch.getAttribute('tip')+"<em></em></p>";
		}
		if ( parseInt(document.documentElement.clientWidth+document.documentElement.scrollLeft) < parseInt(this.tip.offsetWidth+lt) ) {
			this.tip.style.left = parseInt(lt-(this.tip.offsetWidth+10))+'px';
		} else {
			this.tip.style.left = lt+'px';
		}
		if ( parseInt(document.documentElement.clientHeight+document.documentElement.scrollTop) < parseInt(this.tip.offsetHeight+tp) ) {
			this.tip.style.top = parseInt(tp-(this.tip.offsetHeight+10))+'px';
		} else {
			this.tip.style.top = tp+'px';
		}
		if (((anch.getAttribute('tip')) != "") || (addy.indexOf(window.location.hostname) == -1)) {
			this.tip.style.visibility = 'visible';
			this.tip.style.opacity = '.1';
			this.tipFade(10);	
		}
	},
	tipFade: function(opac) {
		var passed = parseInt(opac);
		var newOpac = parseInt(passed+10);
		if ( newOpac < 100 ) {
			this.tip.style.opacity = '.'+newOpac;
			this.tip.filter = "alpha(opacity:"+newOpac+")";
			opacityID = window.setTimeout("sweetTitles.tipFade('"+newOpac+"')",20);
		}
		else { 
			this.tip.style.opacity = '1';
			this.tip.style.filter = "alpha(opacity:100)";
		}
	}
};

// Opens a link in a new window when class = externalLink

// changed to class = external - Simon Chilton 4/7/07

function doPopups() {
  if (!document.getElementsByTagName) return false;
  var links = document.getElementsByTagName("a");
  for (var i=0; i < links.length; i++) {
    if (links[i].className.match("external")) {
		links[i].className = links[i].className + " newWinStyle";
		if (links[i].title == "") {
		links[i].title = "(new window)";
		}
		else {
		links[i].title = links[i].title + " (new window)";	
		}
	 	links[i].onclick = function(e) {
			if(!e)e=window.event;
			if(e.shiftKey || e.ctrlKey || e.altKey) return;
			window.open(this.href);
			return false;
			}
      }
    }
}

// ALTERNATING ROW COLOURS IN TABLE

// Main function, called when the page loads
function alternateRows() {
	var i, j;
	if (!document.getElementById) return
		var tables = document.getElementsByTagName("table");	  
		//search through tables in document
		for (i=0; i<tables.length; i++) {
			// If table has the right classname
				rows = tables[i].getElementsByTagName("tr");
				applyClasstoRows(rows);
		}
}

// Function, which is passed a table reference, applies the class 'even' to each even row, <tr> tag
function applyClasstoRows(myRows) {
	// search through rows
	for (j=0; j<rows.length; j++) {
	   // Set class for even rows (odd doesn't need to be set)
	   if (j%2 == 0) { 
		  rows[j].setAttribute("class", "alternate");
	   } 
	}
}


// Runs all the listed functions on the loading of the window

window.onload=function(){
//addResize();
//resizeT("stIncrease", "increase");
//resizeT("stDecrease", "decrease");
//resizeT("stReset", "reset");
alternateRows();
addCaption("imgLeft");
addCaption("imgRight");
doPopups();
sweetTitles.init();

}

