/* ===========================================================================
 * SCHEDULE THE BEHAVIOURS
 * =========================================================================== 
 */

 
/* http://blog.peter-ryan.co.uk/2007/12/08/suckerfish-menus-with-hide-delay/ */
initMenu = function() 
{
	var timeout = 600;
	var cssClass = "hover";

	var queue = [];
	var reCSS = new RegExp("\\b" + cssClass + "\\b");
	var nav = document.getElementById("navigation");
	if(nav != null)
	{
		var sfEls = nav.getElementsByTagName("li");
		for (var i=0; i<sfEls.length; i++) {
	
			// mouseover and mouseout handlers for regular mouse based interface.
			sfEls[i].onmouseover = function() {
				queueFlush();
				this.className += " " + cssClass;
			}
			sfEls[i].onmouseout = function() {
				queue.push([setTimeout(queueTimeout, timeout), this]);
			}
	
			// focus and blur handlers for keyboard based navigation.
			sfEls[i].onfocus = function() {
				queueFlush();
				this.className += " " + cssClass;
			}
			sfEls[i].onblur = function() {
				queue.push([setTimeout(queueTimeout, timeout), this]);
			}
	
			// click event handler needed for tablet type interfaces (e.g. Apple iPhone).
			sfEls[i].onclick = function(e) {
				if (this.className.search(reCSS) == -1) {
					// CSS not set, so clear all sibling (and decendants) menus, and then set CSS on this menu...
					var elems = this.parentNode.getElementsByTagName("li");
					for (var i=0; i<elems.length; i++) {
						elems[i].className = elems[i].className.replace(reCSS, "");
					}
					this.className += " " + cssClass;
				} else {
					// CSS already set, so clear all decendant menus and then this menu...
					var elems = this.getElementsByTagName("li");
					for (var i=0; i<elems.length; i++) {
						elems[i].className = elems[i].className.replace(reCSS, "");
					}
					this.className = this.className.replace(reCSS, "");
				}
				if (e && e.stopPropagation)
					e.stopPropagation();
				else
					window.event.cancelBubble = true;
			}
		}
		
		var lists = nav.getElementsByTagName("ul");
		if(lists!=null && lists.length > 0)
		{
			var curvedCorner = document.createElement('div');
			curvedCorner.id = "navcorner";
			curvedCorner.style.height = lists[0].offsetHeight+"px";
			nav.appendChild(curvedCorner);
		}
	}

	queueFlush = function () {
		while (queue.length) {
			clearTimeout(queue[0][0]);
			queueTimeout();
		}
	}

	queueTimeout = function() {
		if (queue.length) {
			var el = queue.shift()[1];
			el.className = el.className.replace(reCSS, "");
		}
	}
	
	
	
}

function getChildrenByTagName(target, tagName)
{
	var children = target.childNodes;
	var matching = new Array();
	
	if (children != null)
	{
		for (var i = 0; i < children.length; i++)
		{
			if (children[i].nodeName.toLowerCase() == tagName)
			{
				matching[matching.length] = children[i];
			}
		}
	}
	
	return matching;
};

