/* $Id: tabbed.js 737 2009-04-29 12:36:16Z belzi $ */

jQuery.noConflict();

jQuery.fn.tabbed = function() {
	var $ = jQuery;
	var $$ = this;
	
	$$.each(function() {
		var $$ = $(this);
//		if ($$.css('position')!='absolute') {
//			$$.css({position:'relative'});
//		}
		$$.find('.tab:not([class*=show])').hide();
		var tabs = $$.find('.tab');
		if ($$.hasClass('auto')) {
			Autotabbed.init($$.attr('id') || $$.selector,tabs,7);
		}
		var legends = $$.find('.legend *[rel]');
		legends.each(
			function() {
				$(this).click(function() {
					var clicked = $(this);
					legends.removeClass('active');
					clicked.addClass('active');
					tabs.fadeOut(300);
					var target = $("#"+clicked.attr('rel'));
					target.fadeIn(300);
					if(clicked.closest('.auto')) Autotabbed.stop(clicked.closest('.auto').attr('id'));
				});
			}
		);
	});
}

var Autotabbed = {
	tabs: {},
	current: {},
	current_interval: {},
	duration: {},
	interval: false,
	init: function(id,tabs,duration) {
		Autotabbed.tabs[id] = tabs;
		Autotabbed.current[id] = 0;
		Autotabbed.current_interval[id] = 0;
		Autotabbed.duration[id] = duration;
		if (!Autotabbed.interval) {
			Autotabbed.interval = setInterval('Autotabbed.rotate()',1000);
		}
	},
	stop: function(id) {
		if (!id) return;
		delete Autotabbed.tabs[id];
		if (!Autotabbed.tabs.length) {
			clearInterval(Autotabbed.interval);
			Autotabbed.interval = false;
		}
	},
	rotate: function() {
		var $ = jQuery;
		$.each(Autotabbed.tabs,function(key) {
			Autotabbed.current_interval[key] = (Autotabbed.current_interval[key]+1) % Autotabbed.duration[key];
			
			if (Autotabbed.current_interval[key]==0) {
				Autotabbed.current[key] = (Autotabbed.current[key] + 1) % Autotabbed.tabs[key].length;
				Autotabbed.tabs[key].fadeOut(300);
				var active = $(Autotabbed.tabs[key][Autotabbed.current[key]]);
				var activeID = active.attr('id');
				active.fadeIn(300);
				var legends = Autotabbed.tabs[key].parents('.tabbed').find('.legend *[rel]');
				legends.removeClass('active');
				var activeLegend = $('*[rel=' + activeID + ']');
				activeLegend.addClass('active');
			}
		});
	}
};

jQuery('document').ready(function($) {
	$('.tabbed').tabbed();
});