// This script has been adapted from:
//   http://alistapart.com/articles/zebratables
// Thanks to David F. Miller for this idea!

// this function is need to work around
// a bug in IE related to element attributes
function hasClass(obj) {
  var result = false;
  if (obj.getAttributeNode("class") != null) {
    result = obj.getAttributeNode("class").value;
  }
  return result;
}

function stripe(className) {
  // if argument is provided to specify the default color
  // of the even rows, then use it; otherwise use white:
  var defaultColor = arguments[1] ? arguments[1] : "#fff";

  var blueColor = "#bdf";
  var zero = parseInt("0", 16);
  var stripeDistance = 1;

  // stripe all tables of the given class
  var tables = document.getElementsByTagName("table");
  for (var t = 0; t < tables.length; t++) {
    if (hasClass(tables[t]) != className) { continue; }

    // the flag we'll use to keep track of
    // whether the current row is odd or even
    var even = false;

    // whether the previous entry was blue
    var lastBlue = true;

    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // tbody elements
    var tbodies = tables[t].getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {

      // find all the tr elements...
      var trs = tbodies[h].getElementsByTagName("tr");

      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {
        var mytr = trs[i];

        var trClass = hasClass(mytr);
        var blue = trClass && trClass.indexOf("blue") >= 0;
        var sameColor = (lastBlue && blue) || (!lastBlue && !blue);
        even = sameColor ? !even : true;

        var evenColor, oddColor;

        // get all the cells in this row...
        var tds = mytr.getElementsByTagName("td");

        if (tds.length > 0) {
          // assign a number to the first item
          tds[0].innerHTML = "" + (i + 1) + ".";
          tds[0].align = "right";

          // compute even/odd color scheme for this row
          evenColor = blue ? blueColor : tds[0].style.backgroundColor;
          if (!evenColor) { evenColor = defaultColor; }
          oddColor = "#";
          for (var c = 1; c < evenColor.length; c++) {
            var ch = parseInt(evenColor.charAt(c), 16);
            ch -= stripeDistance;
            if (ch < zero) { ch = zero; }
            oddColor += ch.toString(16);
          }
        }

        // and iterate through them...
        for (var j = 0; j < tds.length; j++) {
          tds[j].style.backgroundColor = even ? evenColor : oddColor;
        }

        // flip from odd to even, or vice versa
        lastBlue = blue;
      }
    }
  }
}
