/****************************************************************
 * Class-handling helper functions
 ****************************************************************
 */
var aCachedREs = new Array();
function classCacheRE(sClass) {
	if(!aCachedREs[ sClass ])
		aCachedREs[ sClass ] = new RegExp('^\\s*(.*)\\b('+ sClass +')\\b(.*)\\s*$');
	return( aCachedREs[ sClass ] );
}

function classMatch(oObject, sClass) {
	if(oObject && oObject.className)
		return(classCacheRE(sClass).exec(oObject.className));
	return(false);
}

function classAdd(oObject, sClass) {
	if(oObject && !classMatch(oObject, sClass))
		oObject.className += ' '+ sClass;
}

function classDel(oObject, sClass) {
	var aMatches = classMatch(oObject, sClass);
	if(aMatches)
		oObject.className = aMatches[1] + aMatches[ aMatches.length - 1 ];
}

/****************************************************************
 * Array Prototypes
 ****************************************************************
 */
// Add the ability to push something onto the end of an array
if(!Array.prototype.push) {
	Array.prototype.push = function( mNewEntry ) {
		this[ this.length++ ] = mNewEntry;
	}
}

// Add the ability to pop something off the end of an array
if(!Array.prototype.pop) {
	Array.prototype.pop = function() {
		var mReturnValue = false;
		if(this.length) {
			mReturnValue = this[ this.length - 1 ];
			this.length--;
		}
		return(mReturnValue);
	}
}

if(!Array.prototype.search) {
	Array.prototype.search = function(sTerm) {
		var iIndex = this.length;
		while(iIndex--) {
			if(this[ iIndex ] == sTerm) return(true);
		}
		return(false);
	}
}

/****************************************************************
 * getElementsByClassName
 ****************************************************************
 */
// Moz or IE.6
if(!navigator.userAgent.match(/MSIE/) ||
	navigator.userAgent.match(/MSIE 6\./)) {

	function getElementsByClassName(sClassName, oObject, bNoRecursion) {
		var aoReturnValue = new Array();

		// Default the object to the document
		if(!oObject) {
			oObject = document.body;
		}

		// Recursion: get all the elements and run through them
		if(!bNoRecursion) {
			var aoElements = oObject.getElementsByTagName('*');
			for(var iElement = 0; iElement < aoElements.length; iElement++) {
				if(classMatch(aoElements[ iElement ], sClassName)) {
					aoReturnValue.push( aoElements[ iElement ] );
				}
			}

		// No recursion: Just run run through all the children
		} else {
			for(var oChild = oObject.firstChild; oChild; oChild = oChild.nextSibling) {
				if(classMatch(oChild, sClassName)) {
					aoReturnValue.push(oChild);
				}
			}
		}

		return(aoReturnValue);
	}

// IE 5.x
} else {
	function getElementsByClassName(sClassName, oObject, bNoRecursion) {
		var aoReturnValue = new Array();

		// Object supplied
		if(oObject) {
			for(var oChild = oObject.firstChild; oChild; oChild = oChild.nextSibling) {
				if(classMatch(oChild, sClassName)) {
					aoReturnValue.push(oChild);
				}

				// Recurse if possible / allowed
				if(oChild.hasChildNodes() && !bNoRecursion) {
					aoReturnValue = aoReturnValue.concat( getElementsByClassName(sClassName, oChild) );
				}
			}

		// No object and *no* recursion: Just run run through all the children
		} else if(bNoRecursion) {
			for(var oChild = document.body.firstChild; oChild; oChild = oChild.nextSibling) {
				if(classMatch(oChild, sClassName)) {
					aoReturnValue.push(oChild);
				}
			}

		// No object and recursion: get all the elements and run through them
		} else {
			for(var iElement = 0; iElement < document.all.length; iElement++) {
				if(classMatch(document.all[ iElement ], sClassName)) {
					aoReturnValue.push(document.all[ iElement ]);
				}
			}
		}

		return(aoReturnValue);
	}
}

/****************************************************************
 * Select boxes helper functions
 *****************************************************************
 */

function vAddOption (oParentElement, sValue, sText, oParams) {

	var oOption = document.createElement('option');
	oOption.value = sValue;
	oOption.innerHTML = sText;

	if (oParams) {
		for(var sName in oParams) {
			oOption[sName] = oParams[sName];
		}
	}

	vAppendElement(oParentElement, oOption);
}

function vAppendElement(oParentElement, oChildElement) {
	try {
		oParentElement.appendChild(oChildElement);
	} catch(ex) {
		oParentElement.add(oChildElement);
	}
}

function vRemoveOptions(oEl) {
	if(oEl && oEl.options && oEl.options.length)
		while(oEl.options.length)
			try {
				oEl.remove(0);
			} catch(ex) {}
}


/****************************************************************
 * Cookie helper functions
 ****************************************************************
 */

function setCookie(sName, sValue, oExpires, sPath, sDomain, sSecure) {

	document.cookie =
		sName + "=" + escape(sValue) +
		((oExpires) ? "; expires=" + oExpires.toGMTString() : "") +
		((sPath) ? "; path=" + sPath : "") +
		((sDomain) ? "; domain=" + sDomain : "") +
		((sSecure) ? "; secure" : "");

}

