image_slideshow = function(){
  profile_images = $('slideshow-images');
  if (profile_images) {
    ss = new SlideShow(profile_images, {slideshow_id: 'image-slideshow'});
  }
};

// Simple slideshow object. Creates a clickable slideshow from and conationer
// element and chlid elements. By default expects the child elements to be 'li'
var SlideShow = Class.create({
  initialize: function(element_id, options) {
    // Default options
    default_options = $H({
      item_elements: 'li',
      slideshow_id: null,
      slideshow_class: 'slideshow',
      slide_time: 5
    });
    
    
    this.options = default_options.merge(options || {});
    this.element  = $(element_id);
    this.items = this.element.select(this.options.get('item_elements'));
    this.items.each(function(el) {
      el.down("img").setStyle( { marginTop: Math.ceil( ( ( el.getHeight() - el.down("img").getHeight() )/2 ) ) + "px" } );
    });

    this.items.invoke('hide');
    this.items.invoke('setStyle', {position:'absolute'});
    this.current_view = this.items.first();
    this.current_view.show();
    // Create wrapper
    wrapper = new Element('div', {className: this.options.get('slideshow_class'), id: this.options.get('slideshow_id')});
    this.element.wrap(wrapper);

    // Insert previous and next buttons
    if(this.items.length>1){
      previous_button = new Element('span', {className: 'previous-slide'}).update('Previous');
      next_button = new Element('span', {className: 'next-slide'}).update('Next');
      wrapper.insert({top: previous_button, bottom: next_button});
      previous_button.observe('click', this.backward.bindAsEventListener(this));
      next_button.observe('click', this.forward.bindAsEventListener(this));
      this.start();
    }
  },
 
  start: function() {
    this.periodical = new PeriodicalExecuter(this.forward.bind(this), this.options.get('slide_time'));
  },
  
  stop: function() {
    this.periodical.stop();
  },

  forward: function() {
    this.stop();
    this.next_view = this.current_view.next(this.options.get('item_elements'));
    if(!this.next_view){
      //scroll back to first image
      this.next_view = this.items.first();
    }
    this.replace();
    this.start();
  },
  
  backward: function() {
    this.stop();
    this.next_view = this.current_view.previous(this.options.get('item_elements'));
    if(!this.next_view){
      //scroll forward to last image
      this.next_view = this.items.last();
    }
    this.replace();
    this.start();
  },

  replace: function() {   
    if (this.next_view) {
      this.next_view.appear();
      this.current_view.fade();
      this.current_view = this.next_view;
    }
  }



});

Event.observe(window, 'load', image_slideshow);