/**
 * standby portfolio (media) javascript include
 * 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
 */

// slides object
var slides = { "version":"1.0" }
var portfolioPos;
var portfolioSize;

slides.activeslide = false;

slides.showslide = function ( id, y ) {
  addElementClass( $('Portfolio'), 'lightbox' );
  var slide = $(id);
  if ( !slide ) return;
  if ( this.activeslide ) {
    this.activeslide.style.display = 'none';
    signal( this.activeslide, "deactivate" );
  }
  this.activeslide = slide;
  this.activeslide.style.display = 'block';
  this.activeslide.style.top = y+"px";
  var videoid = getNodeAttribute( slide, "videoid" );
  if ( videoid ) {
    log("Playing",videoid);
    window.setTimeout( "$('flowplayer"+videoid+"').DoPlay()", 1000 );
  }
  signal( this.activeslide, "activate" );
}

slides.close = function () {
  if ( this.activeslide ) {
    this.activeslide.style.display = 'none';
    //signal( this.activeslide, "deactivate" );
  }
  removeElementClass( $('Portfolio'), 'lightbox' );
}

slides.clickhandler = function ( e ) {
  if ( e.target().tagName=='A' ) return;
  e.stop();
  e.src().blur();
  var elepos = getElementPosition( e.src() );
  var y = elepos.y - portfolioPos.y - 12;
  if ( (y+300) > portfolioSize.h ) {
    y = portfolioSize.h - 300;
  }
  log( "Clicked pos",elepos );
  var id = e.src().id.substr(1);
  this.showslide( id, y );
}

slides.init = function() {
  portfolioPos = getElementPosition( $('Portfolio') );
  portfolioSize = getElementDimensions( $('Portfolio') );
  // find slidenav links
  iterateElementsByTagAndClassName ( "table", "slidenav", $('Object'), function( navs, i ) {
    connect( navs[i], "onclick", slides, "clickhandler" );
    var slideid = navs[i].id.substr(1);
    var slide = $(slideid);
    if ( slide ) {
      connect( slide, "activate", function() { addElementClass( navs[i], "active" ) } );
      connect( slide, "deactivate", function() { removeElementClass( navs[i], "active" ) } );
    }
  });
  // show a different slide if requested
  if ( window.location.hash ) {
    var id = window.location.hash.substr(1);
    var isslide = $(id);
    if ( hasElementClass( isslide, "slide" ) ) {
      log("Showing slide on this page",id);
      this.showslide( id, 0 );
    }
  }
}

connect( window, "ondomload", slides, "init" );