/**
 * Creates a tabbed menu using jQuery
 * 
 * Copyright (c) 2009 Dave Widmer
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * 
 * @author	Dave Widmer
 * @version	1.01	2009-06-26
 * @see		http://www.davewidmer.net/projects/jquery_tabbed_menu
 */
(function($){
		
	$.fn.tabbed_menu = function(tabs, content, opt_param){
		// First element is an empty object so it won't override the defaults object
		var options = $.extend({}, $.fn.tabbed_menu.defaults, opt_param);
		// Add in options
		options.container = this;
		options.tabs = $(tabs, this);
		options.content = $(content, this);
		
		init(options);
		
		return this.each(function(i){
			$(options.tabs, this).click(function(event){
				handleClick(event, options);
			});
		});
	};
	
	$.fn.tabbed_menu.defaults = {
		active:':nth-child(1)',
		fade:'none',
		activeClass:''
	};
	
	var init = function(options){
		$(options.tabs).each(function(i){
			attachContent(this,$(options.content).eq(i));
		});
		hideVisibleContent(options.content);
		var active =  $(options.tabs).filter(options.active);
		setActive(active[0], options.tabs, options.fade, options.activeClass);
	};
	
	var handleClick = function(event, options){
		 if( ! $(event.target.content).is(':visible') ){
			hideVisibleContent(options.content);
			setActive(event.target, options.tabs, options.fade, options.activeClass);
		}
	};
	
	var attachContent = function(tab,content){
		tab.content = content;
	};
	
	var hideVisibleContent = function(content){
		$(content).filter(':visible').each(function(){
			$(this).hide();
		});
	};
	
	var setActive = function(item, tabs, fade, active){
		(fade !== 'none') ? 
				$(item.content).fadeIn(fade): 
				$(item.content).show();
				
		$(tabs).each(function(){
			if( $(this).hasClass(active) ){
				$(this).removeClass(active);
			}
		});
		$(item).addClass(active);
	};

})(jQuery);