/*
	home.js for beyondthebean.com writen by www.featurecreep.com
	You are free to use any code you find in this file as long as you credit www.featurecreep.com
	comments or questions to info@featurecreep.com
*/

/*************************************************************************************
	INITIALISE SCREEN
*************************************************************************************/

function initialiseScreen(){

	//Accessible stylesheet?
	if(accessibilityCookie){
		var linkTags = document.getElementsByTagName("LINK");
		for(var i = 0 ; linkTags[i] ; i++){
			var linkTag = linkTags[i];
			if(linkTag.href.indexOf("screen.css") > -1) linkTag.disabled = true;
			else if(linkTag.href.indexOf("accessibility.css") > -1) {
				if(document.all)linkTag.rel = "stylesheet";
				linkTag.disabled = false;
			}
		}
	}
	
	//We're not sight impaired so JavaScript goes ahead if compatible
	else if(javascriptCompatible){
		
		//JAVASCRIPT CSS RULES// - now done in javascript.xsl to avoid fouc in msie6
		//appendToClassName(document.getElementsByTagName("HTML")[0], "JavaScript");
		
		// Create class name hashes //
		createClassNameHash();
		
		// Initialise main images //
		initMainImages();
		
		// Call page specific functions //
		if(nodeName == "what-we-are-like") initPeopleRollovers();
		if(nodePath == "/") NewsTicker.initialise();
		if(nodeName == "barista-tips") addTipH2Handlers();
		initialiseContentGroupExpanders();
		
		// H1 //
		var h1Color = "#333333";
		var h2Color = "#333333";
		var hoverBgColor = "#e5e5e5";
		
		// Background window colour //
		window.backgroundColor = "#FFFFFF";
		
		// SIFR //	
		var wmode = nodeName = "transparent";
		var replaceH1 = true;
		if(topSectionPath == '/news' && nodeName !='news') replaceH1 = false;
		if(replaceH1)sIFR.replaceElement(named({sSelector:"h1 span", sFlashSrc:"/swf/vag-rounded.swf", fContentHandler:btbFontWrapper, nLeading:-10, sWmode:wmode}));
		sIFR.replaceElement(named({sSelector:"p#pageTitle", sFlashSrc:"/swf/vag-rounded.swf", fContentHandler:btbFontWrapper, nLeading:-10, sWmode:wmode}));
		
		// Forgotten password link
		if(document.getElementsByTagName("BODY")[0].className.indexOf("MyAccount") > -1){
			var anchors = document.getElementsByTagName("A");
			for(var i = 0 ; anchors[i] ; i++){
				if(anchors[i].href.toString().indexOf("forgotten-password") > -1){
					attachEvents_forgottenPasswordAnchor(anchors[i]);
				}
			}
		}		
	}
}



/*************************************************************************************
	Delegate class. Development only.
	Warning: Not IE5 compatible as it uses Function.apply
*************************************************************************************/
var Delegate = {
	create : function (target, handler) {
		// Create delegate function
		var delegate = function() {
			// Get reference to self
            var self = arguments.callee;
            
			// Call handler with arguments
			return self.handler.apply(self.target, arguments);
		};
		
		// Pass in local references
		delegate.handler = handler;
		delegate.target = target;
		
		// Return the delegate function.
		return delegate;
	}
}


/*************************************************************************************
	ACCESSIBILITY
*************************************************************************************/

var accessibilityCookie = readCookie("accessibility") == "true" ? true : false;

function accessibleView(){  
	createCookie("accessibility", "true", 365);
	document.location.reload();
	return false;
}
function normalView(){  
	createCookie("accessibility", "false", 365);
	document.location.reload();
	return false;
}

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=/";
}
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;
}










/*************************************************************************************
	MAIN IMAGES
*************************************************************************************/
/*
array mainImages, empty if no images, populated if there are images
div class mainImages, holds the first image
MainImage class, with static members and also instances representing flip images (including the one in the source)
*/





