var gb = {};

gb.Tabs = JSX.Class.create('gb.Tabs');
gb.Tabs.prototype =
{
	__target: null,
	__styleDefault: null,
	__styleActive: null,
	__active: 0,
	__tabs: null,
	
	__construct: function(target, defaultStyle, activeStyle)
	{
		JSX.Event.makeBroadcaster(this);
		
		this.__target		= document.getElementById(target);
		this.__styleDefault	= defaultStyle;
		this.__styleActive	= activeStyle;
		
		this.__tabs = new Array();
	},
	
	addTab: function(title, content, active, style)
	{
		active = (JSX.isBool(active) && active === true);
		if(active) this.__active = this.__tabs.length;
		
		var defaultImg	= '/img/'+ this.__styleDefault +'/'+ title +'.png';
		var activeImg	= '/img/'+ this.__styleActive +'/'+ title +'.png';
		
		var $tab =
		{
			title:		title,
			defaultImg:	defaultImg,
			activeImg:	activeImg,
			content:	document.getElementById(content),
			style:		style
		};
		this.__tabs.push($tab);
	},
	
	switchTab: function($tabId, $reload)
	{
		if(this.__active != $tabId || $reload == true)
		{
			$cur = this.__tabs[this.__active];
			$cur.className = '';
			$cur.img.src = $cur.data.defaultImg;
			try{ $cur.data.content.style.display = 'none'; }catch(e){}
			$cur.style.cursor = 'pointer';
			
			$new = this.__tabs[$tabId];
			$new.className = 'active';
			$new.img.src = $new.data.activeImg;
			try{ $new.data.content.style.display = 'block'; }catch(e){}
			$new.style.cursor = 'auto';
			
			this.__active = $tabId;
			this.dispatchEvent('onSwitch', [$new.data.title, $cur.data.title]);
		}
	},
	
	create: function()
	{
		var $tabs = '';
		var $before = this.__target.firstChild;
		
		var $iL = (this.__tabs.length - 1);
		for(var $i=0; $i<=$iL; $i++)
		{
			var $tab	= this.__tabs[$i];
			var $tabs	= this;
			var $active	= (this.__active == $i);
			var $style	= $tab.style;
			
			if(JSX.isEmpty($style))
			{
				var $style = ($i == $iL && $iL > 1)
					? 'tab2'
					: 'tab';
			}
			
			var $img = document.createElement('img');
				$img.setAttribute('src',	$tab.defaultImg);
				$img.setAttribute('title',	$tab.title);


			var $div = document.createElement('div');
				$div.setAttribute('id', $style);
			
			$div.onclick = function()
			{
				this.tab.switchTab(this.tabId);
			};
			
			$div.tabId	= $i;
			$div.tab	= this;
			$div.img	= $img;
			$div.data	= $tab;
			$div.style.cursor = 'pointer';
			$div.appendChild($img);
			
			$tab.content.style.display = 'none';
			
			this.__target.insertBefore($div, $before);
			this.__tabs[$i] = $div;
		}
		
		this.switchTab(this.__active, true);
	}
};

var Tabs = gb.Tabs;