var TabCollection = new Class( {
	
	  tabs: []
	
	, add: function( tabs ) {
		this.tabs.extend( tabs );
		return this;
	  }
	
	, getVisible: function( ) {
		return this.tabs.filter( function( tab ) { return tab.isVisible( ); } ).shift( );
	  }
	
	, toggle: function( to ) {
		var from = this.getVisible( );
		
		from.hide( );
		to.show( );
	  }
	
	, render: function( container ) {
		if( this.tabs ) {
			container.addClass( 'loading' );
			
			var self = this;
			var labels = new Element( 'ul', { 'class': 'labels clean flatten' } );
			var tabs = new Element( 'div', { 'class': 'tabs' } );
			
			var i;
			this.tabs.each( function( tab, i ) {
				tab.setControl( new Element( 'li', { 'html': tab.getTitle( ), 'events': { 'click': self.toggle.bind( self, tab ) } } ) );
				
				tab.setContent( new Element( 'div', { 'class': 'tab', 'html': tab.getContent( ), 'styles': { 'visibility': 'hidden' } } ) );
				
				labels.grab( tab.getControl( ) );
				tabs.grab( tab.getContent( ) );
			} );
			
			labels.getFirst( ).addClass( 'first' );
			labels.getLast( ).addClass( 'last' );
			
			this.tabs[0].setVisible( true );
			this.tabs[0].getContent( ).setStyle( 'visibility', 'visible' );
			
			container.empty( );
			container.grab( labels );
			container.grab( tabs );
			
			this.tabs.each( function( tab, i ) { tab.onLoad( ); } );
			container.removeClass( 'loading' );
			container.addClass( 'loaded' );
		}
	  }
	
} );

var Tab = new Class( {
	
	  title: ''
	, content: null
	, control: null
	, is_visible: false
	
	, onLoad: function( ) { }
	, onFocus: function( ) { }
	, onBlur: function( ) { }
	
	, initialize: function( title ) {
		this.setTitle( title );
	  }
	
	, getTitle: function( ) { return this.title; }
	, setTitle: function( title ) { this.title = title; return this; }
	
	, getContent: function( ) { return this.content; }
	, setContent: function( content ) { this.content = content; return this; }
	
	, getControl: function( ) { return this.control; }
	, setControl: function( control ) { this.control = control; return this; }
	
	, show: function( ) {
		this.setVisible( true );
		this.getContent( ).fade( 'in' );
		this.onFocus( );
	  }
	, hide: function( ) {
		this.onBlur( );
		this.setVisible( false );
		this.getContent( ).fade( 'out' );
	  }
	
	, setVisible: function( visible ) {
		if( visible ) {
			this.getContent( ).addClass( 'selected' );
			this.getControl( ).addClass( 'selected' );
		}
		else {
			this.getContent( ).removeClass( 'selected' );
			this.getControl( ).removeClass( 'selected' );
		}
		this.is_visible = visible;
	  }
	, isVisible: function( ) {
		return this.is_visible;
	  }
	
	, render: function( ) {
		return this.getContent( );
	  }
	
} );