/* SBS Tab Manager
 * Version 1.0
 * Written by Timothy Chandler <tim@s3.net.au>
 * 
 * NOTE: This application requires Prototype version 1.6 and Scriptaculous version 1.8 (or greater) to run.
 */
var tabmanager=Class.create();
tabmanager.prototype=
{
	config:{},
	defaultConfig:
	{
		hook:	false,
		tabs:	[]
	},
	resetConfig: function()
	{
		this.config=
		{
			id:		this.defaultConfig.hook,
			tabs:	this.defaultConfig.tabs
		}
		return;
	},
	setConfig: function(overrideConfig)
	{
		if (overrideConfig)
		{
			if (overrideConfig.hook!=undefined && overrideConfig.hook!='')this.config.hook=overrideConfig.hook;
			if (overrideConfig.tabs!=undefined && overrideConfig.tabs!='')this.config.tabs=overrideConfig.tabs;
		}
		return;
	},
	initialize: function(options)
	{
		this.resetConfig();
		this.setConfig(options);
		if (!this.config.hook || $(this.config.hook)==null)
		{
			throw 'Unable to initialize tab manager. Hook was invalid.';
		}
		else if (!this.config.tabs.length)
		{
			throw 'Unable to initialize tab manager. No tabs were referenced to manage.';
		}
		else
		{
			for (i=0; i<this.config.tabs.length; i++)
			{
				if ($(this.config.tabs[i].id)==null)
				{
					throw 'Unable to initialize tab manager. One of the referenced tabs could not be found.';
				}
				else if ($(this.config.tabs[i].link)==null)
				{
					throw 'Unable to initialize tab manager. One of the referenced tab links could not be found.';
				}
				else
				{
					this.attachEvent(this.config.tabs[i]);
				}
			}
		}
		return this;
	},
	attachEvent: function(tab)
	{
		var object=$(tab.id);
		object.object=this;
		object.xid=object.identify();
		object.xlink=tab.link;
		object.xcontent=tab.content;
		object.observe
		(
			'click',
			function()
			{
				var $this=this.object;
				var xid=this.xid;
				var xlink=this.xlink;
				var parent=$(this).up();
				parent.childElements().each
				(
					function(element)
					{
						if (element.hasClassName('selected'))
						{
							element.removeClassName('selected');
							$this.cache.save(element.id);
						}
						if (element.identify()==xid)
						{
							element.addClassName('selected');
						}
						element.blur();
						$(element.xlink).hide();
						return;
					}
				);
				$(this.xlink).show();
				if (!$this.cache.isCached(this.id))
				{
					new Ajax.Updater
					(
						this.xlink,
						this.xcontent,
						{
							evalScripts: true
						}
					);
				}
			}
		);
		return;
	},
	cache:
	{
		_cache:new Hash(),
		save: function(name)
		{
			this._cache.set(name,true);
			return true;
		},
		isCached: function(name)
		{
			return (this._cache.get(name)==true)?true:false;
		}
	}
}