function addEvent(obj, evType, fn){
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	}
	else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	}
	else {
		return false;
	}
}

// set up the search box so that the label disappears when focussed
function searchCriteriaFocussed() {
	document.getElementById('criterialabel').style.display = 'none';
}
function searchCriteriaBlurred() {
	if(document.searchform.criteria.value === '') {
		document.getElementById('criterialabel').style.display = 'inline';
	}
}
function toggleNextDiv(e) {
	Event.stop(e);
	if(!e) e = window.event;
	tog = $(e.target || e.srcElement).up().next('div');
	if (tog)
		tog.toggle();
}
function initialiseM3webpage() {
	addEvent(document.getElementById('criteria'), 'focus', searchCriteriaFocussed);
	addEvent(document.getElementById('criteria'), 'blur', searchCriteriaBlurred);

	if (typeof($$) !== 'undefined') {
		var hash = location.hash.substring(1);

		/* hide all kpis */
		var anchor = $$(".showpi");
		if (anchor.length) {
			hide_kpis = $$(".showpi ~ div");
			if (hide_kpis)
				hide_kpis.invoke("hide");
			anchor.each(function(elem) {
				elem.innerHTML = '<a href="#">' + elem.innerHTML + '</a>';
				addEvent(elem.down('a'), 'click', toggleNextDiv);
			});
		}
		
		/* specialist module - hide all except fragment */
		var anchor = $$("div.specialist-module a[name="+hash+"]");
		if (hash && anchor.length) {
			hide_mods = $$("div.specialist-module").select(function(elem) {
				return !elem.down("a[name="+hash+"]");
			});
			if (hide_mods)
				hide_mods.invoke("hide");
			anchor[0].scrollIntoView(true);
		}

		/* auto-redirect-link */
		var a = $('auto-redirect-link');
		if (a) window.location = a.href;

		/* faqs - show fragment */
		var anchor = $(hash);
		if (anchor && hash.startsWith('faq') && hash.endsWith('link')) {
			$(hash.substring(0,hash.length-4)).show();
		}
		
		/* faqs - show all if all hidden (by faq code) */
		var links = $$(".faqanswer").map(function(elem) {
			return elem.previous().down("a");
		});
		if (!links.any(function(elem) { return elem.visible(); })) {
			links.invoke("show");
		}
		
		/* faqs - hide empty categories */
		if ($$('.faqanswer').first() && $$('h1').first().innerHTML.match(/frequently/i)) {
			var categories = $$("#mainbody > h2");
			categories.each(function(elem) {
				 next = elem.next();
				 while (next && next.tagName != 'H2') {
					 if (next.tagName == 'H4') {
						 var link = next.down("a");
						 if (link && link.visible())
							return; // continue each
					 }
					 next = next.next();
				 }
				 elem.hide();
			});
		}
		
		/* faqs - now page stable, scroll to fragment - OBSOLETE, fragment is only thing visible
		anchor.scrollIntoView(true); */
	}
}

addEvent(window, 'load', initialiseM3webpage);

