/**
*
*  Sortable HTML table
*  http://www.webtoolkit.info/
*
**/
function demoShowMatchClick() {
  var re = new RegExp(document.demoMatch.regex.value);
  var m = re.exec(document.demoMatch.subject.value);
  if (m == null) {
    alert("No match");
  } else {
    var s = "Match at position " + m.index + ":\n";
    for (i = 0; i < m.length; i++) {
      s = s + m[i] + "\n";
    }
    alert(s);
  }
}

var sortedCell = "";
function SortableTable (tableEl) {
 
	this.tbody = tableEl.getElementsByTagName('tbody');
	this.thead = document.getElementById('myTable1').getElementsByTagName('thead');
	this.tfoot = document.getElementById('myTable2').getElementsByTagName('tfoot');
 
	this.getInnerText = function (el) {
		var price = el.innerHTML.split("$");
		if (price[1])
			return price[1];
		var re = new RegExp("(?=<span\sid='span_sort_title'\sstyle='visibility:hidden;').*(?=</span>)");
  		var m = re.exec(el.innerHTML);
		var span = el.innerHTML.split("<span"); 
		var sortTitle = "";
		sortTitle = ("<" + span[1]).replace(/<[^<>]+>/g,'');
		if (sortTitle != "<undefined")
			return sortTitle;
		else {
			re = new RegExp("(?=<span\sid='span_sort_date'\sstyle='visibility:hidden;').*(?=</span>)");
			m = re.exec(el.innerHTML);
			span = el.innerHTML.split("<span"); 
			var sortDate = "";
			sortDate = ("<" + span[1]).replace(/<[^<>]+>/g,'');
			if (sortDate != "<undefined")
				return sortDate;
		}
		if (typeof(el.textContent) != 'undefined') return el.textContent;
		if (typeof(el.innerText) != 'undefined') return el.innerText;
		if (typeof(el.innerHTML) == 'string') return el.innerHTML.replace(/<[^<>]+>/g,'');
	}
 
	this.getParent = function (el, pTagName) {
		if (el == null) return null;
		else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
			return el;
		else
			return this.getParent(el.parentNode, pTagName);
	}
 
	this.sort = function (cell) {
 
	    var column = cell.cellIndex;
	    var itm = this.getInnerText(this.tbody[0].rows[1].cells[column]);
		var sortfn = this.sortCaseInsensitive;
 
		if (itm.match(/\d\d[-]+\d\d[-]+\d\d\d\d/)) sortfn = this.sortDate; // date format mm-dd-yyyy
		if (itm.replace(/^\s+|\s+$/g,"").match(/^[\d\.]+$/)) sortfn = this.sortNumeric;
 
		this.sortColumnIndex = column;
 
	    var newRows = new Array();
	    for (j = 0; j < this.tbody[0].rows.length; j++) {0
			newRows[j] = this.tbody[0].rows[j];
		}
 
		newRows.sort(sortfn);

		var colorSelect = "#99ff99"; //#00CC00";
		
		
		if (cell.getAttribute("sortdir") == 'down' && sortedCell == cell.className) {
			newRows.reverse();
			cell.setAttribute('sortdir','up');
			cell.style.backgroundColor = colorSelect;
			cell.innerHTML = "<div style='float:left'>" + document.getElementById(cell.className).value + "</div><div style='float:right; padding-right:10px;'><img style='text-align:right;' src='../graphics/arrow_down.gif' /><input type='hidden' id='"+cell.className+"' value='"+document.getElementById(cell.className).value+"' /></div>";
		} else {
			cell.setAttribute('sortdir','down');
			cell.style.backgroundColor = colorSelect;
			cell.innerHTML = "<div style='float:left'>" + document.getElementById(cell.className).value + "</div><div style='float:right; padding-right:10px;'><img src='../graphics/arrow_up.gif' /><input type='hidden' id='"+cell.className+"' value='"+document.getElementById(cell.className).value+"' /></div>";
		}
		sortedCell = cell.className;
		
		for (i=0;i<5;i++){
			if (this.thead[0].rows[0].cells[i] != cell) {
				this.thead[0].rows[0].cells[i].style.backgroundColor = "#E1FFE1"; // #99ff99";
				this.thead[0].rows[0].cells[i].innerHTML = "<div style='float:left'>" + document.getElementById(this.thead[0].rows[0].cells[i].className).value + "</div><div style='float:right; padding-right:10px;'><img style='text-align:right;' src='../graphics/arrow_up_down.gif' /><input type='hidden' id='"+this.thead[0].rows[0].cells[i].className+"' value='"+document.getElementById(this.thead[0].rows[0].cells[i].className).value+"' /></div>";
			}
		}
		
		for (i=0;i<newRows.length;i++) {
			if (i%2 == 0)
				newRows[i].style.backgroundColor = "#FFF";
			else
				newRows[i].style.backgroundColor = "#f9f9f9";//f0f0f0";
			this.tbody[0].appendChild(newRows[i]);
		}
 
	}
 
	this.sortCaseInsensitive = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]).toLowerCase();
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]).toLowerCase();
		
		if (aa.indexOf("evenings") != -1)
			aa = "zz";
		else if (bb.indexOf("evenings") != -1)
			bb = "zz";

		
		if (aa==bb) return 0;
		if (aa<bb) return -1;
		return 1;
	}
 
	this.sortDate = function(a,b) {
		aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]);
		bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]);
		date1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
		date2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
		if (date1==date2) return 0;
		if (date1<date2) return -1;
		return 1;
	}
 
	this.sortNumeric = function(a,b) {
		aa = parseFloat(thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]));
		if (isNaN(aa)) aa = 0;
		bb = parseFloat(thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]));
		if (isNaN(bb)) bb = 0;
		return aa-bb;
	}
 
	// define variables
	var thisObject = this;
	var sortSection = this.thead;
 
	// constructor actions
	if (!(this.tbody && this.tbody[0].rows && this.tbody[0].rows.length > 0)) return;
 
	if (sortSection && sortSection[0].rows && sortSection[0].rows.length > 0) {
		var sortRow = sortSection[0].rows[0];
	} else {
		return;
	}
 
	for (var i=0; i<sortRow.cells.length; i++) {
		sortRow.cells[i].sTable = this;
		sortRow.cells[i].onclick = function () {
			this.sTable.sort(this);
			return false;
		}
	}
	
	this.sort(sortRow.cells[0]);
 
}





























