/*
 * $Id: ImTool.js,v 1.2 2002/04/14 18:25:44 christo Exp $
 * Cross Browser Tool for manipulating images by name,
 * features:
 * - transparently deals with the way ns4 moves images objects
 *   into the layers hierarchy if you use <div> or <span> tags
 *   in your document
 * - getImageByName(name)
 *
 * finds images with names in the document and builds a list of references
 * to them. This trivial and pointless in all browsers but netscape 4
 * which does not keep images which exist inside div tags in the 
 * document.images array. These images must be sought in the layers
 * hierarchy, each of which may have a document with an images array.
 * I'm assuming this is a tree or acyclic graph (if not we'll be in an
 * infinite death loop - it wouldn't be the first time)
 * returns an array of Images
 */

/*
   ImTool constructor, make sure the document has fully loaded, or you
   may miss out on some images.
*/
function ImTool() {
   var n;
   this.images = ImTool.getDocumentImages(window.document);
   // build names hash; key clashes will overwrite but we don't care
   // unnamed images will not be added to the hash
   this.namedImages = new Object();
   for (var i=0; i<this.images.length; i++) {
      n = this.images[i].name;
      if (n != null) {
         this.namedImages[n] = this.images[i];
      }
   }
}

/*
 * recursively collect all images in this document and the
 * layers hierarchy under it (if there is such a thing)
 * - this is a class method
 * - it returns an array of Image objects
 */
ImTool.getDocumentImages = 
function(doc) {
   var myImages = new Array();
   for (var i=0; i<doc.images.length; i++) {
      myImages[myImages.length] = doc.images[i];
   }
   // now do all the layers
   if (doc.layers) {
      var aLayersImages = new Array();
      // each layer
      for(var j=0; j<doc.layers.length; j++) {
         // recursive step
         aLayersImages = ImTool.getDocumentImages(doc.layers[j].document);
         for (var k=0; k<aLayersImages.length; k++) {
            myImages[myImages.length] = aLayersImages[k];
         }
      }

   }
   return myImages;
}

/*
 *  returns a string representation of the list of all the images 
 *  this ImTool has found
 */
ImTool.prototype.getImageListAsString = 
function() {
   var str = this.images.length + " images found:\n";
   for (var i=0; i<this.images.length; i++) { 
      if (this.images[i].name) {
         str += this.images[i].name;
      } else {
         str += this.images[i];
      }
      str += "\n";
   }
   return str;
}

/*
 * returns an image object reference if the image exists in
 * the ImTool. If there is more than one image with that 
 * name, one, chosen arbitrarily, will be returned.
 */
ImTool.prototype.getImageByName = 
function(name) { 
   return this.namedImages[name];
}

