﻿$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */
	
	var leftMostClientWidth = 0;
	var ClientsLargerThenMask = false;
	
	var animInterval = 1000; //Milliseconds
	var PixelIncrements = 50;
	var Offset = 0;
	
	var totClientsWidth = 0;
	var ClientWidths = new Array();
	var ContainingDivWidth = $('#bottom').width();
	
	var PauseAnim = false;
	
	/* Get size data from childs */
	$('#Clients .client').each(function(i){
		/* Traverse through all the Diapos and store their accumulative widths in totClientsWidth */
		
		ClientWidths[i]= $(this).width();
		totClientsWidth += ClientWidths[i];
		
		/* The ClientWidths array contains each diapo's commulutative offset from the left part of the container */		
		if(!$(this).width())
		{
			alert("Pas de clients?.... COME ON!!");
			return false;
		}
	});

	$('#Clients').each(function(i){
		/* Pausing when mouse is over */
	    $(this).hover(function() {
	      $('#Clients').stop();
	      Offset = -parseFloat($('#Clients').css("marginLeft"));
          PauseAnim = true;
          //$(this).css('cursor','wait');
        }, function() {        
          PauseAnim = false;
          autoAdvanceClient();
          //$(this).css('cursor','default');
        });
	});
	
	/* Change the containing div's width to the exact width of all the Clients combined */
	$('#Clients').width(totClientsWidth);
	
	/* Get the first clients width, to do the swap check */
	if (ClientWidths.length>0)
	  leftMostClientWidth = ClientWidths[0];
	
	ClientsLargerThenMask = (totClientsWidth > ContainingDivWidth);
	
	/*****
	 *
	 *	Enabling auto-advance.
	 *
	 ****/
	
	function autoAdvanceClient()
	{
	    if (PauseAnim) return; //To resume, call autoAdvanceClient()
	    
        // No need to scroll clients!
		if (!ClientsLargerThenMask) return;

		Offset += PixelIncrements;		
		$('#Clients').animate(
          {marginLeft:-Offset+'px'}, 
		  {
		    duration: animInterval, 
		    easing: 'linear',
            complete: SwapClient
          } 
        );
	}
	
	function SwapClient()
	{
      if (Offset > leftMostClientWidth)
      {
        //alert('swapping');
        $('#Clients .client').eq(0).appendTo($('#Clients'));
        Offset -= leftMostClientWidth;
        $('#Clients').css("marginLeft", -Offset+'px');
        leftMostClientWidth = $('#Clients .client').eq(0).width();
        //alert('swapped');
	  }
	  
	  autoAdvanceClient();
    }

	// The number of seconds that the slider will auto-advance in:
	
	var itvl = null;
	
	if (ClientsLargerThenMask)
	    autoAdvanceClient();

	/* End of customizations */
});
