var max_counter = 162;
var h_counter = 134;
var w_banner = 940;
var timerCounter = null;
var timerCounterSpeed = 30;
var switchBannerSpeed = 7000;
var pauseBannerSpeed = 500;

function counter(){

    var hundreds = Math.abs(parseInt($('#hundreds').css('margin-top')));
    if(hundreds>=parseInt(max_counter%1000/100)*h_counter){
      var tens = Math.abs(parseInt($('#tens').css('margin-top')));
      if(tens>=parseInt(max_counter%100/10)*h_counter){
        var units = Math.abs(parseInt($('#units').css('margin-top')));
        if(units>=parseInt(max_counter%10)*h_counter){
        
          clearInterval(timerCounter);
          setTimeout(function(){
            switchBanner();
            setTimeout('switchBanner()', switchBannerSpeed);
          }, pauseBannerSpeed);
        
        } else
        counting();
      } else
      counting();
    } else
      counting();

}

function counting(){
  indent($('#random_banner'));
  
  if(indent($('#units')))
    if(indent($('#tens')))
      if(indent($('#hundreds')))
        indent($('#thousands'));
}

function indent(object){
  var sup = false;
  if(Math.abs(parseInt($(object).css('margin-top'))) >= $(object).height()-h_counter){
    $(object).css('margin-top', 0);
    sup = true;
  } else{
    $(object).css('marginTop', parseInt($(object).css('marginTop'))-h_counter);
  }
  
  return sup;
}

function switchBanner(){
  var newMarginLeft = parseInt($('#banner_container').css('margin-left')) == 0 ? -w_banner : 0;
  
  if(newMarginLeft == 0)
    $('.turn').css('margin-top', 0);
  
  $('#banner_container').animate(
    {marginLeft : newMarginLeft},
    800,
    function(){
      if(newMarginLeft == 0)
        timerCounter = setInterval('counter()', timerCounterSpeed);
    }
  );
}

// Lancement de l'animation
$(document).ready(function() {
  timerCounter = setInterval('counter()', timerCounterSpeed);

  $('#banner_1').click(function(){
    clearInterval(timerCounter);
    switchBanner();
    setTimeout('switchBanner()', switchBannerSpeed);
  })
});
