(function() {
  
  function getInnerText(element) {
    element = $(element);
    return element.innerText && !window.opera ? element.innerText
      : element.innerHTML.stripScripts().unescapeHTML().replace(/[\n\r\s]+/g, ' ');
  }
  
  // FIXME: I needed to add a fancy apostrophe to this character class
  // in order to get it to treat a possessive apostrophe-s as part of a word.
  // Other characters might need this treatment as well.
  var WORD = /[\w\u2019']+/g
  
  
  function makeSmallCaps(post) {
    var p = $(post).down('p');
    if (!p) return;
    
    var html = p.innerHTML;
    var text = getInnerText(p), matches = (text.match(WORD) || []).slice(0, 3);
        
    html += "<" // help out the regex
    matches.each( function(match) {
      // Strip trailing punctuation from the match. Interferes with word
      // boundary in regexp.
      match = match.replace(/[\u2019']$/, '');
      
      var re = new RegExp("(\\b" + RegExp.escape(match) + "\\b)(?=[^>]*?<)", 'm');
      html = html.sub(re, "<span class='smallcaps'>#{0}</span>");
    });
    
    html = html.strip().gsub(/<$/, '');
    p.update(html);
  }
  
  
  function hasCalibri() {
    var b = document.body, d = new Element('div'), s = new Element('span');
    
    d.appendChild(s);
    
    d.style.fontFamily = s.style.fontFamily = "monospace";
    s.style.fontSize = '72px';
    
    s.innerHTML = "ml";
    
    d.setStyle({
      visibility: 'hidden',
      position: 'absolute',
      left: '-9999px'
    });
    
    b.appendChild(d);
    var defaultWidth = s.offsetWidth;    
    s.style.fontFamily = "Calibri, monospace";    
    var hasCalibri = s.offsetWidth !== defaultWidth;


    b.removeChild(d);
    
    d = s = null;
    return hasCalibri;
  }
  
  function addEndSign(post) {
    var lastParagraph = post.select('p').last();    
    var endSign = new Element('span', { 'class': 'end-sign' }).update("&nbsp;");
    lastParagraph.insert({ bottom: endSign });
  }  
  
  function init() {
    // Put the first three words of each post in smallcaps.    
    $$("div.post-body").each(makeSmallCaps);
    
    // Add the "end sign" arrow to each DIV.
    $$('div.article div.post-body').each(addEndSign);
    
    if (!hasCalibri()) {
      $(document.body).addClassName('no-calibri');
    }
  }
  
  document.observe("dom:loaded", init);
})();