function initMainImages() {
	// Abort if there are no main images for this page or if there are no images to flip to
	if (!classNameHash.mainImages || mainImages.length == 0) return;
	
	// Get reference to main images div
	var content = classNameHash.mainImages[0];
	
	// Get reference to current image
	var img = content.getElementsByTagName("IMG")[0];

	// Get reference to front image div, skip up twice if the image is wrapped in an anchor (i.e. it's a link)
	MainImage.imageDivFront = img.parentNode.nodeName == "A" ? img.parentNode.parentNode : img.parentNode;
	MainImage.imageDivFront.style.zIndex = 10;
	MainImage.imageDivFront.style.position = "absolute";

	// Add new back image div as sibling of existing image div, behined it in stacking order
	MainImage.imageDivBack = document.createElement("DIV");
	MainImage.imageDivFront.parentNode.insertBefore(MainImage.imageDivBack, MainImage.imageDivFront);
	MainImage.imageDivBack.style.zIndex = 9;
	MainImage.imageDivBack.style.position = "absolute";
	
	// Copy dimensions of current image
	MainImage.imageWidth = img.width;
	MainImage.imageHeight = img.height;

	// Determine whether to enable alpha by reading style of current image (or browser sniffing for IE6)
	MainImage.alphaEnabled = MainImage.alphaEnabled && (getCurrentStyle(img, "opacity", "opacity") || browser == "msie6");

	// Populate images array starting with existing image
	MainImage.images = new Array();
	MainImage.images[0] = new MainImage(MainImage.images.length, MainImage.getElementAssetId(img), img.src, img.alt,img.parentNode.href);

	for (var i = 0; i < mainImages.length; i++) {
		// Add images defined in simple mainImages in source of page array to array
		MainImage.images[MainImage.images.length] = new MainImage(MainImage.images.length, mainImages[i].id, mainImages[i].src, mainImages[i].alt, mainImages[i].href);
	}
	
	// Set selected image index to current image index
	MainImage.selectedImageIndex = 0;
	
	// Create thumbnails if more than one image and not on home page
	if (MainImage.images.length > 1 && nodePath != "/") {
		var imagesPerRow = 5;
		var firstImageTop = Math.ceil(MainImage.images.length / imagesPerRow) * 16;
		var anchorOffsetTop = 107, anchorOffsetRight = 162;

		for (var i = 0; i < MainImage.images.length; i++) {	
			var mainImage = MainImage.images[i];
		
			var thumbDiv = document.createElement("DIV");
			image = thumbDiv.appendChild(document.createElement("IMG"));
			image.src = "/images/system/thumbnail-" + mainImage.id + ".jpg";
			image.width = 18;
			image.height = 11;
			thumbDiv.className = i == 0 ? "selectedThumb" : "thumb";
			
			// Calculate offset for image thumbnail to be able to right align
			var indexOffset = MainImage.images.length % imagesPerRow == 0 ? 0 : (imagesPerRow - (MainImage.images.length % imagesPerRow));
			
			// Position thumbnail
			thumbDiv.style.right = ((23 * ((imagesPerRow - 1) - ((i + indexOffset) % imagesPerRow))) + anchorOffsetRight) + "px";
			thumbDiv.style.top = (anchorOffsetTop - firstImageTop + (Math.floor((i + indexOffset) / imagesPerRow) * 16)) + "px";
			
			thumbDiv.style.zIndex = 100;
			document.getElementById("content").appendChild(thumbDiv);

			mainImage.thumbDiv = thumbDiv;
			thumbDiv.obj = mainImage;
			/*FIND ALTERNATIVE TO DELEGATE CLASS IF IE5 INCOMPATIBLE*/
			thumbDiv.onclick = Delegate.create(mainImage, mainImage.onThumbClick);
		}
	}
	//cache the images needed, when the last loads, it will kick off roll
	MainImage.imageCache = new Array();
	MainImage.stillToLoad = MainImage.images.length - 1;
	MainImage.onImageLoad = function(){
		MainImage.stillToLoad -= 1;
		//alert(MainImage.stillToLoad);
		if(MainImage.stillToLoad == 0) MainImage.startRoll();
	}
	
	
	for (var i = 1; i < MainImage.images.length; i++) {	
		MainImage.imageCache[i-1] = new Image();
		MainImage.imageCache[i-1].src = MainImage.images[i].src;
		MainImage.imageCache[i-1].onload = MainImage.imageCache[i-1].onerror = MainImage.imageCache[i-1].onabort =  MainImage.onImageLoad;
	}
}




