Object.extend(Element, {
	getBehaviourProperty: function(element, attribute) {
		if(element.getAttribute('properties'))
			var properties = element.getAttribute('properties').split(", ");
		else
			return false;
		var result = properties.detect(function(item) {return item.indexOf(attribute) == 0;});
		if(result)
				return result = result.split(attribute + ":")[1];
		else
				return false;
	},
	addBehaviourProperty: function(element, attribute, value) {
		var properties = element.getAttribute('properties');
		if(properties)
			element.setAttribute("properties", properties + ", " + attribute + ":" + value);
		else
			element.setAttribute("properties", attribute + ":" + value);
	}
});


// General Library Functions
// TODO: Add find next non-text node to Library
var library = {

	// Add Event
	addEvent: function(elm, evType, fn, useCapture)
	{
		if(elm.addEventListener)
		{
			elm.addEventListener(evType, fn, useCapture);
			return true;
		}
		else if(elm.attachEvent)
		{
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		}
		else
		{
			elm['on' + evType] = fn;
		}
	},
	
	// Check for presence CSS selector in className
	checkClass: function(elm, selector, startsWith)
	{		
		if(!elm.className)
			return false;

		if(startsWith && (' ' + elm.className).indexOf(' ' + selector) != -1)
		{
			return true;
		}
		else if((' ' + elm.className + ' ').indexOf(' ' + selector + ' ') != -1)
		{
			return true;
		} 
		else
		{
			return false;
		}
	},
	
	// Find parent element that matches tag name
	ascendDom: function(elm, tag)
	{		
			while (elm.nodeName.toLowerCase() != tag && elm.nodeName.toLowerCase() != 'body')
				elm = elm.parentNode;
			return elm;
	},
	
	// Rollover Mouse Over IE currentTarget fix
  getMouseOverFor: function(node) {
    return function(e) { library.rolloverMouseOver(e, node); };
  },

	// Rollover Mouse Out IE currentTarget fix
  getMouseOutFor: function(node) {
    return function(e) { library.rolloverMouseOut(e, node); };
  },
	
	//  Rollover Mouse Over
	rolloverMouseOver: function(e, targetElement)
	{
		var element = window.event ? targetElement : e ? e.currentTarget : null;
    if (!element)
			return;
		element.className += ' hover';
	},

	//  Rollover Mouse Out
	rolloverMouseOut: function(e, targetElement)
	{
		var element = window.event ? targetElement : e ? e.currentTarget : null;
    if (!element)
			return;
		element.className = element.className.replace(/\shover/i, "");
	},
	
	//  Tooltip Activate
	tooltipActivate: function(e)
	{
		var element = window.event ? window.event.srcElement : e ? e.target : null;
    if (!element)
			return;

		element = library.ascendDom(element,"div");
		
		element.className += ' help-tip';
	},

	//  Tooltip Deactivate
	tooltipDeactivate: function(e, targetElement)
	{
		var element = window.event ? window.event.srcElement : e ? e.target : null;
    if (!element)
			return;
			
		element = library.ascendDom(element,"div");
		
		element.className = element.className.replace(/\shelp-tip/i, "");
	}
}




// Div Tag Behaviours
var divBehaviour = {

	init: function()
	{
		if(!document.getElementsByTagName)
			return;
		divBehaviour.divTags = document.getElementsByTagName('div');
		
		for(var i = 0; i < divBehaviour.divTags.length; i++)
		{
			// Rollover Behaviour
			if(library.checkClass(divBehaviour.divTags[i], "rollover"))
			{
				library.addEvent(divBehaviour.divTags[i], 'mouseover', library.getMouseOverFor(divBehaviour.divTags[i]), false);
				library.addEvent(divBehaviour.divTags[i], 'mouseout', library.getMouseOutFor(divBehaviour.divTags[i]), false);
			}
			
			// Switch Content Behaviour
			if(library.checkClass(divBehaviour.divTags[i], "switch"))
			{
				// NB This code only allows for one set of switch tags per page
				var switchElements = divBehaviour.divTags[i].getElementsByTagName('div');
				for(var j = 0; j < switchElements.length; j++)
				{
					if(library.checkClass(switchElements[j], "switch-section"))
    				divBehaviour.divSwitchSections[divBehaviour.divSwitchSections.length] = switchElements[j];
					if(library.checkClass(switchElements[j], "switch-tab"))
    				divBehaviour.divSwitchTabs[divBehaviour.divSwitchTabs.length] = switchElements[j];
				}

				for(var j = 0; j < divBehaviour.divSwitchTabs.length; j++)
				{
  				divBehaviour.divSwitchTabs[j].innerHTML = "<a href='javascript:divBehaviour.switchSection(" + j + ")'>" + divBehaviour.divSwitchTabs[j].innerHTML + "</a>";
				}
			}
				
		}
	},
	
	switchSection: function (section)
	{
		for(var i = 0; i < divBehaviour.divSwitchSections.length; i++)
		{
			divBehaviour.divSwitchSections[i].className = divBehaviour.divSwitchSections[i].className.replace(/\ssection-shown/g, "");
		}
		divBehaviour.divSwitchSections[section].className += " section-shown";
		
		for(var i = 0; i < divBehaviour.divSwitchTabs.length; i++)
		{
			divBehaviour.divSwitchTabs[i].className = divBehaviour.divSwitchTabs[i].className.replace(/\stab-shown/g, "");
		}
		divBehaviour.divSwitchTabs[section].className += " tab-shown";
	},
	
	divTags: [],
	divSwitchSections: [],
	divSwitchTabs: []
};
library.addEvent(window, 'load', divBehaviour.init, false);


