jQuery(function($){

var ns = 'GallerySlideShow';

var gss = window[ns] = function ( options ) {
  this.options = options || {};
  this.root    = $(this.options.root);
  this.box     = $(this.options.box);
  this.item    = $(this.options.item);
  this.counter = $(this.options.counter);
  this.prev    = $(this.options.prev);
  this.next    = $(this.options.next);

  this.enable  = this.box.length && this.item.length ? true : false;
  if ( ! this.enable ) return;
  
  this.index   = 0;
  this.active  = -1;
  this.size    = this.item.length;
  
  this.initialize();
  this.observe();
};

gss.prototype = {
  
  initialize: function () {
    this.item.hide();
    this.go( this.index );
  },
  
  observe: function () {
    this.prev.click( $.proxy( this.go_prev, this ) );
    this.next.click( $.proxy( this.go_next, this ) );
  },
  
  fadeOut: function ( index ) {
    this.item.eq(index).fadeOut(300);
  },
  
  fadeIn: function ( index ) {
    this.item.eq(index).fadeIn(300);
  },
  
  changeHeight: function ( index ) {
    var height = this.item.eq(index).height() + 50;
    this.box.animate({height: height + 'px'}, 300);
  },
  
  go: function ( index ) {
    if ( this.active != -1 ) {
      this.fadeOut(this.active);
    }
    
    this.fadeIn(index);
    this.active = index;
    this.changeHeight(index);

    this.counter.text(index + 1);
  },
  
  handle_event: function ( event ) {
    if ( event && event.preventDefault ) event.preventDefault();
    if ( event && event.target && event.target.nodeName.toLowerCase() == 'a' ) event.target.blur();
  },
  
  go_prev: function ( event ) {
    this.handle_event( event );
    this.index--;
    if ( this.index < 0 ) {
      this.index = this.size - 1;
    }
    this.go( this.index );
  },
  
  go_next: function ( event ) {
    this.handle_event( event );
    this.index++;
    if ( this.index >= this.size ) {
      this.index = 0;
    }
    this.go( this.index );
  }
  
}


});