// Constructor, called by initMainImages for both the image in the page source and for the ones in the page source array
function MainImage(index, id, src, alt, href) {
	
	// Store constructor parameters for later use
	this.index = index;
	this.id = id;
	this.src = src;
	this.alt = alt;
	this.href = href;

	// Create new Image object into which our image can be loaded
	this.image = new Image(MainImage.imageWidth, MainImage.imageHeight);
	
	// Set backreference to this for event handlers
	this.image.obj = this;
	
	// Set event handler for image load event
	this.image.onload = Delegate.create(this, this.onImageLoad);
}

// Whether or not we're rolling the images
MainImage.rolling = true;

// Number of frames (steps) for fade
MainImage.fadeFrames = 20;

// Amount of time to fade images, in milliseconds
MainImage.fadeTime = 400;

// Amount of time between image fades
MainImage.displayTime = 5000;

// Index of currently selected (shown) image
MainImage.selectedImage = 0;

// Whether alpha fading is enabled. Set to false to override style & browser 
// sniffing and disable alpha fading
MainImage.alphaEnabled = true;

MainImage.startRoll = function() {
	MainImage.rolling = true;
	MainImage.timer = setTimeout("MainImage.onTimerRoll()", MainImage.displayTime);
}

MainImage.stopRoll = function() {
	MainImage.rolling = false;
	clearTimeout(MainImage.timer);
}


// Utility function to get asset id from an element's class name
MainImage.getElementAssetId = function(element) {

	// Start with passed in element
	currentElement = element;
	
	// WHile there are elements left to check
	while (currentElement) {
		// Get list of CSS class names applied to element
		var classNames = currentElement.className.split(" ");
		
		// For each CSS class
		for (var i = 0 ; i < classNames.length; i++) {
			var className = classNames[i];
			
			// If this is an asset class
			if (className.indexOf("asset") == 0) {
				// Return asset ID after 'asset' prefix
				return className.substr(className.indexOf("asset") + 5);
			}
		}
		
		// Check parent element
		currentElement = currentElement.parentNode;
	}
}

// Event handler for image transition timer
MainImage.onTimerRoll = function() {
	if (windowLoaded){
		// Show next image
		var nextIndex = MainImage.selectedImageIndex == MainImage.images.length-1 ? 0 : MainImage.selectedImageIndex + 1;
		MainImage.images[MainImage.selectedImageIndex].deselect();
		MainImage.images[(nextIndex)].select();
	}
}

MainImage.fadeIn = function(index, frame) {
	// Default to first frame
	frame = frame || 1;
	
	// Calculate opacity accoring to frame using linear transition
	var opacity = Math.round((frame / MainImage.fadeFrames) * 100);
	
	// Set image opacity 
	if (browser == "msie6") {
		// MSIE6 opacity is from 0-100 using alpha filter
		MainImage.imageDivFront.style.filter = "alpha(opacity=" + opacity + ")";
		
	} else {
		// Convert opacity from 0-100 range to 0-1 range
		opacity = opacity / 100;
		
		// Fix for firefox blinking - never reach full opacity
		opacity -= 0.01;
		
		// Set opacity style
		MainImage.imageDivFront.style.opacity = opacity;
	}
	
	// If this isn't the last frame
	if (frame != MainImage.fadeFrames) {
		// Calculate time to fade one frame
		var fadeFrameTime = Math.round(MainImage.fadeTime / MainImage.fadeFrames);
		
		// Set timeout for next fade frame
		setTimeout("MainImage.fadeIn(" + index + ", " + (frame + 1) + ")", fadeFrameTime);
	}
}



MainImage.prototype.select = function() {
	// If image has already loaded
	if (this.image.src.length > 0 && this.image.complete) {
		
		// Call onload event handler
		this.onImageLoad();
		
	// Otherwise
	} else {
		// Start preloading image
		MainImage.loadingImage = this;
		this.image.src = this.src;
	}
}

