var slide_show;
function SlideShow() {
  this.pattern     = new RegExp(/slide_\d/);         // Naming convention to look for when finding slides.
  this.ui_elements = ['controls','slides','screen']; // Coresponds to divs in the associated HTML page.
  this.slides      = new Array();                    // Array containing found slides.
  this.index       = 0                               // Current slide
  this.interval    = 5                               // Number of seconds between each slide
  
  // Optional Parameters
  this.screen_height = 300                           // Set this variable if you want to force a consistent height.
  
  this.initialize = function() {
    this.slide_div = document.getElementById('slide_show');
    
    if(this.slide_div) {
      this.build();
    
      this.find_slides();
      this.initialized = true;
    }
  }
  
  this.build = function() {
    for(var x= 0; x< this.slide_div.childNodes.length; x++) {
      if(this.slide_div.childNodes[x].attributes) {
        for(var e = 0; e < this.ui_elements.length; e++) {
          if(this.slide_div.childNodes[x].getAttribute('id') == this.ui_elements[e]) {
            // Found a desired ui_element
            this['build_' + this.ui_elements[e]](this.slide_div.childNodes[x]);
          }
        }
      }
    }
  }
    
  this.build_controls = function(node) {
    // Create the various transport controls needed to control the playback of the automatic slideshow
    this['control_panel'] = document.createElement('ul');
    var buttons = [['last','&#171; prev'], ['play','play'], ['stop', 'pause'], ['next','next &#187;']]
    
    for(var b = 0; b < buttons.length; b++) {
      this[buttons[b][0] + '_button'] = document.createElement('li');
      this[buttons[b][0] + '_button'].setAttribute('id',buttons[b] + '_button');
      this[buttons[b][0] + '_button'].setAttribute('className','button');
      this[buttons[b][0] + '_link'] = document.createElement('a');
      this[buttons[b][0] + '_link'].setAttribute('href','javascript:slide_show.' + buttons[b][0] + '()');
      this[buttons[b][0] +'_link'].innerHTML = buttons[b][1];
      this[buttons[b][0] + '_button'].appendChild(this[buttons[b][0] + '_link']);
      this['control_panel'].appendChild(this[buttons[b][0] + '_button']);
    }
    
    node.appendChild(this['control_panel'])
  }
  
  this.build_slides = function(node) {
    //console.log('Build Slides');
    this.slides = this.find_slides(node)
    var links;
    
    for(var x = 0; x < this.slides.length; x++) {
      // Make a HTMLcollection of all anchor tags within this dom element
      if(links = this.slides[x].getElementsByTagName("a")) {
        for (var i = 0; i < links.length; i++) { 
          // Isolate just the href string
          href = links[i].getAttribute("href"); 
          
          // Ensure thumbnails look uniform.
          links[i].style.height   = '30px';
          links[i].style.width    = '50px';
          links[i].style.overflow = 'hidden';
          
          // Remove the old href and replace it with the JS function
          links[i].setAttribute('href','javascript:slide_show.show("' + this.slides[x].getAttribute('id') + '", "' + href + '")')
          links[i].removeAttribute('target')
        }  
      }
      
    }
  }
  
  this.build_screen = function(node) {
    if(imgs = node.getElementsByTagName("img")) {
      // Isolate just the img node
      for (var i = 0; i < imgs.length; i++) { this.screen = imgs[i] }
      if(this.screen_height) this.screen.setAttribute('height',this.screen_height);
    }
  }
  
  // Extract only the DOM elements, which contain slides
  this.find_slides = function(node) {
    if(!node) return
      
    var slides = new Array(); 
    tags = node.getElementsByTagName("*")
    var slide_id;
      
    for(var t = 0; t < tags.length; t++) {
      // return unless this node has attributes
      if(!tags[t].attributes) return;
        
      // only store the attributes with a matching id pattern
      if(slide_id = tags[t].getAttribute('id')) {
        if(slide_id.match(this.pattern)) slides.push(tags[t])
      } 
    }
    
    return slides
  }
  
  // Display an image
  this.show = function(element, href) {
    // Toggle off last selected slide 
    if(this.last_selected_slide) this.last_selected_slide.setAttribute('class','image')
    
    element = document.getElementById(element);
    elements = element.getElementsByTagName("*")
    
    // Find any nodes with the correct class and change it to the selected class.
    for(var e = 0; e < elements.length; e++) {
      if(image = elements[e].getAttribute('class')) {
        elements[e].setAttribute('class', 'selected_image')
        // This node now becomes the last selected slide.
        this.last_selected_slide = elements[e];
      }    
    }
    
    var img_loader = new Image;
    img_loader.slideshow = this;
    img_loader.onload  = function() {
        // Set the href of the screen's image to that of the selected thumbnail
        this['slideshow'].screen.setAttribute('src', href);
        this['slideshow'].set_timer();
    }
    
    // Preload the image first before displaying it on the screen.
    img_loader.src = href;
  }
    
  this.set_timer = function() {
    if (this.timer) clearInterval(this.timer);
    var level = this
    this.timer = setInterval(function(){level['next']()}, this.interval * 600);    
  }
  
  // Start the autoplay feature
  this.play = function() {
    if(this.initialized)
      this.set_timer();
  }
  
  // Stop the slideshow's autoplay
  this.stop = function() {
    if (this.timer) clearInterval(this.timer);
  }
  
  this.last = function() {
    ( 1 <= this.index ) ? this.index-- : this.index = this.slides.length -1;  

    this.trigger_link();  
  }
  
  this.next = function() {
    (this.slides.length > (this.index + 1)) ? this.index++ : this.index = 0;  

    this.trigger_link();
  }
  
  // Call a javascript function embeded in one of the slide thumbnails on the page.
  this.trigger_link = function() {
    if(links = this.slides[this.index].getElementsByTagName("a")) {
      for (var i = 0; i < links.length; i++) { 
        // Trigger the embeded javascript link;
        eval(links[i].getAttribute("href"));
      }
    }
  }
}

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);
  slide_show = new SlideShow();
  slide_show.initialize();
  slide_show.play();
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;