var AnchorObserver = { enabled:  true, interval: 0.1 };

AnchorLink = Class.create({
  initialize: function(func) {    
    this.callback = func;
    this.observeLinks();
  },
  
  observeLinks: function() {
    document.observe("anchor:changed", this.showAnchor.bind(this));
    /* Adds an observer that polls to see if the URL anchor has chnaged. */
    document.observe("dom:loaded", function() {
      var lastAnchor = "";
      function poll() {
        var anchor = (window.location.hash || "").slice(1);
        if (anchor != lastAnchor) {
          document.fire("anchor:changed", { to: anchor, from: lastAnchor });
          lastAnchor = anchor;
        }
      }
    
      if (AnchorObserver.enabled) {
        setInterval(poll, AnchorObserver.interval * 1000);
      }
    });
  },
  
  getAnchor: function() {
    return window.location.hash.split('#')[1];
  },
  
  showAnchor: function() {
    if(window.location.hash) {
      this.callback(this.getAnchor());
    }
  }
});

AnchorLink.set = function(anchor) {
  window.location.hash = '#'+anchor;
}

SlideShow = Class.create({
  initialize: function(autofade, interval) {
    this.root = $('slides');
    this.interval = interval;
    this.interval_id = null;
    if (!this.root) {alert('There is no viewport. Add #slides div to your HTML document to use this slide show.');}
    new AnchorLink(this.handle_click.bind(this));
    if (autofade) {
      document.observe("dom:loaded", function() {
        var lastAnchor = "";
        this.interval_id = setInterval(this.poll, interval);
      }.bind(this));
    }
  },
  
  poll: function() {
    var current = $$('#slides .slide.current').first();
    if (current) {
      var next    = current.nextSiblings().first();
      if (!next) {next = $$('#slides .slide').first();}
      AnchorLink.set(next.identify());            
    }
  },
  
  handle_click: function(anchor) {
    var current = $$('#slides .slide.current').first();
    var next = $(anchor);

    if (!current || !next || current.identify() == next.identify()) {return;}

    next.addClassName('current');
    current.removeClassName('current');

    current.setStyle('z-index:0');
    next.setStyle('z-index:100');

    current.fade({duration:0.5});
    next.appear({duration:3.0});

    $$('#slide_navigation .name').each(function(n){n.hide();})
    $$('#slide_navigation .name.'+anchor).first().show();

    $$('#slide_navigation .title').each(function(n){n.hide();})
    $$('#slide_navigation .title.'+anchor).first().show();
    
    if (this.interval_id != null) {
      clearInterval(this.interval_id);
      this.interval_id = setInterval(this.poll, this.interval);
    }    
  }
});

