/*
Namespace: Tabs
	Simple tabbed sections

Plugin Name: jquery.tabs.js

About: Version
	1.0

Description:
	A jQuery plugin for creating simple tabbed panels

Requires:
	jQuery 1.3 <http://jquery.com>

*/

(function($) {
	
	var activate = function($e, o) {
		var $el = this,
			el = this.get(0);
		
		$e.tabs.each(function(){
			var $this = $(this);
			
			if (!this.$body) {
				return;
			}
			
			if (el === this) {
				$this.addClass(o.activeTabClass);
				this.$body
						.addClass(o.activeBodyClass)
						.removeClass(o.hiddenBodyClass);
			} else {
				$this.removeClass(o.activeTabClass);
				this.$body
						.removeClass(o.activeBodyClass)
						.addClass(o.hiddenBodyClass);
			}
		});
	};
	
	$.fn.tabs = function(options) {
		
		var options = $.extend({}, $.fn.tabs.defaults, options || {});
		
		// iterate and reformat each matched element
		return this.each(function() {
			
			var $this = $(this);
			
			// build element specific options
			var o = $.meta ? $.extend({}, options, $this.data()) : options;
			
			var w, $e = {};
			$e.tablist	= $this.find('.' + o.tablistClass);
			$e.tabs		= $e.tablist.find(o.tabElements);
			
			$e.tabs.each(function(){
				var $this = $(this),
					$link = $this.find('a'),
					href;
					
				this.$link = $link.length ? $link : $this;
				href = this.$link.attr('href');
				
				if (typeof href !== "string") {
					return;
				}
				
				this.$body = $(href);
				
				if (!this.$body.length) {
					return;
				}
				
				// fix the width of the body, then hide it.
				// We only want the width of the first tab body, as the others are hidden.
				w = w || this.$body.width()
				this.$body.css('width', w);
				this.$body.addClass(o.hiddenBodyClass);
				
				// Bind a click event.
				this.$link.bind('click', function(e){
					e.preventDefault();
					activate.call($(this).parent(), $e, o);
				});
				
			});
			
			// Activate the first tab
			$e.tabs.get(0).$link.trigger('click');
			
		});
		
	};
	
	$.fn.tabs.defaults = {
		tablistClass : 'tabs',
		tabElements : 'li',
		activeTabClass : 'active',
		activeBodyClass : 'active',
		hiddenBodyClass : 'hidden'
	};
	
})(jQuery);