var Image = Image || {};
Image.Thumbnail = Class.create();
Image.Thumbnail.prototype = {
  initialize: function(img, input, options) {
    this.setOptions(options);

    var img = $(img);
    this.img = img;
    this._saveImageInfo();

    var input = $(input);
    this.input = input;
    Event.observe(input, 'change', this.show.bind(this))
  },

  setOptions: function(options) {
    this.options = {
      suffixes: {
        gif: true,
        jpeg: true,
        jpg: true,
        png: true
      }
    }
    Object.extend(this.options, options || {});
  },

  _saveImageInfo: function() {
    var img = this.img;
    if (!img.width) {
      setTimeout((function(){this._saveImageInfo()}).bind(this), 1000);
      return;
    }
    var img_org = document.createElement('img');
    this.img_org = img_org;
    img_org.src = img.src;
    img_org.width = img.width;
    img_org.height = img.height;
  },

  show: function() {
    var filename = this.input.value;
    if (!this.isValidSuffix(filename)) {
      this.showOriginal();
      return false;
    }

    var img_tmp = document.createElement('img');
    filename = filename.replace(/\\/g, '/');
    img_tmp.src = 'file:///'+filename;
    this.img_tmp = img_tmp;
    Event.observe(img_tmp, 'load', this._show.bind(this))
  },

  _show: function() {
    var img = this.img;
    var img_tmp = this.img_tmp;
    var max_length = this.img_org.width;
    var ox = img_tmp.width;
    var oy = img_tmp.height;

    if ((img_tmp.width >= img_tmp.height) && (ox > max_length)) {
      ox = max_length;
      oy = img_tmp.height * max_length / img_tmp.width;
    } else if (img_tmp.height > max_length) {
      ox = img_tmp.width * max_length / img_tmp.height;
      oy = max_length;
    }

    img.src = img_tmp.src;
    img.width = ox;
    img.height = oy;
  },

  isValidSuffix: function(filename) {
    filename.match(/\.([^.]*)$/);
    return this.options.suffixes[RegExp.$1];
  },

  showOriginal: function() {
    var img = this.img;
    var img_org = this.img_org;
    img.src = img_org.src;
    img.width = img_org.width;
    img.height = img_org.height;
  }
}
