/* made by RJ - emperor */
$(function() {
  var amountImages = $('#imageSlider .images img').length;
  var listWidth = $('#imageSlider .buttons ul li').width();
  //var imageWidth = $('#imageSlider .images img').width();
  var imageWidth = 210;
  var imageSpace = 10;
  var currentID = 0;
  var speed = 500;
  var timer;

  $('#imageSlider .images .slider').css('width', (imageSpace + imageWidth) * amountImages);
  $('#imageSlider .buttons ul').empty();
  $('#imageSlider .buttons ul').css('width', listWidth * amountImages);
  $('#imageSlider .images img').each(function(index) {
    $('#imageSlider .buttons ul').append('<li><a href="#">' + index + '</a></li>');
  });

  function autoScroll() {
    if ($('#imageSlider .images').queue() == 0) {
      var iNext = currentID + 1;
      if (iNext > amountImages - 1) {
        iNext = 0;
      }
      scrollImage(iNext);
    }
  }

  function clickScroll() {
    clearTimeout(timer);
    var thisID = $(this).index('#imageSlider .buttons ul li a');
    scrollImage(thisID);
    return false;
  }

  function scrollImage(id) {
    clearTimeout(timer);
    $('#imageSlider .buttons ul li').removeClass('active');
    $('#imageSlider .buttons ul li').eq(id).addClass('active');
    $('#imageSlider .images').animate({
      left: -(id * (imageWidth + imageSpace))
    }, Math.abs((currentID - id) * speed), function() {
      currentID = id;
      timer = setTimeout(function() { autoScroll(); }, 3000);
    });

  }

  $('#imageSlider .buttons ul li').eq(0).addClass('active');
  $('#imageSlider .buttons ul li a').click(clickScroll);
  timer = setTimeout(function() { autoScroll(); }, 3000);

});