/*--------------------------------------------------------------*/
// HTML TABLE SORTER
// OBJECT ORIENTED JAVASCRIPT IMPLEMENTATION OF QUICKSORT
// @author	Terrill Dent 
// @source	http://www.terrill.ca
// @date	August 28th, 2006
/*--------------------------------------------------------------*/
function TSorter(){
	var table = Object;
	var trs = Array;
	var ths = Array;
	var curSortCol = Object;
	var prevSortCol = '3';
	var sortType = Object;

	function get(){}

	function getCell(index){
		return trs[index].cells[curSortCol] 
	}

	/*----------------------INIT------------------------------------*/
	// Initialize the variable
	// @param tableName - the name of the table to be sorted
	/*--------------------------------------------------------------*/
	this.init = function(tableName)
	{
		table = document.getElementById(tableName);
		ths = table.getElementsByTagName("th");
		for(var i = 0; i < ths.length ; i++)
		{
			ths[i].onclick = function()
			{
				sort(this);
			}
		}
		return true;
	};
	
	/*----------------------SORT------------------------------------*/
	// Sorts a particular column. If it has been sorted then call reverse
	// if not, then use quicksort to get it sorted.
	// Sets the arrow direction in the headers.
	// @param oTH - the table header cell (<th>) object that is clicked
	/*--------------------------------------------------------------*/
	function sort(oTH)
	{
		curSortCol = oTH.cellIndex;
		sortType = oTH.abbr;
		trs = table.tBodies[0].getElementsByTagName("tr");

		//set the get function
		setGet(sortType)

		// it would be nice to remove this to save time,
		// but we need to close any rows that have been expanded
		for(var j=0; j<trs.length; j++)
		{
			if(trs[j].className == 'detail_row')
			{
				closeDetails(j+2);
			}
		}

		// if already sorted just reverse
		if(prevSortCol == curSortCol)
		{
			oTH.className = (oTH.className != 'ascend' ? 'ascend' : 'descend' );
			reverseTable();
		}
		// not sorted - call quicksort
		else
		{
			oTH.className = 'ascend';
			if(ths[prevSortCol].className != 'exc_cell'){ths[prevSortCol].className = '';}
			quicksort(0, trs.length);
		}
		prevSortCol = curSortCol;
	}
	
	/*--------------------------------------------------------------*/
	// Sets the GET function so that it doesnt need to be 
	// decided on each call to get() a value.
	// @param: colNum - the column number to be sorted
	/*--------------------------------------------------------------*/
	function setGet(sortType)
	{
		switch(sortType)
		{   
			case "link_column":
				get = function(index){
					return  getCell(index).firstChild.firstChild.nodeValue;
				};
				break;
			default:
				get = function(index){	return getCell(index).firstChild.nodeValue;};
				break;
		};	
	}

	/*-----------------------EXCHANGE-------------------------------*/
	//  A complicated way of exchanging two rows in a table.
	//  Exchanges rows at index i and j
	/*--------------------------------------------------------------*/
	function exchange(i, j)
	{
		if(i == j+1) {
			table.tBodies[0].insertBefore(trs[i], trs[j]);
		} else if(j == i+1) {
			table.tBodies[0].insertBefore(trs[j], trs[i]);
		} else {
			var tmpNode = table.tBodies[0].replaceChild(trs[i], trs[j]);
			if(typeof(trs[i]) == "undefined") {
				table.appendChild(tmpNode);
			} else {
				table.tBodies[0].insertBefore(tmpNode, trs[i]);
			}
		}
	}
	
	/*----------------------REVERSE TABLE----------------------------*/
	//  Reverses a table ordering
	/*--------------------------------------------------------------*/
	function reverseTable()
	{
		for(var i = 1; i<trs.length; i++)
		{
			table.tBodies[0].insertBefore(trs[i], trs[0]);
		}
	}

	/*----------------------QUICKSORT-------------------------------*/
	// This quicksort implementation is a modified version of this tutorial: 
	// http://www.the-art-of-web.com/javascript/quicksort/
	// @param: lo - the low index of the array to sort
	// @param: hi - the high index of the array to sort
	/*--------------------------------------------------------------*/
	function quicksort(lo, hi)
	{
		if(hi <= lo+1) return;
		 
		if((hi - lo) == 2) {
			if(get(hi-1) > get(lo)) exchange(hi-1, lo);
			return;
		}
		
		var i = lo + 1;
		var j = hi - 1;
		
		if(get(lo) > get(i)) exchange(i, lo);
		if(get(j) > get(lo)) exchange(lo, j);
		if(get(lo) > get(i)) exchange(i, lo);
		
		var pivot = get(lo);
		
		while(true) {
			j--;
			while(pivot > get(j)) j--;
			i++;
			while(get(i) > pivot) i++;
			if(j <= i) break;
			exchange(i, j);
		}
		exchange(lo, j);
		
		if((j-lo) < (hi-j)) {
			quicksort(lo, j);
			quicksort(j+1, hi);
		} else {
			quicksort(j+1, hi);
			quicksort(lo, j);
		}
	}
}

