//
//  slideshow.js
//

var IRSlideshow = Class.create({
  defaultDuration:   6.0,
  defaultTransition: 0.66,
  
  initialize: function (element) {
    this.element = element;
    this.slides  = element.select("li").map(function (element) {
      return new IRSlide(this, element);
    }.bind(this)).reverse(false);
    this.controller = new IRController(this);
    this.showSlide(0);
    this.controller.play();
  },
  
  showNextSlide: function () {
    this.showSlide((this.currentIndex || 0) + 1);
  },
  
  showPreviousSlide: function () {
    this.showSlide((this.currentIndex || 0) - 1);
  },
  
  showSlide: function (index) {
    index = index % this.slides.size();
    while (index < 0)
      index = this.slides.size() + index;
    this.previousIndex = this.currentIndex;
    this.currentIndex  = index;
    if (this.currentIndex == (this.previousIndex || 0))
      this.slides[this.currentIndex].show();
    else {
      this.slides[this.currentIndex].show();
      this.slides[this.previousIndex].hide();
    }
  },
});

var IRSlide = Class.create({
  initialize: function (slideshow, element) {
    this.slideshow = slideshow;
    this.element   = element;
    this.prepareAnimation();
  },
  
  prepareAnimation: function () {
    this.element.setOpacity(0.0);
    this.animator = new Animator().addSubject(
      new NumericalStyleSubject(this.element, "opacity", 0.0, 1.0));
    this.animator.options.duration = 4000;
  },
  
  show: function () { this.animator.seekTo(1.0); },
  hide: function () { this.animator.seekTo(0.0); },
  
  showWithoutAnimation: function () {
    this.animator.jumpTo(1.0);
  },
  
  hideWithoutAnimation: function () {
    this.animator.jumpTo(0.0);
  },
  
  showAndReplaceSlide: function (oldSlide) {
    this.element.style.zIndex = oldSlide.element.style.zIndex + 1;
    Object.extend(this.options, {
      onComplete: oldSlide.hideWithoutAnimation.bind(oldSlide)
    });
    this.show();
  },
});

var IRController = Class.create({
  initialize: function (slideshow) {
    this.slideshow = slideshow;
    this.isPlaying = false;
  },
  
  play: function () {
    if (this.isPlaying) return;
    this.isPlaying = true;
    this.timer = new PeriodicalExecuter(function () {
      this.showNextSlide();
    }.bind(this), 6.0);
  },
  
  pause: function () {
    this.timer.stop();
    this.isPlaying = false;
  },
  
  showNextSlide: function () {
    return this.slideshow.showNextSlide();
  },
  
  showPreviousSlide: function () {
    return this.slideshow.showPreviousSlide();
  },
  
  showSlide: function (index) {
    this.pause();
    return this.slideshow.showSlide(index);
  },
});

Event.observe(window, "load", function () {
  $$("ul.slideshow").each(function (element) {
    new IRSlideshow(element);
  });
});

