
var resizeDelay = 10;

var resizeIncrement = 1;

var imgCache = new Object();

function getCacheTag (imgElement) {
   return imgElement.src + "~" + imgElement.offsetLeft + "~" + imgElement.offsetTop;
}

function cachedImg (imgElement, increment) {
   this.img = imgElement;
   this.cacheTag = getCacheTag(imgElement);
   this.originalSrc = imgElement.src;

   var h = imgElement.height;
   var w = imgElement.width;
   this.originalHeight = h;
   this.originalWidth = w;

   increment = (!increment) ? resizeIncrement : increment;
   this.heightIncrement = Math.ceil(Math.min(1, (h / w)) * increment);
   this.widthIncrement = Math.ceil(Math.min(1, (w / h)) * increment);
}

function resizeImg (imgElement, percentChange, newImageURL) {

   var pct = (percentChange) ? percentChange / 100 : 1;

   var cacheTag = imgElement.getAttribute("cacheTag");
   if (!cacheTag) {
      cacheTag = getCacheTag(imgElement);
      imgElement.setAttribute("cacheTag", cacheTag);
   }

   var cacheVal = imgCache[cacheTag];
   if (!cacheVal) {
      imgCache[cacheTag] = new Array(new cachedImg(imgElement), pct);
   } else {
      cacheVal[1] = pct;
   }

   if (newImageURL)
      imgElement.src = newImageURL;

   resizeImgLoop(cacheTag);
   return true;
}

function resizeImgLoop (cacheTag) {
   // get information about the image element from the image cache
   var cacheVal = imgCache[cacheTag];
   if (!cacheVal)
      return false;

   var cachedImageObj = cacheVal[0];
   var imgElement = cachedImageObj.img;
   var pct = cacheVal[1];
   var plusMinus = (pct > 1) ? 1 : -1;
   var hinc = plusMinus * cachedImageObj.heightIncrement;
   var vinc = plusMinus * cachedImageObj.widthIncrement;
   var startHeight = cachedImageObj.originalHeight;
   var startWidth = cachedImageObj.originalWidth;

   var currentHeight = imgElement.height;
   var currentWidth = imgElement.width;
   var endHeight = Math.round(startHeight * pct);
   var endWidth = Math.round(startWidth * pct);

   if ( (currentHeight == endHeight) || (currentWidth == endWidth) )
      return true;

   var newHeight = currentHeight + hinc;
   var newWidth = currentWidth + vinc;
   if (pct > 1) {
      if ((newHeight >= endHeight) || (newWidth >= endWidth)) {
         newHeight = endHeight;
         newWidth = endWidth;
      }
   } else {
      if ((newHeight <= endHeight) || (newWidth <= endWidth)) {
         newHeight = endHeight;
         newWidth = endWidth;
      }
   }

   imgElement.height = newHeight;
   imgElement.width = newWidth;

   if ((newHeight == cachedImageObj.originalHeight) || (newWidth == cachedImageObj.originalwidth)) {
      imgElement.src = cachedImageObj.originalSrc;
   }

   setTimeout("resizeImgLoop('" + cacheTag + "')", resizeDelay);
}

