/*
A super simple javascript slideshow

Copyright (c) 2007 Aaron Suggs (aaron@ktheory.com)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

var Slideshow = Class.create();
Slideshow.addMethods({
  // Slideshow constructor method
  initialize : function(){
    // Each HTML element with class="slide" is considered to be a slide in the slideshow
    this.slides = $$('.slide');
    this.slidesCount = this.slides.size();
    this.delay = 9990; // number of milliseconds before moving to the next slide
    this.stopped = false // Is the slideshow stopped?
    // The index points to the element of the slides array that we're currently showing
    this.index = 0;

    this._updateSlide();
  },
  
  // Display the next slide
  next : function(){
    this.index = (this.index + 1) % this.slidesCount
    this._updateSlide();
  },
  
  // Display the previous slide
  previous : function(){
    this.index = (this.index - 1 + this.slidesCount) % this.slidesCount;
    this._updateSlide();

  },
  
  // Stop the slideshow from automatically advancing
  stop : function(){
    this.stopped = true;
    this._resetTimer();
  },
  
  // Begin of resume automatically advancing the slideshow
  play : function(){
    this.stopped = false;
    this._resetTimer()
  },
    
  // Private method to hide all slides,
  // then show the slide at the proper index
  _updateSlide : function(){
    // hide all the slides
    this.slides.invoke('hide');
    // Show the slide at the index
    this.slides[this.index].show();
    
    this._resetTimer();
  },
  // Reset the timer
  _resetTimer : function(){
    clearTimeout(this.timer);
    if (!this.stopped) this.timer = setTimeout(this.next.bind(this), this.delay)
  }
  
});

// When the page loads, instantiate the slideshow
Event.observe(window, "load", function(){
  window.slideshow = new Slideshow();
});