/*
 * CB5 interface Javascript
 *
 * Copyright 2009 Fund for the City of New York
 * This is free software. Use and distribution are subject to the terms
 * of the FCNY Open Source Software License. See license.txt, or
 * http://fred.fcny.org/fcny-ossl.txt
*/

// cb5.slideshow object
var cb5 = {"version": "1.0"};

cb5.slideshow = function( e, p ) {
  this.version = "1.0";
  // no active slide to start
  this.slides = [];
  this.activeSlide = false;

  this.init(e, p);
}

// show a slide, hide others
cb5.slideshow.prototype.showSlide = function ( id ) {
  if ( id ) {
    nextSlide = $( id );
    if ( nextSlide && hasElementClass( nextSlide, "slide" ) ) {
      if ( this.activeSlide ) {
        this.activeSlide.style.display = 'none';
        this.activeSlide = false;
      }
      this.activeSlide = nextSlide;
    }
  }
  if ( !this.activeSlide ) {
    this.activeSlide = this.slides[0];
  }
  log("Active slide",this.activeSlide.id);
  this.activeSlide.style.display = 'block';
}

// click handler
cb5.slideshow.prototype.controlClick = function ( e ) {
  e.stop();
  var slideid = e.src().hash.substr(1);
  window.location.hash = e.src().hash;
  this.showSlide( slideid );
}

// init handler
// @param object event e
// @para object htmlElement p
cb5.slideshow.prototype.init = function( e, p ) {
  if( typeof(p) == 'undefined' ) {
    p = currentDocument();
  }
  this.slides = new Array();
  var tmp = getElementsByTagAndClassName("div", "slide", p);
  for( i = 0; i < tmp.length; i++ ) {
    this.slides[tmp[i].id] = tmp[i];
  }
  this.slides[0] = this.slides[tmp[0].id];
  log("Found slides",this.slides)
  // modifiy all slidenav links to use the controlClick handler
  var slidecontrols = getElementsByTagAndClassName( "a", "slidenav", p);
  for ( i=0; i<slidecontrols.length; i++ ) {
    connect( slidecontrols[i], "onclick", this, "controlClick" );
  }
  log("Captured",slidecontrols.length,"slide navigation links");
  // check hash and display slide, otherwise display first slide
  var hashval = false;
  if ( window.location.hash ) {
    hashval = window.location.hash;
    if ( hashval.substr( 0, 1 )=="#" ) {
      hashval = hashval.substr( 1 );
    }
  }
  if ( hashval && typeof(this.slides[hashval]) != 'undefined' ) {
    log("Showing slide",hashval);
    this.showSlide( hashval );
  }
  else {
    log("Showing first slide");
    this.showSlide();
  }
}

//connect(window,"ondomload",cb5.slideshow,"init");