/* Author: Rebecca Skeers, rebecca@webmistress.com.au */
function tidyPage()
{
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++)
	{
		
		// Fix up the image caption widths
		// Alternatively add inline styles manually to every div with class 'image','image-left' or 'image-right' to add a width equal to the image width
		if(divs[i].className.match("image"))
		{
			var imagelist = divs[i].getElementsByTagName("img");
			var captionlist = divs[i].getElementsByTagName("div");
			
			if(imagelist.length>0)
			{
				if(imagelist[0].className.match("border"))
					divs[i].style.width = (imagelist[0].width+6)+"px";
				else
					divs[i].style.width = (imagelist[0].width)+"px";
					
				for (var j = 0; j < captionlist.length; j++)
				{
					if(captionlist[j].className.match("caption"))
					{
						captionlist[j].style.width = (imagelist[0].width-14)+"px";
					}
				}
			}
		}
		
		/* Add inner divs to boxes */
		/* Alternatively add these inner divs in the XHTML, however adding them in JS simplifies the XHTML code. Use whichever method works with the CMS. */
		if(divs[i].className.match("box"))
		{
			var boxcontent = divs[i].innerHTML;
			
			var innerDiv1 = document.createElement('div');
			innerDiv1.className="inner1";
			
			var innerDiv2 = document.createElement('div');
			innerDiv2.className="inner2";
			
			var innerDiv3 = document.createElement('div');
			innerDiv3.className="inner3";
			
			divs[i].innerHTML = '';
			innerDiv3.innerHTML = boxcontent;
			innerDiv2.appendChild(innerDiv3);
			innerDiv1.appendChild(innerDiv2);
			divs[i].appendChild(innerDiv1);
			divs[i].style.padding = "0px";
		}
		
		/* Add an inner div to the lead, if there is no feature image. */
		if(divs[i].className.match("lead"))
		{
			var featureImage = document.getElementById("featureimage");
			
			if(featureImage==null)
			{
				var leadcontent = divs[i].innerHTML;
				
				var innerLeadDiv = document.createElement('div');
				innerLeadDiv.className="inner1";
				
				divs[i].innerHTML = '';
				innerLeadDiv.innerHTML = leadcontent;
				divs[i].appendChild(innerLeadDiv);
			}
		}
	}
	
	/* Add the rounded corner to the feature image. */
	var featureImage = document.getElementById("featureimage");
	if(featureImage != null)
	{
		var cornerDiv = document.createElement('div');
		cornerDiv.innerHTML = '';
		cornerDiv.id="featureimagecorner";
		featureImage.appendChild(cornerDiv);
	}
	
	var tab1 = document.getElementById("tab1");
	var tab2 = document.getElementById("tab2");
	if(tab1 != null && tab2 != null)
	{
		var height1 = tab1 ? tab1.offsetHeight : 0;
		var height2 = tab2 ? tab2.offsetHeight : 0;
		
		//alert("tab height 1 = " + height1 " and tab height 2 = " + height2);
		
		if(height1 > height2)
		{
			tab1.style.height=(height1)+'px';
			tab2.style.height=(height1)+'px';
		}
		else if(height2 > height1)
		{
			tab1.style.height=(height2)+'px';
			tab2.style.height=(height2)+'px';
		}	
	}
	
	/* Align heights of home page columns */
	var homecol1a = document.getElementById("homecol1a");
	var homecol1b = document.getElementById("homecol1b");
	if(homecol1a != null && homecol1b != null)
	{
		var divs1 = homecol1a.getElementsByTagName("div");
		var divs2 = homecol1b.getElementsByTagName("div");
		
		if(divs1.length>1 && divs2.length>1)
		{
			if(divs1[0].className.match("box") && divs2[0].className.match("box"))
			{
				var height1 = divs1[1] ? divs1[1].offsetHeight : 0;
				var height2 = divs2[1] ? divs2[1].offsetHeight : 0;
			
				if(height1 > height2)
				{
					divs1[1].style.height=(height1)+'px';
					divs2[1].style.height=(height1)+'px';
					
					divs1[2].style.height=(height1)+'px';
					divs2[2].style.height=(height1)+'px';
				}
				else if(height2 > height1)
				{
					divs1[1].style.height=(height2)+'px';
					divs2[1].style.height=(height2)+'px';
					
					divs1[2].style.height=(height2)+'px';
					divs2[2].style.height=(height2)+'px';
				}
			}
		}
	}
}

function popUp(URL)
{
	eval("window.open('" + URL + "','windowName', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=550,height=550');");
}

function initLinks()
{
	if (!document.getElementsByTagName) 
 		return;
 		
 	var b = document.getElementsByTagName("body");
 	theBody = b[0];
 	if(theBody.className.match("new-window"))
 	{
	 	is_popup=true;
 		 window.focus();
	}
 
 	var anchors = document.getElementsByTagName("a");
 	for (var i=0; i<anchors.length; i++) 
 	{
   		var anchor = anchors[i];
   		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
   		{
     		anchor.target = "_blank";
 		}	
     	else if (anchor.className.match("print")) 
     	{
        	anchor.onclick = function() 
        	{
          		printPage();
          		return false;
        	};
    	}
 	}
}

function initTables()
{
	var tables = document.getElementsByTagName("table");
	
	for (var i = 0; i < tables.length; i++)
	{
		if(tables[i].className.match("data"))
		{
			var trs = tables[i].getElementsByTagName("tr");
			for (var j = 1; j < trs.length; j += 2)
			{
				if (trs[j].className == "")
				{
					trs[j].className = "alt";
				}
				else if(!trs[j].className.match("alt"))
				{
					trs[j].className += " alt";
				}
			}
		}
	}
	
	return true;
};

function setClass(el, str)
{
	if(el)
	{
		if (el.className == "")
			el.className = str;
		else
			el.className += " "+str;	
	}	
	return true;
}

function removeClass(el, str)
{
	if(el)
	{
		el.className=el.className.replace(new RegExp(" "+str+"\\b"), "");
		el.className=el.className.replace(new RegExp(str+"\\b"), "");	
	}
}

function show(elementID) 
{
	document.getElementById(elementID).style.display = 'block';
}

function hide(elementID) 
{
	document.getElementById(elementID).style.display = 'none';
}