function getCookie(sName) {

	var sCookie = document.cookie;
	var sPrefix = sName + "=";
	var iBegin = sCookie.indexOf("; " + sPrefix);

	if (iBegin == -1) {

		iBegin = sCookie.indexOf(sPrefix);

		if (iBegin != 0) {
			return null;
		}

	} else {
		iBegin += 2;
	}

	var iEnd = sCookie.indexOf(";", iBegin);

	if (iEnd == -1)
		iEnd = sCookie.length;

	return unescape(sCookie.substring(iBegin + sPrefix.length, iEnd));

}



/****************************************************************
 * Lanbel-handling helper functions
 ****************************************************************
 */
function initOverLabels() {
	if (!document.getElementById)
		return;

	var aLabels = getElementsByClassName('sys_overlabel');

	for (var i = 0; i < aLabels.length; i++) {

		var oLabel, sFieldId, oField;
		oLabel = aLabels[i];

		sFieldId = oLabel.htmlFor || oLabel.getAttribute('for');
		if (!sFieldId || !(oField = document.getElementById(sFieldId))) {
			continue;
		}

		classAdd(oLabel, 'sys_overlabel-apply');

		if (oField.value === '') {
			toggleLabel(oLabel, false);
		} else {
			toggleLabel(oLabel, true);
		}

		// Handle clicks to show and hide labels.
		oField.onfocus = function() {
			toggleLabel(oLabel, true);
		};

		oField.onblur = function() {
			if (oField.value === '') {
				toggleLabel(oLabel, false);
			}
		};

		// Handle clicks to label elements (for Safari).
		oLabel.onclick = function() {
			oField.focus();
		};

	}
}

function toggleLabel(oLabel, bHide) {
	oLabel.style.display = (bHide) ? 'none' : 'block';
}

/****************************************************************
 * Video transcripts
 ****************************************************************
 */
function initVideoTranscripts() {

	var aTranscripts = getElementsByClassName('transcript');

	for(var i = 0; i < aTranscripts.length; i++) {

		var oTranscript = aTranscripts[i];

		// Create toggle link
		var oPara = document.createElement('p');
		classAdd(oPara, 'transcript_toggle');

		oPara.appendChild(document.createTextNode('('));

		var oLink = oPara.appendChild(document.createElement('a'));
		oLink.href = '#';
		oLink.oTranscript = oTranscript;
		oPara.appendChild(document.createTextNode(')'));

		// Create handlers for toggle link
		oLink.onclick = function() {
			this.oTranscript.style.display = (this.oTranscript.bHide) ? 'none' : 'block';

			if (this.firstChild) {
				this.removeChild(this.firstChild);
			}

			var sLinkText = (this.oTranscript.bHide) ? 'Open commentary' : 'Close commentary';
			this.appendChild(document.createTextNode(sLinkText));

			this.oTranscript.bHide = !this.oTranscript.bHide;

			return false;
		};

		// Add toggle link to document
		//oTranscript.parentNode.insertBefore(oPara, oTranscript);
		aVideo = getElementsByClassName('video', oTranscript.parentNode);
		aVideo[0].appendChild(oPara);

		// By default hide transcript
		oTranscript.bHide = true;
		oLink.onclick();

	}

}

var sRotateImageCookie = 'rotateImage';
var sRotateImagePath = '/images/home/';
var iRotateImagesNum = 7;

function initImageRotate() {

	if (!document.getElementById)
		return;

	var oImage = document.getElementById('topImageReplace');

	if (oImage) {

		// Get current image number
		var iImage = (getCookie(sRotateImageCookie)==null) ? 0 : getCookie(sRotateImageCookie);

		// Go to next image
		if (++iImage > iRotateImagesNum) {
			iImage = 1;
		}

		// Update image with new value
		oImage.style.backgroundImage = 'url(' + sRotateImagePath + iImage + '.jpg)';
		oImage.id = 'topImage';

		var oDate = new Date();
		oDate.setTime(oDate.getTime()+(365*24*60*60*1000));

		// Save current value
		setCookie(sRotateImageCookie, iImage, oDate);

	}

}

/****************************************************************
 * Calendar popouts
 ****************************************************************/

var iTimeout;

function initCalendar() {

	var oEventsCalendar = document.getElementById('eventsCalendar');

	if (!oEventsCalendar)
		return;

	var oBody = document.getElementsByTagName('body')[0];
	var aEventCells = getElementsByClassName('event', oEventsCalendar);

	for (var i = 0; i < aEventCells.length; i++) {

		var oCell = aEventCells[i];
		var oLink = oCell.getElementsByTagName('a')[0];
		var oPopout = oCell.getElementsByTagName('div')[0];
		oCell.oPopout = oPopout;
		oPopout.oCell = oCell;

		oCell.onmouseover = function(oEvent) {
			updatePopout(oEventsCalendar, this.oPopout, oEvent);
		};

		oCell.onmousemove = function(oEvent) {
			updatePopout(oEventsCalendar, this.oPopout, oEvent);
		}

		oCell.onmouseout = function() {
			hidePopout(this.oPopout);
		};

		oPopout.onmousemove = function(oEvent) {
			hidePopout(this);
		}

	}

}

