var Fabtabs = Class.create();

Fabtabs.prototype = 
{
	initialize: function( element, options ) 
	{
		this.options = Object.extend( { 
										activeClass: 		'active',
										linkSelector: 		'li a',
										autoLinkExternal: 	true 
									  }, options || {} );
		this.element = $( element );
		this.menu    = $A( this.element.select( this.options.linkSelector ));
		
		this.show( this.getInitialTab() );
		this.menu.each( this.setupTab.bind( this ));

		if( this.options.autoLinkExternal ) {

			$A( document.getElementsByTagName( 'a' )).each( function( a )
			{
				var loc = a.hash;
				
				if( loc &&
					( a.href.replace( loc, '' ) == location.href.replace( location.hash, '' )) &&
					!this.menu.include( a ) &&
					this.menu.find( function( value ) { return value.hash == loc; }.bind( this )))
					this.setupTab( a );

			}.bind( this ));
		}
	},
	setupTab: function( elm ) 
	{
		Event.observe( elm, 'click', this.activate.bindAsEventListener( this ), false );
	},
	activate: function( ev ) 
	{
		var elm = Event.findElement( ev, 'a' );
		
		Event.stop( ev );
		this.show( elm );
	},
	hide: function( elm ) 
	{
		this.findTab( elm ).removeClassName( this.options.activeClass );
		$( this.tabID( elm )).hide();
	},
	show: function( elm ) 
	{
		var tab = this.findTab( elm );
		
		tab.addClassName( this.options.activeClass );
		$( this.tabID( elm )).show();

		this.menu.without( tab ).each( this.hide.bind( this ));
	},
	tabID: function( elm ) 
	{
		var hash = elm.hash;

		return( hash ? hash.substr( 1 ) : null );
	},
	findTab: function( link )
	{
		var elm = null;
		var id = this.tabID( link );
		
		if( id )
			elm = this.menu.find( function( v ) { return this.tabID( v ) == id; }.bind( this ));

		return( elm );
	},
	getInitialTab: function() 
	{
		return this.findTab( document.location ) || this.menu.first();
	}
}

