
function TabControl(elemObj)
{
	Dispatcher.call(this, "onswitch");
	var switchGrPath = "#{0}_tabcontrol > .tabswitch";
	var blockGrPath = "#{0}_tabpages > .tabpage";
	var switchPath = "tabswitch_{0}";
 	var blockPath = "tab_{0}";

	if (elemObj.className.match(/switchboard/))
	{
		switchGrPath = "#{0}_switchboard > .switch";
		blockGrPath = "#{0}_switchblocks > .switchblock";
		switchPath = "switch_{0}";
		blockPath = "block_{0}";
	}

	var ctrl = this;
	if (elemObj.id.match(/(.*)_(?:tabcontrol|switchboard)/))
	{
		this.id = elemObj.id;
		this.name = RegExp.$1;
		this.switchPath = switchPath;
		this.blockPath = blockPath;
		this.switchGrPath = switchGrPath.format(this.name);
		this.blockGrPath = blockGrPath.format(this.name);

		$(this.switchGrPath).each(function ()
		{
			if (this.id.match(/switch_(.*)/))
			{
				this.name = RegExp.$1;
				var link = this.tagName == "A" ? this : $("a", this)[0];
				if (link != null)
				{
					link.name = this.name;
					link.onclick = function ()
					{
						if (ctrl.showTab(this.name))
							return false;
						else
							return true;
					};
				}
			}
		});
	}
}
TabControl.prototype = new Dispatcher;

TabControl.prototype.showTab = function (itemName)
{
	var targetID = this.blockPath.format(itemName);
	if ($("#" + targetID).length != 0)
	{
		$(this.blockGrPath).each(function ()
		{
			if (this.id == targetID)
				$(this).addClass("active");
			else
				$(this).removeClass("active");
		});

		var targetSwitchID = this.switchPath.format(itemName);
		$(this.switchGrPath).each(function ()
		{
			if (this.id == targetSwitchID)
				$(this).addClass("active");
			else
				$(this).removeClass("active");
		});

		if (TabControl.callback && typeof TabControl.callback === "function")
			TabControl.callback(itemName);

		this.fireEvent("onswitch", { item: itemName });
		return true;
	}
	else
		return false;
}

TabControl.initEvents = new Array();
TabControl.initialized = false;
TabControl.instances = null;
TabControl.callback = null;

TabControl.registerInitEvent = function (func)
{
	if (TabControl.initialized)
		func();
	else
		TabControl.initEvents.push(func);
}

TabControl.executeInitEvent = function (func)
{
	for (var i = 0; i < TabControl.initEvents.length; i++)
	{
		TabControl.initEvents[i]();
	}
	TabControl.initEvents = new Array();
}

TabControl.setup = function ()
{
	if ($.browser.msie)
		setTimeout(initialiseTabContol, 500);
	else
		initialiseTabContol();

	function initialiseTabContol() {
		var elems = $(".tabcontrol,.switchboard");
		if (elems.length != 0)
		{
			TabControl.instances = new Object;
			for (var i = 0; i < elems.length; i++)
			{
				TabControl.instances[elems[i].id] = new TabControl(elems[i]);
			}
			
			TabControl.initialized = true;
			TabControl.executeInitEvent();
		}
	}
}

$(document).ready(TabControl.setup);
