/*
	moduletabs.js
	============================
	ifl/alisatird
	16/08/2007

	Class for creating Module Tabs*  functionality - hiding and displaying content within a page
	* http://developer.yahoo.com/ypatterns/pattern.php?pattern=moduletabs
	
	TODO:  make sure that it works with multiple ModuleTabs on a page
*/

function ModuleTabs(element)
{
	if(!(element = document.getElementById(element))) //make 'element' a node, even if a string ID is passed in as the parameter
	{
		eval("throw new Error('ModuleTabs: element is not a valid element')") //throws a  helpful error message if the element can't be found. "throw" is invalid syntax in earlier browsers, wrapping it in an eval prevents it causing a parse error until it comes to execute it
	}
		
	this.aTabs = element.getElementsByTagName('a');
	this.aModules = [];
	
	for (var i = 0; i < this.aTabs.length; i++){
		
		// get references to modules
		var sAnchor = this.aTabs[i].hash;
		var sId = sAnchor.slice(1,sAnchor.length);
		this.aModules.push (document.getElementById(sId));
		
		// assign onclick function to tabs
		var oThis = this;
		this.aTabs[i].accociatedTagIndex = i;
		this.aTabs[i].onclick = function() {
			oThis.showTab(this.accociatedTagIndex);
			return !oThis._isCssOn(); // return false if css is on, true if off
		};
	}
}

ModuleTabs.prototype.showTab = function(selected){
	// hightlight selected tab
	for (var i = 0; i < this.aTabs.length; i++){
		//var elTab = bbcjs.dom.parent( this.aTabs[i] ); // this has been replaced with
		var elTabOne = bbcjs.dom.parent( this.aTabs[i] );
		var elTab = bbcjs.dom.parent( elTabOne );
		var elModule = this.aModules[i];
		if (i == selected){
			bbcjs.dom.addClassName( elTab, 'selected' );
			bbcjs.dom.addClassName( elModule, 'selected' );
			bbcjs.dom.removeClassName( elModule, 'hidden' );
		}
		else {
			bbcjs.dom.removeClassName( elTab, 'selected' );
			bbcjs.dom.removeClassName( elModule, 'selected' );
			bbcjs.dom.addClassName( elModule, 'hidden' );
		}
	}
}

ModuleTabs.prototype._isCssOn = function(){
	var blockCount = 0;
	
	bbcjs.forEach(this.aModules, function(elModule){
		if (bbcjs.dom.getStyle( elModule, 'display' ) == "block"){
			blockCount += 1;
		}
	});
	
	if(blockCount == this.aModules.length) // if all modules are display:block then assume css is off
	{
		return false;
	}
	else if (blockCount == 0) // if no styles set also assume that css is off (happens in IE 5 on MAC)
	{
		return false;
	}
	else
	{
		return true;
	}
}