/**
 * Toggle Background Script
 * Copyright Hugo Hudson, 2006
 *
 * Usage:
 *
 * Include this file in your page by placing the following code in the page
 * header (between the <head> and </head> tags):
 * <script type="text/javascript" src="toggle.js"></script>
 *
 * Then add the class 'toggle' to any element on your page with a background
 * image (as defined by the css stylesheet property background-image).
 *
 * Whenever the user passes his mouse over the element, the background image
 * will change, and then change back when the mouse leaves the element.  The
 * background image for the toggled image is given by adding '-toggle' to the
 * filename, for example 'test.png' becomes 'test-toggle.png'.
 */

// run the setup method after the page loads
addEvent(window, 'load', setMouseToggle);
// a cache for preloading images, for faster mouse-overs and things like that
preloadedToggleImages = new Array();

/*
 * This function finds all objects with the class 'toggle', then tells them
 * that on mouseOver their background image should swap to be the same as the
 * current image name, but with '-toggle' at the end of the filename.
 */
function setMouseToggle() {
  var elements = byclass('toggle');
  for (var i=0; i<elements.length; i++) {
    var e = elements[i];
    // get the background image filename
    var normalBgImage = getStyle(e).backgroundImage;
    var regexp = /^url\("?(.*?)"?\)$/;
    // from the filename, insert the string '-toggle'
    var filename = normalBgImage.replace(regexp,'$1');
    var regexp = /^(.*)(\.(png|jpg|jpeg|gif))$/;
    var toggleFilename = filename.replace(regexp,'$1-toggle$2');
    // preload the images
    var preload_original = new Image();
    var preload_toggle = new Image();
    preload_original.src = filename;
    preload_toggle.src = toggleFilename;
    preloadedToggleImages.push(preload_original);
    preloadedToggleImages.push(preload_toggle);
    // set a couple of new properties for the toggle methods
    e.filenameOriginal = 'url('+filename+')';
    e.filenameToggled = 'url('+toggleFilename+')';
    // setup the onmouse commands
    e.onmouseover = mouseToggleChange;
    e.onmouseout = mouseToggleReset;
  }
}
function mouseToggleChange(e) {
  if (typeof e == 'undefined') var e = window.event;
  var src = (e.target ? e.target : e.srcElement);
  src.style.backgroundImage = src.filenameToggled;
}
function mouseToggleReset(e) {
  if (typeof e == 'undefined') var e = window.event;
  var src = (e.target ? e.target : e.srcElement);
  src.style.backgroundImage = src.filenameOriginal;
}
