/* 
 * Uses the IZI URL toolbox to control slimbox
 */

var SlimboxThroughURL = new Class( {

  photos: new Array(),
  currentIndex: -1,

  initialize: function ()
  {
    window.addEvent( 'domready', this.boot.bind(this) );
  },

  boot: function ()
  {
    // Listen to URL
    IZI.toolbox.URL.addListener( this.listenToChanges.bind(this) );
    this.listenToChanges( IZI.toolbox.URL.getVariables() );

    // Listen to lightbox
		$("lbPrevLink").addEvent( 'click', this.listenToSlimboxPrevious.bind( this ) );
	  $("lbNextLink").addEvent( 'click', this.listenToSlimboxNext.bind( this ) );
    $("lbCloseLink").addEvent( 'click', this.listenToSlimboxClose.bind( this ) );
    $("lbOverlay").addEvent( 'click', this.listenToSlimboxClose.bind( this ) );

    var links = $$(document.links).filter(function(el) {
      return el.rel && el.rel.test(/^izibox/i);
    });
    links.each( function ( el ) {
      el.addEvent( 'click', this.onThumbClick.bindWithEvent( this, el ) );
      this.photos.push( this.getPhotoUrlFromRel( el.get( 'rel' ) ) );
    }.bind( this ) );
  },

  getPhotoUrlFromRel: function ( rel )
  {
    rel = rel.replace( /^izibox\['/, '' );
    rel = rel.replace( /\']/, '' );
    return rel;
  },

  onThumbClick: function ( event, el )
  {
    event = new Event( event );
    event.preventDefault();
    IZI.toolbox.URL.add( 'photo', this.getPhotoUrlFromRel( el.get( 'rel' ) ) );
  },

  listenToSlimboxNext: function ()
  {
    this.currentIndex++;
    IZI.toolbox.URL.add( 'photo', this.photos[this.currentIndex] );
  },

  listenToSlimboxPrevious: function ()
  {
    this.currentIndex--;
    IZI.toolbox.URL.add( 'photo', this.photos[this.currentIndex] );
  },

  listenToSlimboxClose: function ()
  {
    this.currentIndex = -1;
    IZI.toolbox.URL.add( 'photo', '' );
  },

  listenToChanges: function ( variables )
  {
    if ( variables.photo && variables.photo != this.photos[this.currentIndex] ) {
      // Show the photo
      var photo = document.getElement( 'a[rel="izibox[\'' + variables.photo + '\']"]' );
      if ( photo ) {
        // Find all available photos
        var elements = $$(document.links).filter(function(el) {
          return el.rel && el.rel.test(/^izibox/i);
        });
        var photos = new Array();
        var startImage = 0;
        elements.each( function (el, key ) {
          photos.push( [escape(el.get( 'href' )), el.get( 'title' )] );
          if ( el.get( 'href' ) == photo.get('href') ) startImage = key;
        } );
        Slimbox.open( photos, startImage );
        this.currentIndex = startImage;
      }
    }
  }
} );

var SBTU = new SlimboxThroughURL();