// ==UserScript==
// @name           Name2Face
// @namespace      http://ejohn.org/
// @description    Attach an icon representation of a friend to their name (or nickname).
// @include        *
// ==/UserScript==

(function() {
  var mapping = {
    "http://ejohn.org/images/icon.jpg": [
      "john resig", "phytar", "jeresig"
    ],
    "http://ejohn.org/images/icons/brock.gif": [
      "randy boland", "boland", "brock"
    ],
    "http://ejohn.org/images/icons/darrin.gif": [
      "darrin"
    ],
    "http://ejohn.org/images/icons/dinomite.gif": [
      "dinomite", "drew stephens"
    ]
  };
  
  var userOnce = false;
  var elemOnce = true;
  
  var doneUser = new Array();
  var doneElm = new Array();
  
  for ( var url in mapping ) {
    var icon = document.createElement( "img" );
    icon.src = url;
    icon.style.border = "0px";
    icon.style.height = "2em";
    icon.style.verticalAlign = "middle";
    icon.style.marginLeft = "4px";
    icon.style.marginRight = "4px";
    
    for ( var name in mapping[url] ) {
      var l = document.evaluate(
        "//body//*[contains(translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), '" + mapping[url][name] + "')]", 
        document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
        
      for ( var i = 0; elm = l.snapshotItem(i); i++ ) {
        if ( !userOnce || doneUser[ url ] == null ) {
          if ( !elemOnce || doneElm[ elm ] == null ) {
            elm.insertBefore( icon.cloneNode(true), elm.firstChild );
            doneElm[ elm ] = true;
          }
          doneUser[ url ] = true;
        }
      }
    }
  }
})();

