/*
 * Tiny Image Rotator.
 *
 * This script can be used to change the background image of a given element
 * at a fixed interval.
 *
 * The element should already have background to start with so that
 * users who have switched off JavaScript still can see something.
 * In addition, the background-properties (for position and repeat)
 * should already be set correctly.
 *
 * (c) 2005 Oliver Klee, http://www.oliverklee.de/
 *
 * This script is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * The GNU General Public License can be found at
 * http://www.gnu.org/copyleft/gpl.html.
 */

/** cache the array so that we don't have to serialize it into a string */
var cachedBackgroundsList = null;

/**
 * Stores a list of background image URLs.
 *
 * @param Array   array of URLs of the background images (with complete relative or absolute path)
 * must contain at least 1 element,
 * the first element should be the background already set via CSS
 */
function setBackgrounds(backgrounds) {
  cachedBackgroundsList = backgrounds;

  return;
}

/**
 * Starts the next iteration of rotating through a set of images.
 * Note: Before this function may be called, setBackgrounds must be called!
 *
 * @param String  the ID of the element for which the background image will be changed
 * @param Integer the number of the image to be displayed (0-based), should be 0 on first call
 * @param Integer interval (in ms) in which the background image will be changed
 */
function rotateImages(id, imageToShow, interval) {
  // If our browser doesn't support the necessary DOM stuff, bail out.
  if (!document.getElementById) {
    return;
  }

  // Have we been called before we have any backgrounds to work on? Bail out as well.
  if (!cachedBackgroundsList) {
    return;
  }

  // If everything is OK, show the image.
  var element = document.getElementById(id);
  element.style.backgroundImage = "url(" + cachedBackgroundsList[imageToShow] + ")";

  var nextImage;
  // find a new random image that's not the same as the current one
  do {
    nextImage = Math.round(Math.random() * (cachedBackgroundsList.length - 1));
  } while (nextImage == imageToShow);

  // preload the next image
  var tempImage = new Image();
  tempImage.src = cachedBackgroundsList[nextImage];

  // And now the next one in queue. Everybody only one cross!
  var functionCall = 'rotateImages("' + id + '", ' + nextImage + ', ' + interval + ')';
  setTimeout(functionCall, interval);

  return;
}
