//
// Swap images on mouseover
//
// Usage:
//
// Put "link_button_preload()" into the onload attrib of your body tag:
// <body onload="link_button_preload();" ...>
//
// Any button image called "button-something.ext" will be swapped with
// "button-something-over.ext" and "button-something-down.ext":
//   <a href="..."><img src="/some/where/button-xy.png"></a>
//
//

var mousedownimages = new Array();

function link_button_mouseout() {
  if (typeof(this.linkimages) != "undefined") {
    for (var img in this.linkimages) {
      if (this.linkimages[img].img != mousedownimages[img]) this.linkimages[img].src = this.linkimages[img].outsrc;
    }
  } else {
    if (this.img != mousedownimages[0]) this.img.src = this.img.outsrc;
  }
}

function link_button_mouseover() {
  if (typeof(this.linkimages) != "undefined") {
    for (var img in this.linkimages) {
      if (this.linkimages[img].img != mousedownimages[img]) this.linkimages[img].src = this.linkimages[img].oversrc;
    }
  } else {
    if (this.img != mousedownimages[0]) this.img.src = this.img.oversrc;
  }
}

function link_button_mousedown() {
  for (var img in mousedownimages) {
    mousedownimages[img].src = mousedownimages[img].outsrc;
  }

  if (typeof(this.linkimages) != "undefined") {
    for (var img in this.linkimages) {
      this.linkimages[img].src = this.linkimages[img].downsrc;
    }
    mousedownimages = this.linkimages;
  } else {
    this.img.src = this.img.downsrc;
    mousedownimages = new Array();
    mousedownimages[0] = this.img;
  }
}

function link_button_preload() {
  var res = "";
  var rx = /^(.*\/button-[^\/.]*)(\.[a-z0-9_-]+)$/i;
  for (var i = 0; document.images[i]; i++) {
    if (!rx.test(document.images[i].src)) continue;
    var img = document.images[i];
    var name = RegExp.$1;
    var ext = RegExp.$2;
    preload_image(name+ext);
    preload_image(name+"-over"+ext);
    preload_image(name+"-down"+ext);

    img.img = img;
    var anchor;
    if (img.parentNode) {
      anchor = img;
      while ((!anchor.tagName || anchor.tagName.toLowerCase() != "a") && anchor.parentNode) anchor = anchor.parentNode;
    } else if (srcElement.parentElement) {
      anchor = img;
      while ((!anchor.tagName || anchor.tagName.toLowerCase() != "a") && anchor.parentElement) anchor = anchor.parentElement;
    }
    if (anchor && anchor.tagName.toLowerCase() == "a") {
      if (typeof(anchor.linkimages) == "undefined") {
        anchor.onmouseover = link_button_mouseover;
        anchor.onmouseout = link_button_mouseout;
        anchor.onclick = link_button_mousedown;
        anchor.linkimages = new Array();
      }
      anchor.images[anchor.images.length] = img;
    } else {
      img.onmouseover = link_button_mouseover;
      img.onmouseout = link_button_mouseout;
      img.onclick = link_button_mousedown;
    }
    img.outsrc = name+ext;
    img.oversrc = name+"-over"+ext;
    img.downsrc = name+"-down"+ext;
  }
}

