/**
 * This class is used to create a tab control which has multiple pages of
 * content that can be switched between.
 */
var TabControl = new Class({

    initialize: function ()
    {
		this.pages = new Array();
    },

	// Adds a new page to the tab control.
    addPage: function ( handle, body )
    {
		
		var page = new Object();
		
		page.handle = handle;
		page.body   = body;
		
		var pageIndex = this.pages.length;
		this.pages[pageIndex] = page;
		
		this._setVisible( page, pageIndex == 0 );

		// Add the event handle to switch to the page when we click the handle.
		
		var tabControl = this;
		
		var f = function () {
				tabControl.showPage(pageIndex);
				tabControl.setCycleDelay(0);
			};
			
		$(handle).addEvent("click", f );	
	
	},
	
	// Switches to the specified page.
	showPage: function ( pageIndex, fade )
	{
		if (this.visiblePage)
		{
			this._setVisible(this.visiblePage, false, fade);
			this.visiblePage = null;
		}
		this._setVisible(this.pages[pageIndex], true, fade);
	},
	
	// Switches to the next page.
	showNextPage: function ( fade )
	{
		
		var pageIndex = this.pages.indexOf(this.visiblePage);
		pageIndex = (pageIndex + 1) % this.pages.length;
		
		this.showPage(pageIndex, fade);
	
	},
	
	// Sets the number of milliseconds before the tab control automatically
	// switches to the next tab. Set to 0 to stop auto cycling.
	setCycleDelay: function ( delay )
	{
	
		this.delay = delay;

		if (delay > 0)
		{

			var tabControl = this;
			
			var f = function () {
					tabControl.showNextPage( true );
					tabControl.setCycleDelay(tabControl.delay);
				};
			
			this.timer = setTimeout( f, delay);
			
		}
		else if (this.timer)
		{
			clearTimeout(this.timer);
		}
		
	},

	// Sets whether or not the page is visible. Internal use only.
	_setVisible: function ( page, visible, fade )
	{
		if (visible)
		{
			
			$(page.handle).addClass("selected");
			
			if (fade)
			{
				var morph = new Fx.Morph(page.body);
				morph.start({ opacity: '1' });
			}
			else
			{
				$(page.body).setStyle("opacity", "1");
			}
			
			$(page.body).setStyle("visibility", "visible");
			this.visiblePage = page;
			
		}
		else
		{
			
			$(page.handle).removeClass("selected");
			var hideBody = function() { $(page.body).setStyle("visibility", "hidden"); };
			
			if (fade)
			{
				var morph = new Fx.Morph(page.body);
				morph.start({ opacity: '0' }).chain( hideBody );
			}
			else
			{
				hideBody();
			}
			
		}
	}
	
});