// Add a css selector for javascript dependent states.
document.documentElement.className += ' hasJS';

/**
 *	A slide show for brookelgie.com
 *	Depends on Prototype.js, Effects.js (Scriptaculous) and fader.js.
 *
 *  @author Brook Elgie
 */
 
var slideShows = [];

var initSlideShows = function() {
  var imageContainers = $$('.image_container');
  imageContainers.each(function(imgContainer, index) {
    // Create slide show.
    slideShows.push(createSlideShow(imgContainer));

    // Remove unecessary elements.
    try {
      imgContainer.select('h3')[0].remove();     
    } catch (er) { }
    try {
      imgContainer.select('.more_images')[0].remove();     
    } catch (er) { }
  }.bind(this));
};


var createSlideShow = function(imgContainer) {
  // An array to pass to the Fader containing the images to transition through.
	var slideShowImages = [];
	
	// Find the additional images for the slide show.
	var imageList = imgContainer.select('.more_images li');
  imageList.each(function(li, index) {
    var link = li.select('a')[0];
    var cite = li.select('.image_caption')[0];
    var slideShowObject = {
      imgPath:link.readAttribute('href'),
      imgAlt:String(link.text),
      imgCaption:cite
    };
    slideShowImages.push(slideShowObject);
  }.bind(this));
  
  // Also add the currently displaying image to the end of slideShowImages (so it loops).
  var lastImage = imgContainer.select('img')[0];
  var caption = imgContainer.select('.image_caption')[0];
  var lastImageObject = {
    imgPath:lastImage.readAttribute('src'),
    imgAlt:lastImage.readAttribute('alt'),
    imgCaption:caption
  };
  slideShowImages.push(lastImageObject);
  
  // A slideShow of class Fader. Pause is false by default.
  var slideShow = new Fader(slideShowImages, imgContainer.id, {crossfade:true, fadeInDuration:1.5, displayDuration:7.0, pause:false});

  if(slideShowImages.length > 1) {
    // Make a next button and insert it after the image container.
    var newTag = Element.extend(document.createElement('a'));
  	newTag.writeAttribute('href', '#');
  	newTag.writeAttribute('class', 'next_image');
  	newTag.update("Next");    

    // Hook up the next button action.
    newTag.observe('click', function(ev) {
      ev.stop();
      slideShow.options.pause = true;
      slideShow.next();
    }.bind(this));
  }

	imgContainer.insert({after:newTag});
	
	// Return the slideshow.
	return slideShow;
};


/**
*	Do stuff once the window has loaded.
*/
Event.observe(window, 'load', initSlideShows);