MainImage.prototype.deselect = function(){ 
	// If image has a thumnnail, set style to deselected
	if (this.thumbDiv) {
		this.thumbDiv.className = "thumb";
	}
}

// Event handler for click on image thumbnail
MainImage.prototype.onThumbClick = function(){
	// Stop rolling
	MainImage.stopRoll();
	
	// If not already the currently selected image
	if (this.index != MainImage.selectedImageIndex){
		// Show selected image
		this.select(); 
	}
}

// Event handler for image preloading timer
MainImage.prototype.onImageLoad = function() {
	
	// Deselect old image
	MainImage.images[MainImage.selectedImageIndex].deselect();

	// Clear out background div
	var numChildren = MainImage.imageDivBack.childNodes.length
	for (var i = 0; i < numChildren; i++) {
		MainImage.imageDivBack.removeChild(MainImage.imageDivBack.lastChild);
	}
	
	// If this is an image link
	if (this.href && this.href.length > 0) {
		// Create anchor and set href
		var anchor = document.createElement("A");
		anchor.setAttribute("href", this.href);
		
		// Create new img tag inside anchor
		anchor.appendChild(document.createElement("IMG"));
		
		// Add anchor to background div
		MainImage.imageDivBack.appendChild(anchor);
		
	// Otherwise
	} else {
		// Create new img tag and add directly to background div
		MainImage.imageDivBack.appendChild(document.createElement("IMG"));
	}

	// Get reference to img tag in background div
	var img = MainImage.imageDivBack.getElementsByTagName("IMG")[0];

	// Set appropriate attributes
	img.setAttribute("src", this.src);
	img.setAttribute("alt", this.alt);
	img.setAttribute("width", MainImage.imageWidth);
	img.setAttribute("height", MainImage.imageHeight);

	// Swap front/back references
	var temp = MainImage.imageDivFront;
	MainImage.imageDivFront = MainImage.imageDivBack;
	MainImage.imageDivBack = temp;

	// Fade image in if browser supports opacity setting
	if (MainImage.alphaEnabled) {
		MainImage.fadeIn(this.index);
	}

	// Put new front image infront of old front image on the z axis
	MainImage.imageDivFront.style.zIndex = 10;
	MainImage.imageDivBack.style.zIndex = 9;

	// Store selected image index
	MainImage.selectedImageIndex = this.index;
	
	// Roll the next image
	if (MainImage.rolling) {
		MainImage.timer = setTimeout("MainImage.onTimerRoll()", MainImage.displayTime);		
	}
	
	// If image has a thumnnail, set style to selected
	if (this.thumbDiv) {
		this.thumbDiv.className = "selectedThumb";
	}
}

/*************************************************************************************
	PEOPLE ROLLOVERS
*************************************************************************************/


// names of each person
Person.names = ["jem", "nikki", "miranda", "jonathan", "terry", "caroline", "kim", "zak", "helen", "ben", "rob"];

	
// collection for Peron objects
Person.people = new Array();

// create people
function initPeopleRollovers(){
	for(var i = 0 ; Person.names[i] ; i++){
		Person.people[Person.people.length] = new Person(classNameHash[Person.names[i]][0], Person.names[i],i);
	}
}
// Assign handlers for each person
Person.assignImgHandlers = function(element, obj){
	element.onmouseover = function(){obj.over()};
	element.onmouseout = function(){obj.out()};
}

Person.height = 0;