function initTabs()
{
	var tabs = document.getElementById("tabslist");
	if(tabs != null)
	{
		var tab1 = document.getElementById("tab1");
		var tab2 = document.getElementById("tab2");
		var tab1link = document.getElementById("tab1link");
		var tab2link = document.getElementById("tab2link");
		
		if(tab1link != null && tab2link != null) 
		{
			tab1link.onclick = function() 
        	{
          		activateTab1();
          		return false;
        	};
        	
        	tab2link.onclick = function() 
        	{
          		activateTab2();
          		return false;
        	};
		}
	}	
	
	this.activateTab1 = function()
	{
		setClass(tab1link.parentNode.parentNode,"active");
		removeClass(tab2link.parentNode.parentNode,"active");
		
		setClass(tab2,"hidden");
		removeClass(tab1,"hidden");
		
		return false;
	}
	
	this.activateTab2 = function()
	{
		setClass(tab2link.parentNode.parentNode,"active");
		removeClass(tab1link.parentNode.parentNode,"active");
		
		setClass(tab1,"hidden");
		removeClass(tab2,"hidden");
		
		return false;
	}
}

function initNewsSlideshow() 
{
	var newsDiv = document.getElementById('news-rotator');
	var delayTime = 8000;
	var currentItem = 0;
	var totalItems = 0;
	
	if(newsDiv != null)
	{
		newsNav = document.createElement('div');
		newsNav.className = 'news-nav';
		var newsNavHtml = '<a class="prev" href="#" onclick="return back();">Previous</a>' + 
						  '<a class="next" href="#" onclick="return next();">Next</a>' +
						  '<a class="play" href="#" onclick="return play();" id="news-rotator-play">Play</a>' +
						  '<a class="pause" href="#" onclick="return pause();" id="news-rotator-pause" style="display:none;">Pause</a>';
		newsNav.innerHTML = newsNavHtml;
		//newsDiv.appendChild(newsNav);
		
		var newsItems = newsDiv.getElementsByTagName('div');
		var tempNav;
		
		for (var i = 0; i < newsItems.length; i++)
		{
			if(newsItems[i].className.match('news-story'))
			{
				tempNav = newsNav.cloneNode(true);
				newsItems[i].id = 'news-item-' + totalItems;
				newsItems[i].appendChild(tempNav);
				if (totalItems != 0) 
					hide(newsItems[i].id);
				totalItems++;
			}
		}		
		
		
	}
	
	this.display = function(itemNum) 
	{
		if (itemNum!=currentItem) 
		{		
			currentItemID = 'news-item-' + currentItem;
			opacity(currentItemID, 99, 0, 500);			
			setTimeout("hide('"+currentItemID+"')",500);

			newItemID = 'news-item-' + itemNum;
			opacity(newItemID, 0, 99, 500);
			setTimeout("show('"+newItemID+"')",50);
			
			currentItem = itemNum;
		}
		return false;
	}
	
	this.back = function() 
	{
		itemNum = currentItem - 1;
		if (itemNum < 0) 
			itemNum = totalItems - 1;
		display(itemNum);
		return false;
	}
	
	this.next = function() 
	{
		itemNum = currentItem + 1;
		if (itemNum >= totalItems) 
			itemNum = 0;
		display(itemNum);
		return false;
	}
	
	this.play = function()
	{
		newsTimer = setInterval('next()',delayTime);
		document.getElementById('news-rotator-play').style.display = 'none';
		document.getElementById('news-rotator-pause').style.display = 'inline';
		return false;
	}
	
	this.pause = function() 
	{
		clearInterval(newsTimer);
		document.getElementById('news-rotator-play').style.display = 'inline';
		document.getElementById('news-rotator-pause').style.display = 'none';
		return false;
	}
	
	if(newsDiv != null)
	{
		play();
	}
}


/* http://www.brainerror.net/scripts/javascript/blendtrans/ */
function opacity(id, opacStart, opacEnd, millisec) 
{
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

/* http://www.brainerror.net/scripts/javascript/blendtrans/ */
function changeOpac(opacity, id) 
{
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.WebkitOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

/* The JavaScript Anthology - James Edwards & Cameron Adams */
function attachEventListener(target, eventType, functionRef, capture)
{
	if (typeof target.addEventListener != "undefined")
	{ 
		target.addEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.attachEvent != "undefined")
	{
		var functionString = eventType + functionRef;
		target["e" + functionString] = functionRef;
		target[functionString] = function(event)
		{
			if(typeof event == "undefined")
			{
				event = window.event
			};

			target["e" + functionString](event);
        };
		target.attachEvent("on" + eventType, target[functionString]);
	}
	else
	{
		eventType = "on" + eventType;

		if (typeof target[eventType] == "function")
		{
			var oldListener = target[eventType];
			target[eventType] = function()
			{
				oldListener();
				return functionRef();
			}
		}
		else
		{
			target[eventType] = functionRef;
		}
	}

	return true;
};