/**
 * StandardTable.js
 * Creates a standard table singleton to use as an interface to standard tables
 * within Webview
 */

// Create as a singleton
var StandardTable = (function(){
  var stdtbl = {
    // CONSTANTS
    CLASS_EVEN     : "StdTblRowEven",
    CLASS_ODD      : "StdTblRowOdd",
    /**
     * DeleteRow
     * Delete a row from a standard table
     * object                DOM Node : any DOM node within the table
     */
    DeleteRow : function(row){
      row = this.getValidRow(row);     // Make sure we have a valid row
      if(!row){ return; }              // Early return
      // We'll make an array to make class assignment easier
      var classArr = new Array;
      if(row.className == this.CLASS_EVEN){
        classArr.push(this.CLASS_EVEN);
        classArr.push(this.CLASS_ODD);
      }else{
        classArr.push(this.CLASS_ODD);
        classArr.push(this.CLASS_EVEN);
      }
      // Now we can adjust all of the classes in the following rows
      var count = 0;
      for(var n = row.nextSibling; n != null; n = n.nextSibling){
        if( !this.isValidRow(n) ){
          continue;                    // Skip this node
        }
        n.className = classArr[count++ % 2];     // Assign new class
      }
      // Now we can delete the row
      row.parentNode.removeChild(row);
    },

    /**
     * getValidRow
     * If the node is not a valid row, search up until we find one or run out
     * of nodes. Return the node on success, false on failure
     * object                DOM Node : the node to check
     */
    getValidRow : function(el){
      if(this.isValidRow(el)){
        return el;                     // We're done
      }
      for(var n = el.parentNode; n != null; n = n.parentNode){
        if(this.isValidRow(n)){
          break;                       // Found it
        }
      }
      return n;
    },

    /**
     * isValidRow
     * Return true if the node is a valid row from a standard table, false
     * otherwise
     * object                DOM Node : the row to check
     */
    isValidRow : function(el){
      return el.nodeType == 1 /*HTML Node*/ &&
             el.tagName.toLowerCase() == "tr" &&
             (
               el.className == this.CLASS_EVEN ||
               el.className == this.CLASS_ODD
             );
    }
  };

  return stdtbl;
})();