var Behaviour = Class.create();
Behaviour.prototype = {
  initialize: function(selector, observers) {
		$$(selector).each(function(el){
				observers.each(function(observer){
				var event = observer[0], handler = observer[1];
					if(event == 'load')
						handler(el);
					else
						Event.observe(el, event, handler, false);	
				});
		});
  }
}

function debug(aMsg) {
   setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
}

function init(){
  loadBehaviours.each(function(el){
  	eval(el);
  });
}

var loadBehaviours = [];



function newWindow(e){
	var title = Element.getBehaviourProperty(e,'linkTitle');
	e.target = "new";
	e.title = title ? title : "This link opens in a new window";
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('A.new-window', [['load',newWindow]])";
function popupWindow(e)
{
	var title = Element.getBehaviourProperty(e,'linkTitle');
	e.target = "popupWindow";
	e.title = title ? title : "This link opens in a popup window";
}

function popupOpen(e) {
	var w = Element.getBehaviourProperty(Event.element(e),'popupWidth'), h = Element.getBehaviourProperty(Event.element(e),'popupHeight');
	if(!w||!h)
		{w=725; h=550;}
	var isVideo = /video/i.test(this.className);
	if (isVideo) { w = 450; h = 350; }
	
	var settings = isVideo
	       ? 'resize=1,location=0,menubar=0,toolbar=0,status=0,directories=0,scrollbars=0'
	       : 'resize=1,location=1,menubar=1,toolbar=1,status=1,directories=1,scrollbars=1';
	
	var popup = window.open('', 'popupWindow',settings+',top=' + Math.round(document.body.clientHeight/2 - h/2) + ',left=' + Math.round(document.body.clientWidth/2 - w/2) + ',width=' + w + ',height=' + h);
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('A.popup-window', [['load',popupWindow], ['click',popupOpen]])";
function addHover(e){Element.addClassName(Event.element(e), 'hover');}

function removeHover(e){Element.removeClassName(Event.element(e), 'hover');}

loadBehaviours[loadBehaviours.length] = "new Behaviour('.rollover', [['mouseover',addHover], ['mouseout',removeHover]])";
function setTabs(e) {
	$$("#" + e.id + " DIV.tab").each(function(tab, index){
			if(checkParentTab(tab,e)) {
					Element.addBehaviourProperty(tab, 'tabGroup' , e.id);
					Element.addBehaviourProperty(tab, 'tabIndex' , index);
					Event.observe(tab, 'click', switchTab, false);
			}
	});
	$$("#" + e.id + " DIV.block").each(function(block, index){
			if(checkParentTab(block,e)) {
					Element.addBehaviourProperty(block, 'tabGroup' , e.id);
					Element.addBehaviourProperty(block, 'tabIndex' , index);
			}
	})
}

function switchTab(e) {
	var group = Element.getBehaviourProperty(Event.element(e),'tabGroup'), index = Element.getBehaviourProperty(Event.element(e),'tabIndex');
	$$("#" + group + " DIV.tab").each(function(el){
		if(checkParentTab(el,$(group)))
					Element.removeClassName(el, 'tab-shown');
	})
	Element.addClassName(Event.element(e), 'tab-shown');
	$$("#" + group + " DIV.block").each(function(el){
		if(checkParentTab(el,$(group))) {
			if(Element.getBehaviourProperty(el,'tabIndex') == index)
				Element.addClassName(el, 'block-shown');
			else
				Element.removeClassName(el, 'block-shown');
		}
	})
}

function checkParentTab(element,parent) {
  var e = element;
  while (e != parent){
  	if (Element.hasClassName(e, 'tabs'))
				return false;
		e = e.parentNode;
  }
	return true;
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.tabs', [['load',setTabs]])";
function updateAjax(e) {
	var id = $(Element.getBehaviourProperty(Event.element(e),'ajaxId')), url = Element.getBehaviourProperty(Event.element(e),'ajaxUrl');
	Element.addClassName(id, 'updating');
	new Ajax.Updater(id, url, {onSuccess : function() {Element.removeClassName(id, 'updating');}});
}

function periodicAjax(e) {
    Ajax.Responders.register({onCreate:showLoader, onComplete:hideLoader});
	var selector = Element.getBehaviourProperty(e,'ajaxUpdateSelector'), interval = Element.getBehaviourProperty(e,'ajaxInterval');
	interval = interval ? interval :30;
    new PeriodicalExecuter(function(){
    	$$(selector).each(function(el){
    		var id = Element.getBehaviourProperty(el,'ajaxId'), url = Element.getBehaviourProperty(el,'ajaxUrl');
    		new Ajax.Updater($(id), url);
    	});
    }, interval);
}

function showLoader() {
	$$(".ajax-global-spinner").each(function(el){
		Element.addClassName(el, 'global-spinning');
	});
}

function hideLoader() {
	$$(".ajax-global-spinner").each(function(el){
		Element.removeClassName(el, 'global-spinning');
	});
}
loadBehaviours[loadBehaviours.length] = "new Behaviour('.update-ajax', [['click',updateAjax]])";
loadBehaviours[loadBehaviours.length] = "new Behaviour('.periodic-ajax', [['load',periodicAjax]])";

function setLabelShift(e) {Element.addClassName(e, 'label-shift');}

function hideLabel(e) {
	$$("DIV.search LABEL").each(function(l, index){
		Element.addClassName(l, 'hide-label');
	});
}

function showLabel(e) {
	$$("DIV.search LABEL").each(function(l, index){
		if($(l.getAttribute("for")).value == "")
			Element.removeClassName(l, 'hide-label');
	}); 
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.search LABEL', [['load',setLabelShift], ['click',hideLabel]])";
loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.search .text', [['focus',hideLabel], ['blur',showLabel], ['click',hideLabel]])";

function hideLabel2(e) {
	$$("DIV.tell-a-friend LABEL").each(function(l, index){
		Element.addClassName(l, 'hide-label');
	});
}

function showLabel2(e) {
	$$("DIV.tell-a-friend LABEL").each(function(l, index){
		if($(l.getAttribute("for")).value == "")
			Element.removeClassName(l, 'hide-label');
	}); 
}

loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.tell-a-friend LABEL', [['load',setLabelShift], ['click',hideLabel2]])";
loadBehaviours[loadBehaviours.length] = "new Behaviour('DIV.tell-a-friend .text', [['focus',hideLabel2], ['blur',showLabel2], ['click',hideLabel2]])";
function disableSubmit(s)
{
	// When we disable the submit button we lose its value so copy to hidden field instead
	var r = document.getElementById("submit-temp");
	r.name = s.name; 
	r.value = s.value; 
	
	s.name = "null";
	s.disabled = true; //'disabled';
	s.className = s.className + ' submit-disabled';
	s.value = 'Please wait...';
	return true;
}

function disableSubmitButtons(f)
{
	for (i = 0; i < f.length; i++) 
	{
		var s = f.elements[i];
		if(s.type == 'submit')
		{
			disableSubmit(s);
		}
	}
}

function setLoginSubmit()
{
	if(document.getElementById("passwordChoice2").checked == true)
	{
		document.getElementById("passwordText").focus();
		document.getElementById("loginButton").value = "Log in";
	}
	else
	{
		document.getElementById("loginButton").value = "Continue";
	}
}

function setLoginRadio(val)
{
	document.getElementById("passwordChoice2").checked = "checked";
	setLoginSubmit()
}

window.onload = init;

var message="";
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if 
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers) 
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function("return false")
