
// Singleton type object for image control functionality
var ImageEnlarger = {
  images: [],
  placeholder: null,
  index: 0,
  
  initialize: function() {
    var prev = $('prev-image');
    var next = $('next-image');
    this.placeholder = $('enlarge-image');
    
    if (!this.placeholder)
      return;
      
    if (prev) {
      Event.observe(prev, 'click', this.prevImage.bind(ImageEnlarger));
    }
    
    
    
    if (next) {
      Event.observe(next, 'click', this.nextImage.bind(ImageEnlarger));
    }
    
    $$('.thumbnail').each(
      function(element) {
        new EnlargableImage(element)
      }
    );
    
    this.updateControls(); 
    
  },
  
  enlarge: function( image ) {
    this.index = this.images.indexOf(image);
    this.placeholder.src = image.large.src;
    
    this.updateControls();
    
  },
  
  showImage: function(i) {
    this.index = i;
    this.changeImage();
  },
  
  nextImage: function() {
    
    this.index++;

    
    if(this.index > (this.images.length - 1))
      this.index = 0;
      
    this.changeImage();
  },
  
  prevImage: function() {
   this.index -= 1;
   if(this.index < 0)
    this.index = (this.images.length - 1);
    
    this.changeImage();
  },
  
  changeImage: function() {
    Effect.Fade(this.placeholder, {duration: .3, queue: { position: 'end', scope: 'enlargeimages'}});
    window.setTimeout(function() { ImageEnlarger.hideImage()}, 300);    
    
  },
  
  hideImage: function() {
    this.placeholder.hide();
    this.placeholder.src = this.images[this.index].large.src;
    Effect.Appear(this.placeholder, {duration: .3, queue: { position: 'end', scope: 'enlargeimages'}});
    this.updateControls();
  },
  
  register: function(image) {
    this.images.push(image);
  },
  
  updateControls: function() {

    var controls = $('image-controls');
    controls.update(' ');
    if (!controls)
      return;
      
    this.images.each(
      function(image, i) {
        var classes = '';
        if (i == this.index) {
          classes += ' image-current';
        }

        var a = new Element('a', { 'class': classes, 'href': 'javascript: ImageEnlarger.showImage(' + i + ');' }).addClassName('image-control').update(i+1);
        controls.appendChild(a);
        
      }
    , this);
  }
  
};

var EnlargableImage = Class.create({
  thumb: null,
  large: null,
  
  initialize: function(thumb, large) {
  
    this.thumb = thumb;
    this.large = new Image();
    this.large.src = thumb.title;
    
    // Change the title to something more elegant
    thumb.title = 'Click to enlarge.';
    
    Event.observe(this.thumb, 'click', this.enlarge.bind(this));
    ImageEnlarger.register(this);
  
  },
  
  enlarge: function() {
    ImageEnlarger.enlarge(this);
  }

});


Event.observe(window, 'load', ImageEnlarger.initialize.bind(ImageEnlarger));




