(function( $ ){

	var mtab_methods = {
		init : function( options ) {  
			this.addClass( 'tab-container' ).children( 'ul' ).addClass( 'tab-controls' ).find( 'li' ).each( function( idx, val ) {
				var count = $(this).parent().find( 'li' ).size();
				if( !$(this).hasClass( 'selected' ) )
					$(this).css( 'z-index', (5+count)-idx ).data( 'z', (5+count)-idx );
					
				$(this).click( function() {
					var hashSearch = /^#\S+/i;
					if( hashSearch.test( $(this).find( 'a' ).attr( 'href' ) ) )
					{
						//Hash exists, switching to another tab.
						$( $(this).find( 'a' ).attr( 'href' ) ).siblings().removeClass( 'selected' );
						$( $(this).find( 'a' ).attr( 'href' ) ).addClass( 'selected' );
						
						$(this).siblings().each( function() {
							$(this).removeClass( 'selected' ).css( 'z-index', $(this).data( 'z' ) );
						});
						$(this).css( 'z-index', '' ).addClass( 'selected' );
					}
					else
						window.location = $(this).find( 'a' ).attr( 'href' ); //No hash, we are switching pages.
				}).find( 'a' ).click( function() { 
					$(this).parent().click();
					return false; 
				});
			});
			this.find( "ul ~ div" ).addClass( 'tab-contents' ).addClass( 'content-section' ).wrapAll( document.createElement( 'div' ) ).after( '<div class="clear"></div>' );
			
			
			if( options && options.startTab >= 0 )
				$(this.find( "li" )[options.startTab]).click();
				
			return this;
		},
		select : function( options ) {
			if( options > 0 )
				this.find( ".tab-controls li" )[options].click();
		}
	};

	$.fn.mtab = function( method ) {
		// Method calling logic
		if ( mtab_methods[method] ) {
			return mtab_methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return mtab_methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.mtab' );
		}
	};

})( jQuery );
