﻿$(document).ready(function(){
	
	$('.jquery-hero-player').each(function(){
	
		var scope = $(this);
	
		var defaultDelay = 7000;	
		var lesBlocks = scope.find(".hero-block");
		var nbBlocs = lesBlocks.length;
		var pauseBool = false;
		var leTimer;
		
		function init()
		{
			var imageLoading = new Image(); 
			imageLoading.src = "assets/images/slideshow/player_play.gif";
		
			lesBlocks.hide();
			lesBlocks.eq(0).show();
			
			scope.append('<div class="boutons_hero"></div>');
			
			scope.find(".boutons_hero").append('<a class="btn_pause" href="javascript:;"></a>');
			
			for(var i = 0; i < nbBlocs; i++)
			{
				scope.find(".boutons_hero").append('<a class="btn_hero" id="'+(nbBlocs-i)+'" href="javascript:;"></a>');
			}
			
			scope.find(".boutons_hero .btn_hero#"+1).addClass('hero_actif');	

			if(lesBlocks.eq(0).attr('rel') != undefined)
				leTimer = setTimeout(timer_bloc, lesBlocks.eq(0).attr('rel'));
			else
				leTimer = setTimeout(timer_bloc, defaultDelay);		
		}
		
		init();
		
		scope.find(".btn_pause").click(function(){
			if( pauseBool == true )
			{
				$(this).removeClass('btn_play');
				pauseBool = false;
				leTimer = setTimeout(timer_bloc, defaultDelay);	
			}
			else
			{
				$(this).addClass('btn_play');
				pauseBool = true;
				clearTimeout(leTimer);
			}
		});
		
		scope.find(".boutons_hero .btn_hero").click(function(){
			anime_bloc($(this).attr('id'));		
		});
		
		function timer_bloc()
		{
			var blocIndex = lesBlocks.index(scope.find(".hero-block:visible"));		
			if(blocIndex < nbBlocs-1)
				anime_bloc( blocIndex + 2 );
			else
				anime_bloc( 1 );
		}	
		
		function anime_bloc(index)
		{
			clearTimeout(leTimer);
		
			scope.find(".hero-block:visible").fadeOut('fast', function(){
				lesBlocks.eq(index-1).fadeIn('normal');
				
				scope.find(".boutons_hero .btn_hero").removeClass('hero_actif');
				scope.find(".boutons_hero .btn_hero#"+index).addClass('hero_actif');	
			});		
			
			if( pauseBool == false )
			{
				if(lesBlocks.eq(index-1).attr('rel') != undefined)
					leTimer = setTimeout(timer_bloc, lesBlocks.eq(index-1).attr('rel'));
				else
					leTimer = setTimeout(timer_bloc, defaultDelay);
			}
		}
	
	});
});
