$(document).ready(function () {
  
  var list = $("#img-rotator a");
  var current_index = 0;

  // setup a function to show the current one and increase the index
  var doNext = function() {  
    // increment the index - if it is beyond the number of li's - reset it to 0
    var current_index = $('#img-rotator a').index($('.show'));
    if (current_index+1 >= list.length){
        next_index = 0;
    }else{
        next_index = current_index + 1;
    }
    
    animateAd(current_index, next_index);
  };

  // set it up to be called every 5000 ms
  var t = setInterval(doNext, 7000);
  
  $('ul.topImgNumber li').click(function(){
     var next_index = $('ul.topImgNumber li').index(this);
     var current_index = $('#img-rotator a').index($('.show'));
     animateAd(current_index, next_index);
     clearTimeout(t);
  });
  
  function animateAd(current_index, next_index){
	   
	   var current = list.eq(current_index);		 
	   var next = list.eq(next_index);
	   
	   if(!next.hasClass("show")){
		   //Set the fade in effect for the next image, show class has higher z-index 
		   next.css({opacity: 0.0}).animate({opacity: 1.0}, 500)
		   .addClass('show');
			
		   //Hide the current image  
		   current.animate({opacity: 0.0}, 500)
		   .removeClass('show');
           
           $('ul.topImgNumber li').eq(current_index).removeClass('on');
           $('ul.topImgNumber li').eq(next_index).addClass('on');
	   }
    }
});