var ImageScaler = Class.create({
  initialize: function(element, options) {
    this.element = $(element);
    this.options = Object.clone(ImageScaler.DEFAULT_OPTIONS);
    Object.extend(this.options, options || {});
    
    this.src = this.element.readAttribute('src');
    this.ratio = this.element.width / this.element.height;
    
    if (Prototype.Browser.IE) this._fixForIE();
    this.resize();
  },
  
  _fixForIE: function() {
    this.element.setStyle({
      // IE >=7 can do this with a proprietary CSS style...
      '-ms-interpolation-mode': 'bicubic',
      // But IE6 needs the stupid filter.
      filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='#{0}', sizingMethod='scale');".interpolate([this.src])
    });
  },
  
  resize: function() {
    if (!window.isFinite(this.ratio)) return;

    // Don't scale images up. Only scale them down.
    if (this.width < this.options.width) return;
    
    var w = this.width, h = this.height;
    
    if (Object.isNumber(this.options.width)) {
      w = this.options.width;
      h = Math.round(w / this.ratio);
    }
    
    if (Object.isNumber(this.options.height)) {
      h = this.options.height;
      w = Math.round(h * this.ratio);
    }

    Object.extend(this.element, { width: w, height: h });
  }
});

Object.extend(ImageScaler, {
  DEFAULT_OPTIONS: {
    width:  'auto',
    height: 'auto'
  }
});


Event.observe(window, 'load', function() {
  $$('.image .photo').each( function(img) {
    new ImageScaler(img, { width: 450 });
  });
});