$(function() {
  var cont = $('#imgarea');
  var box  = $('#img');
  var btn  = $('#btn');
  var next = $('#btn .next');
  var prev = $('#btn .prev');
  var size = 745;
  var time = 5000;
  var timerID;
  var leIE8 = navigator.userAgent.indexOf('MSIE')   != -1 &&
              navigator.userAgent.indexOf('MSIE 9') == -1 ? true : false;

  slideTimer();
  next.click(nextClick);
  prev.click(prevClick);
  next.mouseup(slideTimer);
  prev.mouseup(slideTimer);
  if (!leIE8) {
    btn.hide();
    cont.hover(
      function() { btn.stop(true, true).fadeIn(); },
      function() { btn.stop(true, true).fadeOut(); }
    );
  }

  function nextClick() {
    box.not(':animated').animate({
      marginLeft : parseInt(box.css('margin-left')) - size + 'px'
    }, 'slow', function() {
      box.css('margin-left', 0);
      $('img', box).first().appendTo(box);
    });
  }

  function prevClick() {
    if (box.is(':animated')) { return false; }
    box.css('margin-left', - size + 'px');
    $('img', box).last().prependTo(box);
    box.animate({
      marginLeft : parseInt(box.css('margin-left')) + size + 'px'
    }, 'slow');
  }

  function slideTimer() {
    clearInterval(timerID);
    timerID = setInterval(nextClick, time);
  }
});

