// Add a function to be called onLoad.
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function hasClass(obj) {
  var result = false;
  if (obj.getAttributeNode("class") != null) {
    result = obj.getAttributeNode("class").value;
  }
  return result;
}

// Return an array of matching elements that are immediate children
function getChildElementsByTagName(element, tagName) {
  tagName = tagName.toLowerCase();
  var childElements = new Array();
  for (var n = 0; n < element.childNodes.length; ++n) {
    var node = element.childNodes[n];
    if (node.nodeType == 1 &&
        node.tagName.toLowerCase() == tagName) {
      childElements = childElements.concat(node);
    }
  }
  return childElements;
}

function addStripes(table) {
  // the flag we'll use to keep track of 
  // whether the current row is odd or even
  var even = false;
  
  // if arguments are provided to specify the colours
  // of the even & odd rows, then use the them;
  // otherwise use the following defaults:
  var evenClass = arguments[1] ? arguments[1] : "even-row";
  var oddClass = arguments[2] ? arguments[2] : "odd-row";
    
  // by definition, tables can have more than one tbody
  // element, so we'll have to get the list of child
  // &lt;tbody&gt;s. This works even if the page author
  // didn't include an explicit tbody tag. Restricting
  // to immediate children avoids problems with nested
  // tables.
  var tbodies = getChildElementsByTagName(table, "tbody");

  // and iterate through them...
  for (var h = 0; h < tbodies.length; h++) {
    // find all the tr elements...
    var trs = getChildElementsByTagName(tbodies[h], "tr");
    
    // ... and iterate through them
    for (var i = 0; i < trs.length; i++) {
      // Put the new class in front so it will be overridden
      // by any pre-existing class
      trs[i].className = (even ? evenClass : oddClass) + " " +
                         trs[i].className;
      
      // flip from odd to even, or vice-versa
      even = ! even;
    }
  }
}

// Stripe tables with the "striped-table" class
addLoadEvent(function() {
  var tables = document.getElementsByTagName("table");
  for (var t = 0; t < tables.length; ++t) {
    var table = tables[t];
    var tableClass = hasClass(table);
    if (tableClass && tableClass.indexOf("striped-table") >= 0) {
      addStripes(table);
    }
  }
});
