(function( $ ){

  var methods = {
     init : function( options ) {
     	// FIXME - this should probably be stored in in per element data store

		if (this.length == 0) {
			return this;
		}
		    	
		var first = true,
			$container,
			$tabs,
			$tab_wrap,
			$container_height = 0,
			$opts,
			tab_list = new Array(),
			content_list = new Array();

   	 	// Merge options with our default settings     	
       	$opts = $.extend( {}, $.fn.tabify.defaults, options );

		// check for zero length
		
		$tabs = $("<div></div>");
		$container = $("<div></div>");
		
		$tabs.addClass($opts.tabs_class);
		$container.addClass($opts.container_class);
	
		this.each(function() {
			var $this = $(this);
			var $tab_button = $this.find($opts.title_sel);
			var $tab_content = $this.find($opts.content_sel);

			tab_list.push($tab_button);
			content_list.push($tab_content);
			
			$container_height = Math.max($container_height, $tab_content.outerHeight());
				
			if (first) {
				// add our button and content divs before the first tab
				$tab_wrap = $this.before($tabs).before($container);
				$tab_button.addClass('cur-tab');
				first = false;
			}
			else
			{
				$tab_content.hide();
			}
	
				
			$tab_button.click(function() {
				if ($(this).hasClass('cur-tab'))
					return;
					
				var len = tab_list.length;
				for(var i = 0; i < len; i++) {
					tab_list[i].removeClass('cur-tab');
					content_list[i].fadeOut();
				}
				$tab_content.delay(500).fadeIn('slow');
				$(this).addClass('cur-tab');
			});
				
			$tabs.append($tab_button);
			$container.append($tab_content);
    	});			

		$container.height($container_height + 100);

		return this;
     }
  };

  $.fn.tabify = function( method ) {
    
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on this plugin' );
    }      
  };
  
  // plugin defaults - added as a property on our plugin function
  $.fn.tabify.defaults = {
		title_sel:   '.tabify-title',    		// selector of the tab title
		content_sel: '.tabify-content', 	// selector for the content
		tabs_class:   'tabify-buttons',	// class that get's added to the button/tab container
		container_class: 'tabify-tabs' 	// class that get's added to the main content container
  };

})( jQuery );
  
  

