
function scaleImage(imgObj, width, height) {
  if(imgObj.height > height || imgObj.width > width) {
    ratio1 = imgObj.width / imgObj.height;
    ratio2 = width / height;
    if(ratio1 > ratio2) {
      imgObj.width  = parseInt(width);
      imgObj.height = parseInt(width / ratio1);  
    } else if(ratio1 < ratio2) {
      imgObj.height = parseInt(height);
      imgObj.width  = parseInt(ratio1 * height);
    } else {
      imgObj.width  = parseInt(width);
      imgObj.height = parseInt(height);
    }
  }
}

function SNImage(index, w, h) {
  this.obj = document.getElementById("img" + index);
  this.width = w;
  this.height = h;
  this.wait = function() {
    if(this.obj.complete && this.obj.height > 0) {
      scaleImage(this.obj, this.width, this.height);
    } else {
      var thisObj = this;
      window.setTimeout( function() { thisObj.wait(); }, 100);
    }
  }
}

function scaleAndDisplay(index, w, h) {
  var img = document.getElementById("img" + index);
  new SNImage(index, w, h).wait();
}