// Constructor function
function Person(group, name,index){
	// The div element for the person
	this.group = group;
	// The unique name for the person
	this.name = name;
	// The image element within the div
	this.img = this.group.getElementsByTagName("IMG")[0];
	// div within group with a className containing "Text"
	this.textDiv = null;
	var divs = this.group.getElementsByTagName("DIV");
	for(var i = 0 ; divs[i] ; i++) if(divs[i].className.indexOf("Text") > -1)this.textDiv = divs[i];
	
	//Create an over image to overlay the existing image and add to group
	this.overImage = document.createElement("IMG");
	this.overImage.className = "overImage";
	this.overImage.src = "/images/people-over/" + this.name + ".gif";
	this.group.appendChild(this.overImage);
	
	// Create and load a title image, add to group. Not for Ben.
	if(this.name != "ben"){
		this.title = document.createElement("IMG");
		this.title.src = "/images/people-over/titles/" + this.name + ".gif";
		this.title.className = "title";
		this.textDiv.appendChild(this.title);
	//remove from layout space to allow mouse events
	this.textDiv.style.position = "absolute";
	}	
	//Add to height if necessary to push page down
	Person.height = Math.max(this.group.offsetHeight + this.group.offsetTop + 40, Person.height);
	
	//Assign handlers, done outside of this scope. Abstracted as done for 
	// several elements
	Person.assignImgHandlers(this.img,this);
	Person.assignImgHandlers(this.overImage,this);
	Person.assignImgHandlers(this.textDiv,this);
}

// Instance methods
Person.prototype.over = function(){
	this.group.style.zIndex = 1000;
	this.overImage.style.visibility = "visible";
	this.img.style.visibility = "hidden";
	this.textDiv.style.visibility = "visible";
}
Person.prototype.out = function(){
	this.img.style.visibility = "visible";
	this.group.style.zIndex = 10;
	this.overImage.style.visibility = "hidden";
	this.textDiv.style.visibility = "hidden";
}





/*************************************************************************************
	FLIPPYS
*************************************************************************************/

function initialiseContentGroupExpanders() {
//If appropriate page class not found, or there is no classNameHash array, return
if(!/( ?WhatWeDo ?)|( ?WhatWeBelieve ?)|( ?knowledge-section ?)/.test(document.body.className)) return;
if(typeof(classNameHash.mainContent) != "object") return;
	var mainContentDiv = classNameHash.mainContent[0];
	var contentGroups = new Array();
	for(var i = 0 ; i < mainContentDiv.childNodes.length ; i++){
		var child = mainContentDiv.childNodes[i];
		if(child.nodeName.match(/^div$/i) && child.className.match(/ ?Group ?/)) contentGroups[contentGroups.length] = child;
	}
	ContentGroupExpander.expanders = new Array();
	for (var i = 0 ; i < contentGroups.length ; i++) {
		ContentGroupExpander.expanders[i] = new ContentGroupExpander(contentGroups[i], i);
	}
}
//Flippy constructor
function ContentGroupExpander(groupDiv, index) {
	this.groupDiv = groupDiv;
	this.h2 = groupDiv.getElementsByTagName("H2")[0];
	this.expanded = false;
	var self = this;
	
	
	//Cache images if first expader
	if(index == 0){
		var bgSrc = getCurrentStyle(this.h2, "background-image", "backgroundImage");
		var bgSrcArr = bgSrc.split("/");
		var colour = bgSrcArr[bgSrcArr.length-3];
		
		window.flippyImageCache = new Array(3);
		for(var i = 0 ; i < 3 ; i++) flippyImageCache[i] = new Image();
		flippyImageCache[0].src = "/images/" + colour + "/flippy/closed-over.gif";
		flippyImageCache[0].src = "/images/" + colour + "/flippy/expanded-over.gif";
		flippyImageCache[0].src = "/images/" + colour + "/flippy/expanded.gif";
	}

	this.h2.onmouseover = function() { self.onMouseOver(); }
	this.h2.onmouseout = function() { self.onMouseOut(); }
	this.h2.onmouseup = function() { self.onClick(); }
}

ContentGroupExpander.positionFooter = function() {
	var courtesyNav = document.getElementById("courtesyNavigation");
	courtesyNav.style.visibility = "hidden";
	courtesyNav.style.bottom = "-1px";
	setTimeout('document.getElementById("courtesyNavigation").style.bottom = "0px";',10);
	courtesyNav.style.visibility = "visible";
}

ContentGroupExpander.prototype.expand = function() {
	for (var i = 0; i < this.groupDiv.childNodes.length; i++) {
		var child = this.groupDiv.childNodes[i];
		
		if (child.nodeType != 1 || child == this.h2) continue;
		child.style.display = "block";
	}
	this.expanded = true;
	this.onMouseOver();

	ContentGroupExpander.positionFooter();
}

