$(document).ready(function(){
  spSlider = $('.spSlider');
  spThumbs = spSlider.find('ul'); //thumbs
  thumbH = spThumbs.find('li:first').height(); //высота
  imageCount = spThumbs.find('li').size();
  curIndex = 0;
  var spTimeout;
  
  spImages = spSlider.find('.spImages');
  z_i = 1;
  spImages.find('a').each(function(){
    $(this).css('z-index',imageCount-z_i);
    z_i++;
  });
  //$(spImages.find('a').get(0)).css('z-index',0);
  
  var lastThumb = spThumbs.find('li').last().detach();
  spThumbs.prepend(lastThumb);
  
  $(spThumbs.find('li').get(1)).addClass('currentThumb');
  $(spImages.find('a').get(1)).addClass('currentImg');
  
  
  //делаем клон, чтоб была неприрывная прокрутка
  /*if (imageCount < 4) {
    spThumbs.find('li:first').clone().addClass('clone').appendTo(spThumbs);
    cloneTh = spThumbs.find('li.clone'); //ссылаемся на клон
  }*/
  
  
  function repos(){
    var temp = spThumbs.find('li:first').detach();
    spThumbs.css('margin-top',0);
    temp.appendTo(spThumbs);
    spThumbs.find('li.currentThumb').removeClass('currentThumb');
    $(spThumbs.find('li').get(1)).addClass('currentThumb');
    setTimeout(spNextImage,3000);
  }
  
  function spNextImage() {
    spThumbs.animate({'margin-top':'-='+thumbH},{queue:false, duration:300, complete:repos});
    if (curIndex < imageCount-1) {
      curIndex++;
    } else {curIndex = 0}
    var nextImg = $(spImages.find('a').get(curIndex));
    nextImg.css('opacity',0);
    nextImg.css('z-index',z_i);
    nextImg.animate({'opacity':1},{queue:false, duration:300})
    z_i++;
  }

  setTimeout(spNextImage,3000);
})
