﻿///<reference path="jquery-1.4.1-vsdoc.js" />
(function ($) {
  $.fn.newsslider = function () {
    var animating = false;
    var itemWidth = 450;
    var position = 0;
    var items = 0;
    var timer = null;
    var timerTime = 7000;

    function animate(direction) {
      if (animating) {
        return;
      }

      position += direction;

      if (position < 0) {
        position = items - 1;
      } else if (position >= items) {
        position = 0;
      }

      animating = true;

      animateTo(position);

      return false;
    }

    function animateTo(location) {
      $('#filmGalleryWrapper').animate({ 'left': -(location * itemWidth) + 'px' }, 'slow', function () { animating = false; });
      $('.indicatorArrow').removeClass('active');
      $($('.indicatorArrow')[location]).addClass('active');
      position = location;
    }

    function moveNext() {
      animate(+1);
      timer = setTimeout(moveNext, timerTime);
    }

    return this.each(function () {
      items = $('#filmGalleryWrapper').children().length;

      $('#filmGallery').find('#filmGalleryWrapper').each(function () {
        $(this).css('width', (items * itemWidth) + 'px');
      });

      $('.indicatorArrow').click(function () {
        clearTimeout(timer);
        animateTo($(this).prevAll().length - 1);
      });

      $('#filmGallery').find('a#prevArrow').click(function () { clearTimeout(timer); animate(-1); });
      $('#filmGallery').find('a#nextArrow').click(function () { clearTimeout(timer); animate(+1); });

      timer = setTimeout(moveNext, timerTime);
    });
  };
})(jQuery);
