var ImageZoomer = Class.create({
  initialize: function(image) {
    this.image = $(image);
    this.img = this.image.down('img');
    this.image.observe('click', this.zoom.bind(this));
  },
  zoom: function() {
    if (this.image.hasClassName("zoom")) {
      this.image.removeClassName("zoom");
      this.image.addClassName("nozoom");
      this.clearComputedStyles();
    } else {
      this.image.removeClassName("nozoom");
      this.image.addClassName("zoom");
      this.computeStyles();
    }
  },
  clearComputedStyles: function() {
    this.img.style.height = '';
    this.img.style.marginTop = '';
  },
  computeStyles: function() {
    var windowSize = document.viewport.getDimensions();
    var imageSize = this.img.getDimensions();
    if (imageSize.height > (windowSize.height - 40)) {
      var height = windowSize.height - 40;
      imageSize.height = height + 40;
      this.img.style.height = height + "px";
    }
    var margin = (windowSize.height - imageSize.height)/2;
    this.img.style.marginTop = margin + "px";
  }
});

Event.observe(window, 'load', function() {
  $$('.image').each(function(image) {
    new ImageZoomer(image);
  })
  // hackish preemptive image load
  new Element("img", {src: "/images/zoom-bg.png"});
})