var PortfolioView = new Class({
  thumbnails: null,
  current_thumbnail: 0,
  timer: 0,
  interval: 5000,

  initialize: function ()
  {
    this.thumbnails = $$('li.portfolio-thumbnail');
    this.initializeThumbnails();
    if( this.thumbnails.length > 1 ) this.initializeNavigator();
    this.setThumbnail();

    if( this.thumbnails.length > 1 ) {
      this.setNavigator();
      this.timer = this.loop.periodical(this.interval, this);
    }
  },

  reset: function ()
  {
    $clear( this.timer );
    this.interval = 5000;
    this.current_thumbnail = 0;

    this.initialize();
  },

  initializeThumbnails: function()
  {
    $each( this.thumbnails, function( thumbnail ) {
      thumbnail.setStyles({'visibility': 'hidden', 'opacity': 0});
    });
  },

  initializeNavigator: function()
  {
    $each( $$('li.portfolio-navigator'), function( navigator, index ) {
      if( index == 0 ) navigator.getElement('a').addClass('active');

      navigator.addEvent('click', function( event ) {
        event.stop();
        this.showThumbnail( index );
      }.bind(this));
    }.bind(this));
  },

  setThumbnail: function()
  {
    // Display current thumbnail
    this.thumbnails[ this.current_thumbnail ].tween( 'opacity', [0, 1] );
  },

  hideAll: function ()
  {
    this.thumbnails.tween('opacity', 0 );
  },

  setNavigator: function()
  {
    $each( $$('li.portfolio-navigator'), function( navigator, index ) {
      if( this.current_thumbnail == index ) {
        navigator.getElement('a').addClass('active');
      } else {
        navigator.getElement('a').removeClass('active');
      }
    }.bind(this));
  },

  loop: function()
  {
    if( this.current_thumbnail + 1 < this.thumbnails.length ) {
      this.current_thumbnail++;
    } else {
      this.current_thumbnail = 0;
    }
    this.hideAll();
    this.setThumbnail();
    this.setNavigator();
  },

  showThumbnail: function( index )
  { 
    $clear( this.timer );
    this.timer = this.loop.periodical(this.interval, this);
    this.current_thumbnail = index;
    this.hideAll();
    this.setThumbnail();
    this.setNavigator();
  }
});
var portfolioview;
window.addEvent('domready', function() {
  portfolioview = new PortfolioView();
});
