//-----------------------------------------------------------------------------
// sortTable(id, col, rev)
//
//  id  - ID of the TABLE, TBODY, THEAD or TFOOT element to be sorted.
//  col - Index of the column to sort, 0 = first column, 1 = second column,
//        etc.
//  rev - If true, the column is sorted in reverse (descending) order
//        initially.
//
// Note: the team name column (index 1) is used as a secondary sort column and
// always sorted in ascending order.
//-----------------------------------------------------------------------------

function sortTable(id, col, attr_name, rev, ignore_last, anchor) {

  // Get the table or table section to sort.
  var tblEl = document.getElementById(id);

  var rows = $("tr", tblEl);
  rows.removeClass('row_0');

  // we use this in place of tblEl, as some browsers seem to add a
  // TBODY which messes things up

  var row_par = rows[0].parentNode;

  // The first time this function is called for a given table, set up an
  // array of reverse sort flags.
  if (tblEl.reverseSort == null) {
    tblEl.reverseSort = new Array();
    // Also, assume the start date column is initially sorted.
    tblEl.lastColumn = 1;
  }

  // If this column has not been sorted before, set the initial sort direction.
  if (tblEl.reverseSort[col] == null)
    tblEl.reverseSort[col] = rev;

  // If this column was the last one sorted, reverse its sort direction.
  if (col == tblEl.lastColumn && !ignore_last)
    tblEl.reverseSort[col] = !tblEl.reverseSort[col];

  // Remember this column as the last one sorted.
  tblEl.lastColumn = col;

  // Set the table display style to "none" - necessary for Netscape 6 
  // browsers.
  var oldDsply = tblEl.style.display;
  tblEl.style.display = "none";

  // Sort the rows based on the content of the specified column using a
  // selection sort.

  var tmpEl;
  var i, j;
  var minVal, minIdx;
  var testVal;
  var cmp;
  var parent;

  // need to incr indexes i and j by two each time as
  // we are dealing with the rows in pairs. We only check the
  // values od the attributes on the top one of each pair

  for (i = 1; i < row_par.rows.length-3; i+=2) {
    // Assume the current row has the minimum value.
    minIdx = i;
    minVal = $(row_par.rows[i].cells[col]).attr(attr_name);

    // Search the rows that follow the current one for a smaller value.
    for (j = i + 2; j < row_par.rows.length; j+=2) {
    testVal = $(row_par.rows[j].cells[col]).attr(attr_name);
      	cmp = compareValues(minVal, testVal);

      // Negate the comparison result if the reverse sort flag is set.
      if (tblEl.reverseSort[col])
      cmp = -cmp;
      // Sort by the row disp_idx if they are equal
      if (cmp == 0 && col != 1)
      cmp = compareValues($(row_par.rows[minIdx]).attr('disp_idx'),
      $(row_par.rows[j]).attr('disp_idx'));
      // If this row has a smaller value than the current minimum, remember its
      // position and update the current minimum value.
      if (cmp > 0) {
        minIdx = j;
        minVal = testVal;
      }
    }
    
    // By now, we have the rows with the smallest value. Remove them
    // from the table and insert them before the current row.
    if (minIdx > i) {
      tmpEl = row_par.removeChild(row_par.rows[minIdx]);
      row_par.insertBefore(tmpEl, row_par.rows[i]);
      tmpEl = row_par.removeChild(row_par.rows[minIdx+1]);
      row_par.insertBefore(tmpEl, row_par.rows[i+1]);
    }
  }
  
  // Make the nice blue and white stripes come back
  Tennis.matches.restripeTable(tblEl)

  // Restore the table's display style.
  tblEl.style.display = oldDsply;
  
  // Display the correct triangle image.
  switchTriangle(anchor, tblEl.reverseSort[col]);
  
  return false;
}

//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------

// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
  document.ELEMENT_NODE = 1;
  document.TEXT_NODE = 3;
}

function getTextValue(el) {
  var i;
  var s;
  
  // Find and concatenate the values of all text nodes contained within the
  // element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

function compareValues(v1, v2) {
  var f1, f2;
  
  // If the values are numeric, convert them to floats.
  
  f1 = parseFloat(v1);
  f2 = parseFloat(v2);
  if (!isNaN(f1) && !isNaN(f2)) {
    v1 = f1;
    v2 = f2;
  }
  
  // Compare the two values.
  if (v1 == v2)
    return 0;
  if (v1 > v2)
    return 1
  return -1;
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s) {

  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.

  return s;
}

// Function to display the correct triangle image.
function switchTriangle(anchor, triangleUp) {
  var allTriangles   = $("table#upcoming_matches img.triangle"),
      rightTriangles = $("table#upcoming_matches img.right_triangle");
  
  allTriangles.hide();
  rightTriangles.show();
  
  $(anchor).find("img.right_triangle").hide();
  
  if (triangleUp) {
    $( $(anchor).find("img.triangle")[0] ).show();
  } else {
    $( $(anchor).find("img.triangle")[1] ).show();
  }
}
