// Our container object
var FanHandler = new Object();

// Initialise the fans, this means attaching mouseover events to each
FanHandler.init = function(container, id_first) {
  FanHandler.container = document.getElementById(container);
  elements = FanHandler.container.getElementsByTagName('area');
  for (var i = 0; i < elements.length; i++) {
    elements[i].onmouseover = function() {
      FanHandler.show(this.id);
    }
  }
  FanHandler.show(id_first);
}

// Make the chosen fan appear on top, and redo the z-index stacking order
FanHandler.show = function(id_first) {
  id_first = id_first.split('_')[1];
  // Store the current children
  elements = FanHandler.container.getElementsByTagName('area');
  children = new Array();
  for (var i = 0; i < elements.length; i++) {
    children.push(elements[i]);
  }
  child_storage = new Array();

  // Save the desired child first
  for (var i = 0; i < children.length; i++) {
    id = children[i].id.split('_')[1];
    if (id == id_first) {
      child_storage.push(children[i]);
    }
  }
  // Now save the rest, and remove them from the DOM
  for (var i = 0; i < children.length; i++) {
    id = children[i].id.split('_')[1];
    if (id != id_first) {
      child_storage.push(children[i]);
    }
    FanHandler.container.removeChild(children[i]);
  }

  // Put them all back in their new order
  for (var i = 0; i < child_storage.length; i++) {
    // Set the stacking order
    target = 'fan_' + child_storage[i].id.split('_')[1];
    document.getElementById(target).style.zIndex = child_storage.length - i;
    FanHandler.container.appendChild(child_storage[i]);
  }

  var wide_path = '/furniture/fans/wide/';
  var wide_container = document.getElementById('banner');
  chosen = document.getElementById('fan_' + child_storage[0].id.split('_')[1])
  img_src = chosen.getElementsByTagName('img')[0].src;
  img_file = img_src.split('/').pop();
  wide_container.src = wide_path + img_file;
}