jQuery(function(){
	jQuery('div.tabs-container').ajaxTabs();
});

jQuery.fn.ajaxTabs = function(options){
	var options = jQuery.extend({
		tabset:'ul.tabset',
		tabsHolder:'div.tab-content',
		afterFirstLoad:null,
		fadeSpeed:true
	},options);

	return this.each(function(){
		var holder = jQuery(this);
		var tabset = jQuery(options.tabset, holder);
		var tabsHolder = jQuery(options.tabsHolder,holder);
		var links = jQuery('a',tabset);
		var hrefArray = [];
		var tabArray = [];
		var firstLoad = [];
		var active = 0;
		var ajaxInAction = false;
		var hash = window.location.hash; 
		
		links.each(function(i){
			hrefArray[i] = jQuery(this).attr('href');
			firstLoad[i] = true;
			if (jQuery(this).hasClass('active')) active = i;
		});
		
		links.each(function(i){
			var link = jQuery(this);
			if (('#'+hrefArray[i]) == hash) {
				links.eq(active).removeClass('active');
				links.eq(i).addClass('active');
				active = i;
			} 
			link.click(function(){
				if (i != active && !ajaxInAction) loadTab(i);
				return false;
			});
		});
		
		loadTab(active);
		
		function loadTab(ind) {
			if (typeof tabArray[ind] != 'undefined') {
				showTab(ind);
			} else {
				ajaxInAction = true;
				jQuery.ajax({
					url: hrefArray[ind],
					error:function(){
						alert('ajax error');
					},
					success:function(msg){
						ajaxInAction = false;
						tabArray[ind] = jQuery(msg).appendTo(tabsHolder).hide();
						showTab(ind);
					}
				});
				
			}
		}
		
		function showTab(ind){
			tabArray[active].css({display:'none'});
			links.eq(active).removeClass('active');
			links.eq(ind).addClass('active');
			//window.location.hash = '#'+	hrefArray[ind];
			if (options.fadeSpeed) {
				tabArray[ind].fadeIn(options.fadeSpeed,function(){
					if (typeof options.afterFirstLoad == 'function' && firstLoad[ind]) {
						options.afterFirstLoad(tabArray[ind]);
						firstLoad[ind] = false;
					}
				});
			} else {
				tabArray[ind].show();
				if (typeof options.afterFirstLoad == 'function' && firstLoad[ind]) {
					options.afterFirstLoad(tabArray[ind]);
					firstLoad[ind] = false;
				}
			}
			active = ind;
		}
	});
}