ContentGroupExpander.prototype.collapse = function() {
	for (var i = 0; i < this.groupDiv.childNodes.length; i++) {
		var child = this.groupDiv.childNodes[i];
		
		if (child.nodeType != 1 || child == this.h2) continue;
		child.style.display = "none";
	}
	this.expanded = false;
	this.onMouseOver();

	ContentGroupExpander.positionFooter();
}

ContentGroupExpander.prototype.toggle = function() {
	if (this.expanded) {
		this.collapse();
	} else {
		this.expand();
	}
}


ContentGroupExpander.prototype.onMouseOver = function() {
	if(this.expanded) this.h2.className = "expanded-over";
	else this.h2.className = "over";
}

ContentGroupExpander.prototype.onMouseOut = function() {
	if(this.expanded) this.h2.className = "expanded";
	else this.h2.className = "";
	
}

ContentGroupExpander.prototype.onClick = function() {
	this.toggle();
}



function addTipH2Handlers(){

	var tips = classNameHash.tip;
	
	if(tips){
		var h2s = new Array();
		for(var i = 0 ; tips[i] ; i++){
			h2s[i] = tips[i].getElementsByTagName("H2")[0];
		}
		
		for(var i = 0 ; i < h2s.length ; i++){
				
			h2s[i].onmousemove = function(){
				this.style.backgroundPosition = this.className == "expanded" ? "-1339px 0px" : "-447px 0px";
			}
			h2s[i].onmouseout = function(){
				this.style.backgroundPosition = this.className == "expanded" ? "-892px 0px" : "0 0";
			}
			h2s[i].onmouseup = function(){
				var expanded = this.className == "expanded";
				var ps = this.parentNode.getElementsByTagName("P");
				for(var i = 0 ; ps[i] ; i++) ps[i].style.display = expanded ? "none" : "block";
				this.className = expanded ? "" : "expanded";
				this.onmousemove();
				var courtesyNav = document.getElementById("courtesyNavigation");
				courtesyNav.style.visibility = "hidden";
				courtesyNav.style.bottom = "-1px";
				setTimeout('document.getElementById("courtesyNavigation").style.bottom = "0px";',10);
				courtesyNav.style.visibility = "visible";
			}
		}
	}
}




function btbFontWrapper(content) {
	return content.replace(/BTB/g, "<font face='VAG Rounded BT'>BTB</font>");
}

function getFeaturedNavigationItemBgColor(node, i, limit, bgColor, hoverBgColor) {
	return /* (node.parentNode.className.indexOf("selected") > -1) ? hoverBgColor : */ bgColor;
}



/*************************************************************************************
	NEWS TICKER
*************************************************************************************/
var NewsTicker = {};

// Amount of time to display news item in milliseconds
NewsTicker.displayTime = 5000;

// Auto-start the ticker?
NewsTicker.rolling = true;

// Time to wait before showing first story
NewsTicker.initialDelay = 100;

NewsTicker.currentItemIndex = 0;

NewsTicker.initialise = function() {

	if( typeof classNameHash.latestNews != "object") return;

	NewsTicker.items = new Array();

	var list = NewsTicker.list = classNameHash.latestNews[0].getElementsByTagName("UL")[0];
	
	var listItems = list.getElementsByTagName("LI");
	
	for (var i = 0; i < listItems.length; i++) {
		var item = new NewsTickerItem(NewsTicker.items.length, listItems[i]);
		NewsTicker.items.push(item);
		item.hide();
	}

	setTimeout(NewsTicker.start, NewsTicker.initialDelay);	
}

NewsTicker.start = function() {
	NewsTicker.list.style.visibility = "visible";
	NewsTicker.items[0].show();

	if (NewsTicker.rolling) {
		NewsTicker.startRoll();
	}
}

NewsTicker.startRoll = function() {
	NewsTicker.rolling = true;
	NewsTicker.timer = setInterval(NewsTicker.onTimerRoll, NewsTicker.displayTime);
}

NewsTicker.stopRoll = function() {
	NewsTicker.rolling = false;
	clearInterval(NewsTicker.timer);
	clearInterval(NewsTicker.typeTimer);
}

