document.observe('dom:loaded', function() {
  $$('li.post').each(function(post) {
    var links = post.getElementsBySelector('.post-body a[@href]');
    if (0 == links.length)
      return;

    // insert <h3>Links</h3><ol></ol>
    var linkdiv = post.down('.post-links');
    var heading = new Element('h3').update('Links');
    linkdiv.appendChild(heading);
    var list = new Element('ol');
    linkdiv.appendChild(list);

    links.each(function(link) {
      // insert <li><q>{text}</q><span class="title">{title}</span><span class="url">{href}</span></li>
      var item = new Element('li');
      var text = new Element('q');
      // TODO: Use renameNode for this, when it's implemented.
      //text = link.cloneNode(true);
      //document.renameNode(text, '', 'q');
      $A(link.childNodes).invoke('cloneNode', true).each(function(item) {
        text.appendChild(item);
      });
      item.appendChild(text);
      if (link.hasAttribute('title')) {
        var title = new Element('span', {className: 'title'}).update(link.getAttribute('title'));
        item.appendChild(title);
      }
      // insert optional spaces before the slashes to allow better line wrapping
      var url = link.getAttribute('href').replace(/([^/])\/([^/])/g, '$1\u200b/$2');
      var href = new Element('span', {className: 'url'}).update(url);
      item.appendChild(href);
      list.appendChild(item);
    });
  });
});
