var imageCache;     // caches the images themselves
var imageSrcNames;  // caches the src value of the images. this is needed because of relative urls
var debug = false;

// swaps an image's source with the provided source
function swapImage(img, src) {
  if (window.preloadImages != null) preloadImages();
  doSwapImage(img, src);
}

// swaps an image's source with the provided source. if multiple images with the same name exist, swaps all of them
function doSwapImage(img, src) {
  myImage = findImage(src);
  if (img[0] == null) {
    if (myImage != null) {
      if (debug) {alert('Swapping cached image '+myImage);}
      img.src = myImage.src;
    } else {
      img.src = src;
    }
  } else {
    for (i=0; i<img.length; i++) {  //>
    if (myImage != null) {
      if (debug) {alert('Swapping cached image '+myImage);}
      img[i].src = myImage.src;
    } else {
      img[i].src = src;
    }
    }
  }
}

// actually performs the preload. send a list of args in the form of
// a series of image src URL strings.
function doPreloadImages() {
  args = doPreloadImages.arguments;
  imageCache = new Array(args.length);
  imageSrcNames = new Array(args.length);

  if (args != null) {
      for (i=0; i<args.length; i++) {   //>
        if (args[i].indexOf("#") != 0) {
          imageCache[i] = new Image;
          imageCache[i].src = args[i];
          imageSrcNames[i] = args[i];
        }
      }
  }
}

// finds image in cache, based on src
function findImage(src) {
  if (imageSrcNames != null) {
      for (i=0; i<imageSrcNames.length; i++) {  //>
        if (imageSrcNames[i] != null) {        
          // if (debug) {alert(i+": checking "+imageSrcNames[i]+" AGAINST "+src);}
          if (imageSrcNames[i] == src) {
            return imageCache[i];
          }
        }
      }
  }
  return null;
}

