(function(){
	
	$.fn.tabs = function(options) {
		var isMethodCall = (typeof options == "string") || false;
		var args = arguments;
		if (!isMethodCall)
			var options = $.extend({}, options, {});
		
		$(this).each(function(){
			var tab = $(this).data("tabs");
			if (isMethodCall && tab) {
				if (tab[options] && typeof tab[options] == "function"){
					tab[options].apply(tab, $.makeArray(args).slice(1));
				}
				return;
			} else {
				tab = new $.tabs(this, options);
				$(this).data("tabs", tab);
			}
		});
		return this;
	};
	
	$.tabs = function(elem, options) {
		this.elem = elem;
		this.options = $.extend({}, options, $.tabs.defaults);
		this.init();
	};
	
	$.extend($.tabs, {
		defaults: {
			selectedClass: "selected",
			showTab: function(obj, event) {
				var h = $(this).attr("href");
				var h = h.split("#",2);
				h = (h.length > 1) ? h[1] : "";
				
				if ( h != "" ) {
					var content = $("#" + h);
					if (content.length) {
						if (obj.current) {
							obj.options.hideTab.apply(obj.current, [obj, event]);
						}
						content.show();
						$(this).addClass(obj.options.selectedClass);
						obj.current = this;
					}
				}
				
				if (event) {
				}
				return false;
			},
			
			hideTab: function(obj, event) {
				var h = $(this).attr("href");
				var h = h.split("#",2);
				h = (h.length > 1) ? h[1] : "";
				
				if ( h != "" ) {
					var content = $("#" + h);
					if (content.length) {
						content.hide();
					}
				}
				
				$(this).removeClass(obj.options.selectedClass);
			}
		},
		prototype: {
			init: function() {
				var self = this;
				this.items = $(">li a", this.elem);
				this.itemsCount = this.items.length;
				this.shortCircuit = false;
				
				if (!this.itemsCount) {
					this.shortCircuit = true;
					return;
				}
				
				this.current = this.items.filter(".selected");
				if (!this.current.length) {
					$(this.items[0]).addClass("selected");
					this.current = $(this.items[0]);
				} else {
					this.current = $(this.current[0]);
				}
				
				this.items.not(this.current).removeClass("selected");
				
				this.items.each(function(){
					self.options.hideTab.apply(this, [self]);
				});
				
				self.options.showTab.apply(this.current, [self]);
				
				this.items.bind("click", function(event){
					this.blur();
					self.options.showTab.apply(this, [self, event]);
					return false;
				});
			}
		}
	});
})(jQuery);