var image = document.getElementById('item');
var thumbs = document.getElementById('menu');
var caption = document.getElementById('caption');

function parse_xhtml(text) {
  var tag_regex = /<(\/?)([a-z]+)((?:\s+[a-z]+=".*?")*)\s*(\/?)>/g;
  var attr_regex = /([a-z]+)="(.*?)"/g;
  var ns = 'http://www.w3.org/1999/xhtml';
  var createElement;

  if(document.createElementNS) {
    createElement = function(tag) {
      return document.createElementNS(ns, tag);
    }
  } else {
    createElement = document.createElement;
  }

  var node = createElement('p');
  var pos = 0;
  var match, attr;
  while(match = tag_regex.exec(text)) {
    if(match.index > pos) {
      var substr = text.substring(pos, match.index);
      node.appendChild(document.createTextNode(substr));
    }

    pos = tag_regex.lastIndex;

    if(match[1]) {
      node = node.parentNode;
      continue;
    }

    node = node.appendChild(createElement(match[2]));

    if(match[3])
      while(attr = attr_regex.exec(match[3]))
	node.setAttributeNS(ns, attr[1], attr[2]);

    if(match[4])
      node = node.parentNode;
  }
  if(pos < text.length-1)
    node.appendChild(document.createTextNode(text.substr(pos)));

  return node;
}

function image_uri(key) {
  return 'images/' + key.substr(key.lastIndexOf('/') + 1) + '.jpg';
}

function tag_of(node) {
  if(node && node.nodeName)
    return node.nodeName.toLowerCase();
  else
    return false;
}

function find(tag, node) {
  while(tag_of(node) != tag)
    node = node.nextSibling;

  return node;
}

function get() {
  image.src = image_uri(this.href);
  image.alt = this.title;
  if(caption)
    caption.replaceChild(this.caption, caption.firstChild);

  return false;
}

for(var i in thumbs.childNodes) {
  var li = thumbs.childNodes[i];
  if(tag_of(li) != 'li')
    continue;

  var a = find('a', li.firstChild);
  a.onclick = get;
  (new Image()).src = image_uri(a.href);

  if(caption)
    a.caption = parse_xhtml(a.caption);
}