function updatePopout(oEventsCalendar, oPopout, oEvent) {

	var mouseX, mouseY;
	oEvent = oEvent || window.event;
	var oCell = oEvent.target || oEvent.srcElement;

	if (!window.opera && typeof oEvent.offsetX != 'undefined') {
		// Use offset coordinates and find common offsetParent
		var oPos = { x: oEvent.offsetX, y: oEvent.offsetY };

		// Send the coordinates upwards through the offsetParent chain.
		var oEl = oCell;
		while (oEl) {
			oEl.mouseX = oPos.x;
			oEl.mouseY = oPos.y;
			oPos.x += oEl.offsetLeft;
			oPos.y += oEl.offsetTop;
			oEl = oEl.offsetParent;
		}

		// Look for the coordinates starting from the reference element.
		var oEl = oEventsCalendar;
		var oOffset = { x: 0, y: 0 }
		while (oEl) {
			if (typeof oEl.mouseX != 'undefined') {
				mouseX = oEl.mouseX - oOffset.x;
				mouseY = oEl.mouseY - oOffset.y;
				break;
			}
			oOffset.x += oEl.offsetLeft;
			oOffset.y += oEl.offsetTop;
			oEl = oEl.offsetParent;
		}

		// Reset stored coordinates
		var oEl = oCell;
		while (oEl) {
			oEl.mouseX = undefined;
			oEl.mouseY = undefined;
			oEl = oEl.offsetParent;

		}

	} else {

		// Use absolute coordinates
		var oPos = getAbsolutePosition(oEventsCalendar);
		mouseX = oEvent.pageX  - oPos.x;
		mouseY = oEvent.pageY - oPos.y;

	}

	// Adjust for size of popout
	mouseX -= 298;
	mouseY -= 26;

	// Apply new coordinates to popout
	oPopout.style.left = mouseX + "px";
	oPopout.style.top = mouseY + "px";

	oPopout.style.zIndex = '10';
	oPopout.style.overflow = 'visible';

}

function getAbsolutePosition(oElement) {

	var oCoords = { x: oElement.offsetLeft, y: oElement.offsetTop };

	if (oElement.offsetParent) {
		var oTmp = getAbsolutePosition(oElement.offsetParent);
		oCoords.x += oTmp.x;
		oCoords.y += oTmp.y;
	}

	return oCoords;

}

function hidePopout(oPopout) {
	oPopout.style.left = "-10000px";
}



/****************************************************************
* Map overlays
***************************************************************/
//var mapImg;
var mapAreas;

function initMapOverlays(mapName) {
//mapImg = document.getElementById(mapName + 'Image');
mapAreas=document.getElementById(mapName + 'Regions').getElementsByTagName('area');

	for (var i=0;i<mapAreas.length;i++) {
		preloadImage= new Image();
		preloadImage.src = "/images/map/" + mapAreas[i].id + ".png";
		preloadImage=null;

		mapAreas[i].onmouseover = function() { regionHover(this.id,mapName); }
		mapAreas[i].onfocus = function() { regionHover(this.id,mapName); }

		mapAreas[i].onmouseout = function() { regionUnHover(this.id,mapName); }
		mapAreas[i].onblur = function() { regionUnHover(this.id,mapName); }

		/*document.getElementById(mapAreas[i].id + 'Nav').onmouseover = function() { navHover(this.id,mapName) };
		document.getElementById(mapAreas[i].id + 'Nav').onfocus = function() { navHover(this.id,mapName) };

		document.getElementById(mapAreas[i].id + 'Nav').onmouseout = function() { navUnHover(this.id,mapName) };
		document.getElementById(mapAreas[i].id + 'Nav').onblur = function() { navUnHover(this.id,mapName) };*/

	}
}

function regionHover(region,mapName) {
	document.getElementById(mapName + 'Image').src = "/images/map/" + region + ".png";
	//document.getElementById(region + 'Nav').parentNode.className="hover";
}

function navHover(region,mapName) {
	document.getElementById(mapName + 'Image').src = "/images/map/" + region.substring(0,region.length-3) + ".png";
}


function regionUnHover(region,mapName) {
	document.getElementById(mapName + 'Image').src = "/images/map/" + mapName + ".png";
	//document.getElementById(region + 'Nav').parentNode.className="";
}

function navUnHover(region,mapName) {
	document.getElementById(mapName + 'Image').src = "/images/map/" + mapName + ".png";
	//document.getElementById(region).parentNode.className="";
}

/****************************************************************
 * Generic JS history - added Sunya 19/03/2009
 ****************************************************************
 */
function initBacklink() {

	linksArr=getElementsByClassName('backClick');

	for(i=0; i<linksArr.length;i++){
		linksArr[i].setAttribute("onclick", 'history.go(-1);return false;');
	}
}


/****************************************************************
 * Set functions to run on load
 ****************************************************************
 */
window.onload = function () {
	initOverLabels();
	initVideoTranscripts();
	initImageRotate();
	initCalendar();
	initBacklink();
}
