/* Set the "target" attribute of all external hyperlinks to _blank,
 * so they open new tabs.  Sadly, XHTML doesn't support target="_blank".
 */

function externalLinks() {
   if (!document.getElementsByTagName) {
        return;
   }
   var anchors = document.getElementsByTagName("a");
   for (var i=0; i<anchors.length; i++) {
       var anchor = anchors[i];
       if (anchor.getAttribute("href") &&
           /external/.test(anchor.getAttribute("rel"))) {
           // This is getting phased out:
           anchor.target = "_blank";
       }
   }
}

window.onload = externalLinks;

var createElement = function(x) {
    if (navigator.userAgent.search("MSIE") >= 0) {
        return document.createElement(x);
    } else {
        return document.createElementNS('http://www.w3.org/1999/xhtml', x);
    }
};

var entities = {};
// Using entities.amp is equivalent to entities["amp"] and appeases JSLint.
entities.amp = '\u0026';
entities.lt = '\u003c';
entities.gt = '\u003e';
entities.quot = '\u0022';
entities.lsquo = '\u2018';
entities.rsquo = '\u2019';
entities.ldquo = '\u201c';
entities.rdquo = '\u201d';
entities.ndash = '\u2013';
entities.mdash = '\u2014';
entities["#39"] = "'";
entities["#039"] = "'";

var convertText = function(text) {
    if (text == null || text == "") {
	return "";
    }
    var matches = text.match(/&[^;]+;|[^&]+/g);
    var result = "";
    for (var i = 0; i < matches.length; ++i) {
        var name = matches[i].match(/^&([^;]+);$/);
        if (name) {
            // document.createEntityReference returns null on Firefox and
            // throws an error on IE.
            var entity = entities[name[1]];
            if (entity === undefined) {
                entity = name[0];
            }
	    result += entity;
        } else {
	    result += matches[i];
        }
    }
    return result;
};

var appendText = function(node, text) {
    // Previously tried mixing document.createTextNode() and
    // document.createEntityReference(), but the latter returns null
    // on Firefox and throws an error on IE.
    node.appendChild(document.createTextNode(convertText(text)));
};
