(function($) { 
	$.fn.tabs = function (o)
	{
		o = $.extend(
		{
			tabs: '',
			panels: '',
			mevent: 'click',
			before: function(){},
			after: function(){},
			activeIndex: 0,						// 1.1 : permit to activate a tab/panel by its index at init (or not if false)
			desactivation: false,				// 1.1 : permit to desactivate at n+1 event, when passed to true
			auto: 0									// 1.2 : permit to switch automatically specifying a delay	
		}, o);

		var wrap = null; if ($(this)[0]) { wrap = $(this); } else { wrap = $('body'); }

		$(wrap).each(function(){
			var wrapCurrent = $(this);
			var tabs = $(o.tabs, wrapCurrent);
			var panels = $(o.panels, wrapCurrent);
			var desactivation = o.desactivation;

			var activeIndex = o.activeIndex;
			if (parseInt(activeIndex) >= 0) {
				tabs.eq(activeIndex).addClass('active');
				panels.eq(activeIndex).addClass('active');
			}

			var tabChange = function (tab) {
				var tabIndex = tabs.index(tab);
				if (!tab.hasClass('active') || desactivation)
				{
					o.before(wrapCurrent);

					var tabInactive = false;
					if (tab.hasClass('active') && desactivation) { tabInactive = true; }

					tabs.removeClass('active');
					panels.removeClass('active');

					if (!tabInactive) {
						tabs.eq(tabIndex).addClass('active');
						panels.eq(tabIndex).addClass('active');
					}

					o.after(wrapCurrent);

					if (o.auto > 0) {
						clearInterval(tabs_interval);
						tabs_interval = setInterval(tabs_rotate, o.auto);
					}
				}
			};

			if (o.auto > 0) {
				var tabs_rotate = function rotation () {
					var nextTab = $(o.tabs + '.active', wrapCurrent).next(tabs);
					if($(o.tabs + '.active', wrapCurrent).next(tabs).length == 0){ nextTab = tabs.eq(0); }
					tabChange(nextTab);
				};
				var tabs_interval = setInterval(tabs_rotate, o.auto);
			}

			tabs.bind(o.mevent,function(){
				tabChange($(this));
				return false;
			});
		});
	};
})(jQuery);
