xAddEventListener(window, 'load', TabStrips_Init);

function TabStrips_Init()
{
	for( var i=0; i<TabStrip_Controls.length; i++ ) 
	{
		var s	= TabStrip_Controls[i];
		var ts	= xGetElementById(s.tabstrip);
		if ( ts != null )
			ts.tabStrip = new TabStrip(ts, s.activetab, s.tabs);
	}
}

function TabStrip(ts, at, t)
{
	this.element	= ts;
	this.activeTab	= getAspNetFormElementByName(at);
	
	// Setup tabs
	this.tabs = new Array(t.length);
	for ( var i=0; i<t.length; i++)
		this.tabs[i] = new Tab(this, i, t[i], i == this.activeTab.value);

	this.activateTab(this.activeTab.value);
}

TabStrip.prototype.activateTab = function(index)
{
	this.activeTab.value = index;
	this.tabs[index].activate();
}

TabStrip.prototype.switchTab = function(index)
{
	var current = this.activeTab.value;
	if ( current != index )
	{
		this.tabs[current].deactivate();
		this.activateTab(index);
	}
}

function Tab(ts, index, s, active)
{
	var el = xGetElementById(s.tab);
	el.tab			= this;
	this.element	= el;
	this.tabStrip	= ts;
	this.index		= index;
	this.hoverCss	= s.hoverCss;
	this.activeCss	= s.activeCss;
	this.panel		= xGetElementById(s.panel);
	xAddEventListener(this.element,"click",Tab.eventHandlers.click );
	addHoverClassName(this.element,this.hoverCss);

	if (!active) this.deactivate();
}

Tab.eventHandlers = 
{
	click: function(e)
	{
		var tab = Tab.eventHandlers.getTab(e);
		tab.tabStrip.switchTab(tab.index);
	},

	getEventTarget:	function(e)
	{
		if (e) { return e.target || window.event.srcElement; }
		return null;
	},
	
	getTab: function(e)
	{
		var el = Tab.eventHandlers.getEventTarget(e);
		while (el != null && el.tab == null)
			el = el.parentNode;
		return el ? el.tab : null;
	}
}

Tab.prototype.deactivate = function()
{
	removeClassName(this.element, this.activeCss);
	// Hide panel
	if ( this.panel )
		this.panel.style.display='none';
}

Tab.prototype.activate = function()
{
	addClassName(this.element, this.activeCss);
	// Show panel
	if ( this.panel )
		this.panel.style.display='block';
}