NewsTicker.onTimerRoll = function() {
	var nextItemIndex = NewsTicker.currentItemIndex == NewsTicker.items.length - 1 ? 0 : NewsTicker.currentItemIndex + 1;
	NewsTicker.items[NewsTicker.currentItemIndex].hide();
	NewsTicker.items[nextItemIndex].show();
}

NewsTicker.onNewsItemMouseOver = function() {
	NewsTicker.items[NewsTicker.currentItemIndex].showAll();
	NewsTicker.stopRoll();
}

NewsTicker.onNewsItemMouseOut = function() {
	NewsTicker.startRoll();
}

NewsTicker.onTypeTimerRoll = function() {
	var newsItem = NewsTicker.items[NewsTicker.currentItemIndex];

	// Move next character out of span
	do {
		var character = newsItem.invisibleTextNode.nodeValue.substring(0,1);
		newsItem.invisibleTextNode.nodeValue = newsItem.invisibleTextNode.nodeValue.substring(1);
		newsItem.visibleTextNode.nodeValue += character;
		var nextChar = newsItem.invisibleTextNode.nodeValue.substring(0,1);
	} while (browser.indexOf("safari") == 0 && (character == " " || character == "-" || nextChar == " "));
	
	if (newsItem.invisibleTextNode.nodeValue.length == 0) {
		clearInterval(NewsTicker.typeTimer);
	}
}


function NewsTickerItem(index, listItem) {
	// Store constructor parameters for future reference
	this.index = index;
	this.listItem = listItem;
}

NewsTickerItem.prototype.initialise = function() {
	if (this.initialised) return;

	var anchor = this.listItem.getElementsByTagName("A")[0];
	
	anchor.onmouseover = NewsTicker.onNewsItemMouseOver;
	anchor.onmouseout = NewsTicker.onNewsItemMouseOut;
	
	// Remove all non-element nodes
	for (var i = anchor.childNodes.length - 1; i >= 0; i--) {
		if (anchor.childNodes[i].nodeType != 1) {
			anchor.removeChild(anchor.childNodes[i]);
		}
	}
	
	var span = anchor.getElementsByTagName("SPAN")[0];
	
	this.invisibleTextNode = span.firstChild;
	this.visibleTextNode = anchor.insertBefore(document.createTextNode(" "), span);

	span.style.visibility = "hidden";
	
	this.initialised = true;
}

NewsTickerItem.prototype.showAll = function() {
	NewsTicker.currentItemIndex = this.index;
	this.visibleTextNode.nodeValue += this.invisibleTextNode.nodeValue;
	this.invisibleTextNode.nodeValue = "";
	clearInterval(NewsTicker.typeTimer);
}

NewsTickerItem.prototype.show = function() {
	this.initialise();
	
	NewsTicker.currentItemIndex = this.index;
	if (this.visibleTextNode.nodeValue != " ") {
		this.invisibleTextNode.nodeValue += this.visibleTextNode.nodeValue;
	}
	this.visibleTextNode.nodeValue = "";
	this.listItem.style.visibility = "visible";
	
	NewsTicker.typeTimer = setInterval(NewsTicker.onTypeTimerRoll, 100 + Math.round((Math.random() * 60) - 30));
}

NewsTickerItem.prototype.hide = function() {
	this.listItem.style.visibility = "hidden";
	clearInterval(NewsTicker.typeTimer);
}

NewsTickerItem.prototype.onTimerRoll = function() {
}




