(function($) {
	
	$.fn.tabs = function( options ){
		
		var defaults = {
			cache: false
		};
		
		options = $.extend({}, defaults, options);

		
		var oList = $(this);
		
		oList.bindTabReferences();
		oList.bindTabExternalAnchors();

		//assign the click function to focus the tab
		$(this).find('li>a')
			.unbind('click.tab')
			.bind('click.tab',
			function(e,data){
				
				//stop the link from going
				e.preventDefault();				
				
				//extend the data
				var opts = $.extend( {}, options, data );
								
	    		//display the related tab content identified by the href
    			$.fn.tabs.show( this , opts );	
				
				return false;
			}
		);	
		
		//if there is a hash location in the url, go there, 
		//otherwise goto the current class in the markup
		var sHashSelector = 'a[href*=' + document.location.hash + ']';
		if ( document.location.hash && oList.find(sHashSelector).length > 0 ) {
			oList.find( sHashSelector).showTab();								
		} else {
			$(this).each(function(i, val){
				var $parent = $(val.parentNode);
				//No clue why this code was here - 11.16.09 - RK
				//if($parent.is('.module, .main')) {
					$parent.find('> ul.tabs:first > li.current > a').triggerHandler('click.tab');
				//}
			});
		}
	}
	
	$.fn.bindTabReferences = function(){
		
		//bind the data to the tabs
		var tabs = $(this);
		
		tabs.find('>li>a').each(function(){
			if( this.hash ){
				var $tab 		= $(this);
				var $tabList = $tab.parents('ul').eq(0);
				var $content = $(this.hash);
				
				$content.data('tab_anchor',$tab).data('tab_list',$tabList);
				$tab.data('tab_content', $content).data('tab_list',$tabList);
			}
			
		});
		
	}
	
	$.fn.bindTabExternalAnchors = function( $area ){
		
		//specify the area in this document to look for external anchors
		var $area = $($area || 'html');
		
		//search for anchors to bind them to tabs
		$(this).find('>li>a').each(
			function(){				
				var $tab = $(this);
				$area.find('a[href$=' + this.hash + ']').not(this)
					.unbind('click.tab')
					.bind('click.tab',
						function(e){
							e.preventDefault();
							$tab.showTab();
							$().tabs.scrollTo( this );
							//return false;	
						}
					);
			}
		);	
	}
	
	$.fn.showTab = function( options ){
		
		//if this tab is a sub tab, we need to open the parent tab first
		var $container 		= $(this).closest('div[id]');
		var $containerTab 	= $('ul.tabs a[href$=#' + $container.attr('id') + ']');
		if( $containerTab.length > 0 ){
			$containerTab.showTab( options );
		};	
			
		$(this).triggerHandler('click.tab', options );
		
	}
	
	$.fn.tabs.tabLoading = function( tab ){
		var $tab = $(tab);
		$tab.addClass('loading');		
		//$tab.data('tab_list').addClass('loading').parent('div[id]').addClass('loading');
		$tab.data('tab_content').addClass('loading');
	}
	
	$.fn.tabs.isLoading = function( tab ){
		
		return $(tab).hasClass('loading');
		
	}
	
	$.fn.tabs.isLoaded = function( tab ){
		
		return $(tab).hasClass('loaded');
		
	}
	
	$.fn.tabs.tabLoaded = function( tab ){
		var $tab = $(tab);
		$tab.removeClass('loading').addClass('loaded');
		$tab.data('tab_list').removeClass('loading').parent('div[id]').removeClass('loading');
		$tab.data('tab_content').removeClass('loading').addClass('loaded');
	}
	
	$.fn.tabs.scrollTo = function( tab ){
		var $tab = $(tab);
	    if ($tab.length) {
			$('html,body').animate({scrollTop: $tab.offset().top}, 500);
			return false;
		}		
	}
	
	$.fn.tabs.show = function( tab, options ){
		
		//make a jquery ref to the tab
		var $tab = $(tab);
		
		//make sure all the other tabs dont look like the current
		$tab.parent().siblings().removeClass('current');
			
		//focus this tab
		$tab.parent().addClass('current');
		
		//if there's no link, its not linked, so cancel
		if (!$tab.attr('href')) {
			return;
		}
				
		//get the tab path (href)
		var path = $tab.attr('href').replace(tab.hash,'').replace(/\s+/g,'');
		
		
		//tab caching - if it's loaded, don't reload the ajax
		if( $.fn.tabs.isLoaded( tab ) && options.cache == true ){
			
			//hide all others
			$( tab.hash ).show();
			$( tab.hash ).triggerHandler('tab.shown');			
			
		} else if( !$.fn.tabs.isLoading(tab) ){

			//create a callback function 
			var callback = function( response, status, xHR){				
				
				if (status == "error" && !(xHR.status==0 && xHR.readyState==4)) {
					$( tab.hash ).html('<ul class="item_list"><li class="error">'+xHR.statusText+'</li></ul>');
				} else if( response ){
					//if there was a response, it was loaded via ajax, so do the onload callback
					if( options && typeof options.onload == 'function' ){
						options.onload.call( tab, $(tab.hash).get(0) );
					}

					//bind any external anchors that may be in this content
					$tab.data('tab_list').bindTabExternalAnchors();					
				}
				
				//hide all others
				$tab.parents('ul,ol').find('li>a').not( tab ).each( function(){ $( this.hash ).hide(); }  );
		
				//show this one
				$( tab.hash ).show();
				$( tab.hash ).triggerHandler('tab.shown');
				
				//mark this tab as loaded
				$.fn.tabs.tabLoaded( tab );
				
				//call the change tab callback			
				if( options && typeof options.change == 'function' ){
					options.change.call( tab );
				}
			}

			//mark this tab as loading
			$tab.parents('ul,ol').find('li>a').not( tab ).each( function(){ $( this.hash ).hide(); } );
			$( tab.hash ).show();
			$.fn.tabs.tabLoading( tab );		

			//if there is a path to the url, not just a hash, load it
			if( path ){				
				
				if ($('input#friends_only[type=checkbox]').attr('checked')) {
					path += '/friendsonly:true';
				}
				$( tab.hash ).load( path , callback);
								
			} else {
				callback();
			}
		}
		
		//show subtabs if there is no ajax request on this item
		if (path == '') {
			
			var subTab = $(tab.hash).find('li.current > a').get(0);
			$.fn.tabs.show( subTab , options );
		
		}
		
	}	
	
	$.fn.setupShowMore = function () {
		//this contains one or more show more buttons
		$(this).each(function(){
			var $button = $(this);

			var $container = $button.prevAll('ul').eq(0);
			var count = $container.children('li').length;
			if (count < window.CONFIG.SIDEBAR_LIST_SIZE) {
				$button.remove();
			} else {
				$button.text('Show More').click( function() { $(this).showMore(); } );
			}		
		});
	}
	
	$.fn.showMore = function( options ){
		
		//make a reference to this
		var $this = $(this);
		
		//make the show more button unclickable and indicate loading
		var $button = $this.addClass('submitting').attr('disabled','disabled').text('Loading more...');
		
		var $container = $this.eq(0).prevAll('ul');
		var count = $container.children('li:not(.share)').length;
		var link = $this.eq(0).parents('.tabs_content').eq(0).prevAll('ul').find('li.current > a').get(0);
		
		//yank the path from the href
		//remove any /start:x if it exists
		//remove any #hash
		var realLink = $(link).attr('href').replace(link.hash,'').replace(/\s+/g,'').replace(/\/start\:[^\/]+/g, '');
		
		realLink += '/start:' + count;
		
		/* Friends only is disabled for now
		if ($('input#friends_only[type=checkbox]').attr('checked')) {
			realLink += '/friendsonly:true';
		}
		*/
		
		$.ajax({
				url: realLink,
				cache: false,
				error: function(xHR) {			
					$container.append('<ul class="item_list"><li class="error">'+xHR.statusText+'</li></ul>');
					$button.remove();
				},
				success: function(html){
					if (html == '') {
						$button.replaceWith( $('<span />').text('There are no more posts to display.').addClass('no_more') );
					} else {
						$html = $(html);
						
						$button.removeClass('submitting').removeAttr('disabled');
						
						elements = $html.filter('li');
						//we suppose there is a "empty message state" if the class name is empty
						if (!(elements.length == 1 && elements.eq(0).hasClass('empty'))) {
							$container.append($html);
						}
												
						//bind any external anchors that may be in this content
						$tabs = $container.parent('div[id]').data('tab_list').bindTabExternalAnchors();;
						
						//find out if we have anymore 
						if (elements.length < 5) {
							$button.replaceWith( $('<span />').text('There are no more posts to display.').addClass('no_more') );
						} else {
							$button.text('Show More');
						}
						
						//fire off the area load function
						SDNA.global.onAreaLoad( $html );
					}
				}
		});
	}
	
	$.fn.clickFriendsOnly = function() {
		//should we do this or $(this).parent().parent().find('.loaded').removeClass('loaded')
		$(this).parent().nextAll('div.tabs_content').find('.loaded.friendsonly').removeClass('loaded').each( function() { $($(this).get(0).hash).text(''); } );
		$(this).parent().nextAll('ul.tabs').find('.loaded.friendsonly').removeClass('loaded').each( function() { $($(this).get(0).hash).text(''); } );
		
		var tabCounts = $(this).parent().nextAll('ul.tabs').find('span.count').text('#');
		var url = $(this).attr('href');
		if ($(this).attr('checked')) {
			url += '/friendsonly:true';
		}
		
		$.ajax({
				url: url,
				cache: true,
				async: false,
				dataType: 'json',
				success: function(data){
					tabCounts.each( function() {
						var name = $(this).parent().html().replace(/ \<span.+/, '');
						if (data['counts'][name]) {
							$(this).text(data['counts'][name]);
						} else {
							$(this).text('0');
						}
					})
				}
		       });
		
		var currentTab = $j( $j('div.main ul.tabs').eq(0).find('> li.current > a').get(0).hash + ' > ul.tabs > li.current > a');
		if (currentTab.length == 0) {
			currentTab = $j('div.main ul.tabs').eq(0).find('> li.current > a');
		}
		
		currentTab.triggerHandler('click.tab');
	}
	
})(jQuery);
