/*
	Tabs jQuery Plugin.
	
	Usage:
		Call the tabs() function on the parent of the tab elements. Each tab
		element should contain a link to it's body using the normal fragment
		identifier style.
		
		For example
		
		<div>
			<ul id="tab-header">
				<li><a href="#one">Tab One</a></li>
				<li><a href="#two">Tab Two</a></li>
				<li><a href="#three">Tab Three</a></li>
			</div>
			
			<div id="one">#1 Body Content</div>
			<div id="two">#2 Body Content</div>
			<div id="three">#3 Body Content</div>
		</div>
		
		should be used:
		
		$("#tab-header").tabs();
	
	Options:
		changeOn
			The type of event (click, mouseover, etc) that should trigger the
			tab change.
		
		linkSelector
			The selector used to select the link within the tab. Usually there
			will only be a single link within a tab, so the default "a:first"
			will be fine.
*/

(function($) {
	
	$.fn.tabs = function(options) {
		var opts = $.extend({}, $.fn.tabs.defaults, options);
		
		this.each(function() {
			var tabs = $(this).children();
			var bodies = $(opts.linkSelector, tabs).map(function() {
				if($.isEmpty(this.hash) && $(this).parent().attr('data-content')){
					this.hash = $(this).parent().attr('data-content');
				}
				return $(this.hash);
			});
			
			tabs.each(function(i) {
				// Now bind the event
				$(this).bind(opts.changeOn, function(e) {
					e.preventDefault();
					if (i >= bodies.length) { return; }
					bodies.each(function() {
						this.hide();
					});
					$(tabs[i]).addClass(opts.activeClass).siblings().removeClass(opts.activeClass);
					bodies[i].show().siblings().hide();
				});
				// And, do initial setup
				if($(tabs[i]).hasClass(opts.activeClass)){
					bodies[i].show().siblings().hide();
				}
			});
		});
		
		return this;
	};
	
	// Allow access to defaults.
	$.fn.tabs.defaults = {
		activeClass: 'active',
		changeOn: "click",
		linkSelector: "a:first"
	};
	
})(jQuery);