/*
Utility
*/
function submitForm(button){

	var errorString = "";
	var labels  = button.form.getElementsByTagName("LABEL");
		
	for(var i = 0 ; i < labels.length ; i++){
		var label = new Label(labels[i]);
		errorString += label.validate();
	}
		
	if(errorString.length == 0) {
		// Create new hidden form field with same values as submit button
		// This is required to make sure it ends up in xml vars collection
		var hiddenFormField = document.createElement("input");
		hiddenFormField.type = "hidden";
		hiddenFormField.name = button.name;
		hiddenFormField.value = button.value;
		button.form.appendChild(hiddenFormField);
		
		button.form.submit();
	} else {
		errorString = "Sorry, your form has not been sent.\n\n" + errorString + "\n\nPlease enter the correct information and try  again.";
		alert(errorString);
	}
	return false;
}
function Label(label){
	this.label = label;
	var _for = label.getAttribute("FOR");
	//IE6 works differently:
	if(!_for)_for = label.attributes["for"].value;
	this.subject = document.getElementById(_for);
}
Label.prototype.validate = function(){
	if(this.subject.className.indexOf("required")>-1){
	
		var pattern = /\s/g;
		var test = this.subject.value.replace(pattern, "");
		if(test.length == 0) {
			var errorString = "- " + this.label.firstChild.nodeValue + " must contain some text\n";
			
			// Get reference to label's input
			if(this.subject.nodeName == "SELECT") {
				errorString = "- Please select an option from '" + this.label.firstChild.nodeValue + "'";
			}

			return errorString;
		}
	
		if(this.subject.className.indexOf("email")>-1){
			var validPattern =  /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/
			if(!validPattern.test(this.subject.value)) return "- " + this.label.firstChild.nodeValue + " is not valid\n";
		}
	}
	return "";
}

function getNextOutermost(element, targetNodeName){
	var examine = element.parentNode;
	while(examine && examine.nodeName != targetNodeName) examine = examine.parentNode;
	return examine;
}


// Event class
function _Event(evt){
	this._rawEvent = evt ? evt : window.event ? event : null;
}

_Event.prototype.getRawEvent = function(){
	return(this._rawEvent);
}

_Event.prototype.getTargetNode = function(){
	var evt = this.getRawEvent();
	var target = evt.target ? evt.target : evt.srcElement ? evt.srcElement : null;
	while(target.nodeType > 1) target = target.parentNode;
	return target;
}

_Event.prototype.getNextOuterDIVWithId = function() {
	var evt = this.getRawEvent();
	var target = this.getTargetNode();
	while(target && (target.nodeName !== "DIV" || target.id == "")) target = target.parentNode;
	return target;	
}


//Elements by class

var classNameHash = new Array();

function createClassNameHash(){
	var elements = document.all ? document.all : document.getElementsByTagName("*");
	
	for(var i = 0 ; i < elements.length ; i++){
	
		var element = elements[i];
		var name = element.className;
		if (name == null || name.length == 0) continue;
		
		//pop the element onto the array
		classNameHash[classNameHash.length] = element;
		
		//Accomodate multiple classes
		var classes = name.split(" ");
		
		//Create an array as a property to the array if one doesn't already exist for each class of the element
		
		for(var j = 0 ; j < classes.length ; j++){
			if(!classNameHash[classes[j]])classNameHash[classes[j]] = new Array();
			classNameHash[classes[j]][classNameHash[classes[j]].length] = element;
		}
	
	}
}




function attachEvents_forgottenPasswordAnchor(anchor){
	anchor.onclick = function(){
		var email = "";
		var inputs = document.getElementsByTagName("INPUT");
		for(var i = 0 ; inputs[i] ; i++){
			if(inputs[i].name == "email") email = inputs[i].value;
		}
		if(email.length > 0 && window.encodeURIComponent){
			document.location.href = this.href + "?email=" + encodeURIComponent(email);
			return false;
		}
		return true;
	}
}






/*************************************************************************************
	DEBUGGER
*************************************************************************************/
// Show the debug window
function showDebug() {
  window.top.debugWindow =
      window.open("",
                  "Debug",
                  "left=0,top=0,width=900,height=400,scrollbars=yes,"
                  +"status=yes,resizable=yes");
  window.top.debugWindow.opener = self;
  // open the document for writing
  window.top.debugWindow.document.open();
  window.top.debugWindow.document.write(
      "<HTML><HEAD><TITLE>Debug Window</TITLE></HEAD><BODY><PRE>\n");
}

// If the debug window exists, then write to it
function debug(text) {
  
  if (!window.top.debugWindow || ! window.top.debugWindow.closed) {
  	showDebug();
  }
  text = ">> " + text;
  window.top.debugWindow.document.writeln(text);
}









initialiseScreen();