(function($, undefined){
	
	$.fn.tab_defil = function(){
	
		var $this = this.first();
		
		//pixels de décalage à chaque appel
		var pas = 2;
		
		//fréquence des appels en ms
		var speed = 10;
		
		/* 
		 * Fixé en dur dans la template :
		 * Les onglets font 72px de large et sont calés à 67px les uns des autres
		 */
		var width = $this.children().length * 67 + 72 - 67; 
		
		var delta = width - $this.parent().width();
		var pos = 0;
		var running = false;
		
		
		if( delta > 0 )
		{
			var $container = $('<div class="tab_defil-container"></div>');
			var $prev = $('<a href="#" class="prev">&lt;</a>');
			var $next = $('<a href="#" class="next">&gt;</a>');
			
			$this
				.wrap( $container )
				.after($prev)
				.after($next);
			
			$prev.hover( prev, stop );
			$next.hover( next, stop );
			
			showControls();
		}
		
		
		function prev(){
			running = true;
			pas = Math.abs( pas );
			defil();
		}
		
		function next(){
			running = true;
			pas = Math.abs( pas ) * -1;
			defil();
		}
		
		
		function stop(){
			running = false;
		}
		
		
		function defil(){
			if( running )
			{
				pos += pas;
				pos = Math.max( -delta, pos );
				pos = Math.min( 0, pos );
				$this.css( 'left', pos + 'px' );
				showControls();
				setTimeout( defil, speed );
			}
		}
		
		
		
		function showControls(){
			if( pos < 0 )
			{
				$prev.show();
			}
			else $prev.hide();
			
			if( pos > -delta )
			{
				$next.show();
			}
			else $next.hide();
		}
		
	};

	$(function(){
		$('#main_content .tab_list').tab_defil();
	});
})(jQuery);
