(function($) {

$.widget("ui.fcpTabs", {
	
	tabCount: 0,
	boxTabs: [],
	boxTabContents: [],

	_create: function() 
	{
		this._tabify();
	},
	
	_tabify: function()
	{
		this.boxTabs = this.element.find("div.boxTitle li.tab");
		this.boxTabContents = this.element.find("div.boxTabContent > div");
		
		// Set tab count
		this.tabCount = this.boxTabs.length;
		
		// Reassign this
		var me = this;
		
		// Set links
		this.boxTabs.children("a").each(function(index, element) {
			var link = $(this);
			
			// Setup onlick handler
			link.click(function() {
				if(this.href.substr(this.href.length - 1) == "#")
				{
					// Activate current tab
					me.boxTabs.removeClass("active");
					$(me.boxTabs[index]).addClass("active");
					
					// Show current content
					me.boxTabContents.each(function() {
						$(this).hide();
					});
					$(me.boxTabContents[index]).show();
					
					return false;
				}
			});
			
			// Set onfocus handler (hide grey border)
			link.focus(function() {
				this.blur();
			});
		});
		
		this._ensureVisibleTabActive();
	},
	
	_ensureVisibleTabActive: function()
	{
		// Check if a visible tab is active
		if(this.boxTabs.filter("li.active:visible").length > 0)
		{
			return;
		}
		
		// Activate the first visible tab
		this.boxTabs.filter("li:visible").first().children("a").click();		
	},
	
	showTab: function(index)
	{
		// Find index by id
		if(isNaN(index))
		{
			index = this.boxTabs.index(this.boxTabs.filter("#" + index));
		}
		
		if(index >= 0)
		{
			this.boxTabs.eq(index).show();
			
			this._ensureVisibleTabActive();
		}
	},
	
	hideTab: function(index)
	{
		// Find index by id
		if(isNaN(index))
		{
			index = this.boxTabs.index(this.boxTabs.filter("#" + index));
		}
		
		if(index >= 0)
		{
			this.boxTabs.eq(index).hide();
			this.boxTabContents.eq(index).hide();
			
			this._ensureVisibleTabActive();
		}
	}

});

})(jQuery);
