
jQuery.fn.tabPanels = function( options )
{
	if( !this[0] )
		return;
		
	var $c = this.eq(0),
		$t = jQuery( '<ul class="tabs"></ul>' ),
		$p = jQuery( '<ul class="panels"></ul>' ),
		active = null;
	
	// clean container before adding tabs / panels
	$c.contents().remove();
	$c.append( $t ).append( $p );
	
	// import tabs
	jQuery.each( options.tabs, function( i, tab )
	{
		// remove obsolete title
		if( tab.$title )
		{
			tab.$title.remove();
			delete tab.$title;
		}
		
		// create tab
		tab.$tab = jQuery( '<li></li>' ).append( jQuery( '<span></span>' ).text( tab.name ) ).data( 'tabPanels', tab ).appendTo( $t );
		
		// add panel
		tab.$panel.appendTo( $p ).hide();
		
		function showTab( e )
		{
			$this = jQuery(this);
			if( this == active.$tab.get(0) )
				return;
			
			var toggle = [];
			// hide current tab
			if( active )
			{
				active.$tab.removeClass( 'active' );
				toggle.push( active.$panel );
			}
			
			var t = $this.data( 'tabPanels' );
			t.$tab.addClass( 'active' );
			toggle.push( t.$panel );
			t.$panel.add( active.$panel ).slideToggle( 200 );

			active = t;
		}
		
		tab.$tab.bind( 'click', showTab );
		
		// activate first tab
		if( active === null )
		{
			tab.$tab.addClass( 'active' );
			tab.$panel.show();
			active = tab;
		}
	} );

};

jQuery( function(){
	var match = {
			group: /tabGroup\[(.+?)\]/,
			id: /tabId\[(.+?)\]/
		},
		tabs = {},
		groups = {};
	
	jQuery( 'div.tabPanel' ).each( function( i, o ){
		var $o = jQuery( o ),
			tab = {
				$panel: $o
			};

		// determine tabId
		if( (tab.id = o.className.match( match.id )) && tab.id.length == 2 )
			tab.id = tab.id[1];
		else
			tab.id = 'tab_' + i;
			
		// determine tabGroup
		if( (tab.group = o.className.match( match.group )) && tab.group.length == 2 )
			tab.group = tab.group[1];
		else
			tab.group = 'default';
	
		// determine tabName, tabTitle
		jQuery( '.tabName', $o ).each( function( ti, to ){
			tab.name = jQuery(to).text();
			tab.title = jQuery(to).attr( 'title' );
			tab.$title = jQuery( to );
			return false; // break;
		} );
		
		
		if( !tabs[ tab.group ] )
			tabs[ tab.group ] = [];
		
		tabs[ tab.group ].push( tab );
	} );
	
	jQuery.each( tabs, function( i, itabs )
	{
		var d = jQuery( '#tabGroup_'+ i );
		if( !d || !d.length )
		{
// 			console.log( 'skipping tabGroup[', i ,'] for no destination-container was found' );
			return true; // continue;
		}
			
		
		d.tabPanels( { group:i, tabs:itabs } );
	} );
} );
