// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.

if(typeof hilite_tag == "undefined") var hilite_tag = "EM";

var hilite_skip = new RegExp('^(?:' + hilite_tag + '|SCRIPT|FORM|SPAN)$');
var hilite_colors = ['#ff6', '#a0ffff', '#9f9', '#f99', '#f6f'];
var hilite_word = [];
var hilite_idx = 0;

function highlightWords(node)
{
  if(!node || !hilite) return;
  if(hilite_skip.test(node.nodeName)) return;
  if(node.hasChildNodes())
    for(var i=0; i < node.childNodes.length; i++)
      highlightWords(node.childNodes[i]);
  if(node.nodeType == 3) { // NODE_TEXT
    if((nv = node.nodeValue) && (regs = hilite.exec(nv))) {
      if(!hilite_word[regs[0].toLowerCase()]) {
        hilite_word[regs[0].toLowerCase()] = hilite_colors[hilite_idx++ % hilite_colors.length];
      }
      var match = document.createElement(hilite_tag);
      match.appendChild(document.createTextNode(regs[0]));
      match.style.backgroundColor = hilite_word[regs[0].toLowerCase()];
      match.style.fontStyle = 'inherit';
      match.style.color = '#000';
      var after = node.splitText(regs.index);
      after.nodeValue = after.nodeValue.substring(regs[0].length);
      node.parentNode.insertBefore(match, after);
    }
  }
}

// display link after first H1 that removes highlighted tags from page
function insertRemoveLink()
{
  var targetNode = document.getElementsByTagName('h1')[0];
  var el = document.createElement('p');
  el.id = 'remove_link';
  el.className = 'noprint';
  el.style.fontSize = '10px';
  targetNode.parentNode.insertBefore(el, targetNode.nextSibling);
  el.appendChild(document.createTextNode(hilite.toString().replace(/^\/\\b\(|\)\\b\/i$/g, "").replace(/\|/g, " ")));
  el.innerHTML = '<b>Highlighted terms</b>: ' + el.innerHTML.replace(/\\'/, "'") + ' | <a href="?nohilite" onclick="removeHighlight(); return false;">remove</a>';
}

// remove highlighted tags from html
function removeHighlight()
{
  var arr = document.getElementsByTagName(hilite_tag);
  while(arr.length && (el = arr[0])) {
    el.parentNode.replaceChild(el.firstChild, el);
  }
  document.getElementById('remove_link').style.display = 'none';
}

function searchHighlight()
{
  if(!hilite_id) return;
  if(navigator.userAgent.indexOf("Mac_PowerPC") != -1) return;
  if(!document.createElement) return;
  if(firstNode = document.getElementById(hilite_id)) {
    insertRemoveLink();
    highlightWords(firstNode);
  }
}

if(typeof window.onload != 'function') {
  window.onload = searchHighlight;
} else {
  var hilite_oldonload = window.onload;
  window.onload = function() {
    hilite_oldonload();
    searchHighlight();
  }
}

