(function() {

var rotators = [], direction = 1, ROTATION_SPEED = 5000, FADE_SPEED = 700;

function rotate(rotator) {
  rotator.currentIdx++;
  if (rotator.currentIdx > rotator.images.length - 1) {
    rotator.currentIdx = 0;
  }

  var image = rotator.images[rotator.currentIdx];
  rotator.container.find('a').attr('href', image.link ? image.link : '#');

  if (direction == 1) {
    rotator.container.find('img.other').show().attr('src', image.src).attr('alt', image.alt);
    rotator.container.find('img.current').fadeOut(FADE_SPEED);
    direction = 0;
  } else {
    rotator.container.find('img.current').attr('src', image.src).attr('alt', image.alt)
      .fadeIn(FADE_SPEED, function() {
        rotator.container.find('img.other').hide();
      });
    direction = 1;
  }
};

ImageRotator = {
  register: function register(images, imageContainer) {
    var imgObj = { container: $(imageContainer), images: images, currentIdx: 0 };
    rotators.push(imgObj);
    for (var i=0, image; image = images[i]; i++) {
      image.obj = new Image();
      image.obj.src = image.src;
    }
  },
  autoRotateAll: function autoRotateAll() {
    setInterval(function() {
      for (var i = 0, rotator; rotator = rotators[i]; i++) {
        rotate(rotator);
      }
    }, ROTATION_SPEED);
  }
};

})();
