(function($) {
	$.fn.tabs = function(settings) {
		var options = $.extend({}, $.fn.tabs.defaults, settings),
			$tabs,
			$tabContents,
			
			tabClickHandler = function(){
				
				var $this = $(this),
					tabHash = $this.attr('href'),
					contentId = tabHash.substr(1);
				
				$tabs.removeClass(options.activeClass);
				$tabContents.removeClass(options.activeClass);
				
				$tabs.filter(function(){
						var $this = $(this);
						if($this.attr('href').indexOf(tabHash) >= 0){
							return $this;
						}
					}).addClass(options.activeClass);
				$('#' + contentId).addClass(options.activeClass);
				
				// do not jump to id
				return false;
			},
			
			initialize = function(){
				if(!callFromExternal()){
				
					// test if there is one active tab; if not activate first one
					var oneTabIsActive = false;
					$tabs.each(function(index,tab){
						if($(tab).hasClass(options.activeClass)){
							oneTabIsActive = true;
						}
					});
					
					if(!oneTabIsActive){
						$tabs.eq(1).trigger('click');
					}
				}
			},
			
			callFromExternal = function(){
				if(location.hash.length > 0){
					var targetContentId = location.hash;
					// is there a content that has the id? then open it
					$tabs.each(function(index,tab){
						var $tab = $(tab),
							contentId = $tab.attr('href');

						if(contentId == targetContentId){
							
							$tab.trigger('click');
							return true;
						}
					});
				}
				
				return false;
			};
		
		return this.each(function() {
			var $this = $(this);
			$tabs = $(options.tabSelector, $this);
			$tabContents = $(options.tabContentSelector, $this);
			
			$this.delegate(options.tabSelector, 'click', tabClickHandler);
			
			$('a', $tabContents).filter(function(){
					var $this = $(this);
					if($this.attr('href').indexOf('#') >= 0){
						return $this;
					}
				}).click(tabClickHandler);
			initialize();
		});
	};
	
	$.fn.tabs.defaults = {
		tabSelector: '.nav li a',
		tabContentSelector: '.content div',
		activeClass: 'active'
	};

})(jQuery);
