// Replace keywords with span tags around those keywords to enable
// highlighting. Highlighted with base class of "keywordhl".
// Each match is also given a second class of "keywordhl#" where "#"
// is the number of the keyword match. This allows you to assign
// different colours (for example) to the different keywords.

var elList;

function recDescent(el) {
  for(var i=0; i<el.childNodes.length; i++) {
    var n = el.childNodes[i];
    if(n.nodeType == 1 && n.nodeName != 'TH') {
      recDescent(n);
      elList.push(n);
    }
  }

  elList.push(el);
}

Event.observe(window, 'load', function() {
  if(!keywords || !keywords.length)
     return;
  $$('.search_results_dataset td').each(function(res) {
    elList = new Array();
    elList.push(res);

    if(res.childNodes.length) {
      startPoint = res;
      recDescent(res);
    }

    var keywordpat = new RegExp('(.*)(' + keywords.join('|') + ')(.*)', 'i');
    var keywordhash = new Hash();
    for(var i=0; i<keywords.length; i++) {
      keywordhash.set(keywords[i], i+1);
    }


    elList.each(function(el){
      for(var i=0; i<el.childNodes.length; i++) {
        var cEl = el.childNodes[i];

        if(cEl.nodeType != 3)
          continue;

        var match = cEl.nodeValue.match(keywordpat);

        if(!match || !match.length)
          continue;

        // "it", the match:
        if(match[2]) {
          var kw = 'keywordhl keywordhl' + keywordhash.get(match[2]);
          var span = new Element('span', {className: kw}).update(match[2]);

          // The order is "reversed" because we're inserting into the middle of
          // an array always inserting after the same point.
          // E.g. inserting after B by inserting c, b, then a:
          // A B C D =>   A B c C D =>  A B b c C D => A B a b c C D
          if(match[3])
            Element.insert(el.childNodes[i], {after: match[3]});

          Element.insert(el.childNodes[i], {after: span});

          if(match[1])
            Element.insert(el.childNodes[i], {after: match[1]});

          Element.remove(el.childNodes[i]);
        }

        // before
/*
        if(match[1]) {
          Element.insert(el.childNodes[i], {before: match[1] });
          i++; // Added extra element, so bump iterator on by one.
        }
*/

      }

    })
  });
});

