//addEvent(window, "load", sortables_init);
var SORT_COLUMN_INDEX;
var TABLESHOWN = ((document.all) ? "block" : "table");

function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) ) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) ) {
			//duplicate table and make it invisible, with no rowspans
			var newTable = thisTbl.cloneNode(true);
			// insert the dupe
			newTable = thisTbl.parentNode.insertBefore(newTable, thisTbl.nextSibling);
			newTable.style.display = "none"
			// change it's id
			newTable.id = newTable.id + "_NoRowSpans"
			
			// change the new table to eliminate row spans:
   			 var deleteThese = new Array;
   			 for (j=1;j<newTable.rows.length;j++) { 
				var rowspan = newTable.rows[j].cells[0].rowSpan;
				var thisrow = newTable.rows[j]
				if (rowspan > 1) {
					var firstCell = thisrow.cells[0].cloneNode(true);
					var lastCell = thisrow.cells[thisrow.cells.length - 1].cloneNode(true);
					firstCell.setAttribute("rowSpan", "1");
					lastCell.setAttribute("rowSpan", "1");
					for (k=0; k < rowspan; k++) {				// loop through the rows effected by the rowspan

						// duplicate the rows of the span into individually sortable rows:
						if (newTable.rows[j + k]){
							var thisRowToGo = newTable.rows[j + k]
							deleteThese.push(thisRowToGo);
							var rowClone = thisRowToGo.cloneNode(false);  //clone of row, without any cells
							
							// cells:
										if(k != 0) rowClone.appendChild(firstCell.cloneNode(true));	// replace the first cell that was missing due to the rowspan
										
										//add in the rest of the cells of the row
										for (var c=0; c < thisRowToGo.cells.length; c++) {
											var cellClone = thisRowToGo.cells[c].cloneNode(true);
											
											// change any rowspans to single rows
											thisRS = parseInt(thisRowToGo.cells[c].getAttribute("rowspan")) // why can't IE just get it from the clone's ".rowSpan", and regognize it as a number, like everyone else?
											if (thisRS) cellClone.setAttribute("rowSpan", "1");
											if(cellClone.className.indexOf("notfirstrow") != -1) cellClone.className = cellClone.className.replace(/(.*)notfirstrow(.*)/,"$1 $2")
											rowClone.appendChild(cellClone);
										}
										
										if(k != 0) rowClone.appendChild(lastCell.cloneNode(true));  // replace the cells that were missing due to the rowspan
							thisRowToGo.parentNode.appendChild(rowClone);	// add the new row
						}
   			 		}
   			 	}
   			 }
   			 
   			 // get rid of the old spanned rows, that were saved for deletion
   			 for (j=0;j<deleteThese.length;j++) {
   			 	deleteThese[j].parentNode.removeChild(deleteThese[j]);
   			 }
			
			ti++
        }
    }
}

colTitle = "Click here to sort this table by the values in this column"
function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;
    
    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '<a href="#" class="sortheader" '+ 
        'onclick="ts_resortTable(this, '+i+');return false;" title="'+ colTitle +'">' + 
        txt+'<span class="sortarrow">&nbsp;&nbsp;&nbsp;<'+'/span><'+'/a>';
    }
    
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if(!el) return ""
	//if (typeof el == "undefined") { return el };
	//if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				if(cs[i].nodeName == "DIV") {
					//alert(ts_getInnerText(cs[i].nextSibling));
					str += ts_getInnerText(cs[i].nextSibling);
				} else {
					str += ts_getInnerText(cs[i]);
				}
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk,clid) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var td = lnk.parentNode;
    var column = clid || td.cellIndex;
    var table = getParent(td,'TABLE');
    
    var COLUMN_HAS_ROWSPANS = false;
	for (r=1;r<table.rows.length;r++){
		originalTable = (table.id.indexOf("_") == -1) ? table : document.getElementById(table.id.split("_")[0]);
		if (originalTable.rows[r].cells.length > column && originalTable.rows[r].cells[column].rowSpan > 1) {
			COLUMN_HAS_ROWSPANS = true;
		}
	}
	
	if(!COLUMN_HAS_ROWSPANS){
		if (table.id.indexOf("_") == -1) { 
			table.style.display = "none"
			table = document.getElementById(table.id + "_NoRowSpans")
			table.style.display = TABLESHOWN
			lnk = table.rows[0].cells[column].firstChild
			ts_resortTable(lnk,clid)
			return
		} 
	} else {
		if (table.id.indexOf("_") > -1) { 
			table.style.display = "none"
			table = document.getElementById(table.id.split("_")[0])
			table.style.display = TABLESHOWN
			lnk = table.rows[0].cells[column].firstChild
			ts_resortTable(lnk,clid)
			return
		} 
	}
    
    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[£$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+[%]*$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    
    for (j=1;j<table.rows.length;j++) { 
		 
    	var rowspan = table.rows[j].cells[0].rowSpan;
    	if (rowspan > 1) {
    		var spannedRows = new Array()
    		for (k=0; k < rowspan; k++) {
    			spannedRows[k] = table.rows[j + k]
    		}
    		newRows.push(spannedRows)
    		j = j + rowspan - 1;
    	} else newRows.push(table.rows[j]);
    }

    newRows.sort(sortfn);

	if (span.getAttribute("sortdir") == 'down' && lnk.className.indexOf("selected") != -1) {
		ARROW = '&nbsp;&nbsp;&uarr;';
		newRows.reverse();
		span.setAttribute('sortdir','up');
	} else {
		ARROW = '&nbsp;&nbsp;&darr;';
		span.setAttribute('sortdir','down');
	}
    
    
    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { 
    	thisRow = newRows[i]
    	if (thisRow.length) for (x=0;x<thisRow.length;x++) {
    		thisRowSpanRow = thisRow[x];
    		if (!thisRowSpanRow.className || (thisRowSpanRow.className && (thisRowSpanRow.className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(thisRowSpanRow);
    	}
    	else if (!thisRow.className || (thisRow.className && (thisRow.className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(thisRow);
    }
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { 
    	thisRow = newRows[i]
    	if (thisRow.length) for (x=0;x<thisRow.length;x++) {
    		thisRowSpanRow = thisRow[x]
    		if (thisRowSpanRow.className && (thisRowSpanRow.className && (thisRowSpanRow.className.indexOf('sortbottom') != -1))) table.tBodies[0].appendChild(thisRowSpanRow);
    	}
    	else if (thisRow.className && (thisRow.className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(thisRow);
    }
    
    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';
                allspans[ci].parentNode.className = "sortheader" //remove "selected" from link class name
                allspans[ci].parentNode.setAttribute('title',colTitle);
            }
        }
    }
        
    span.innerHTML = ARROW;
    
    lnk.className = lnk.className + " selected" ;
	lnk.setAttribute('title','Click here to reverse the sort order of this table');
    lnk.blur();
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    if(typeof(a[0]) == "object") aa = ts_getInnerText(a[0].cells[SORT_COLUMN_INDEX]);
    else aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    if(typeof(b[0]) == "object") bb = ts_getInnerText(b[0].cells[SORT_COLUMN_INDEX]);
    else bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) { 
    if(typeof(a[0]) == "object") aa = ts_getInnerText(a[0].cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    else aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    if(typeof(b[0]) == "object") bb = ts_getInnerText(b[0].cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    else bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
    if(typeof(a[0]) == "object") aa = parseFloat(ts_getInnerText(a[0].cells[SORT_COLUMN_INDEX]));
    else aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    if(typeof(b[0]) == "object") bb = parseFloat(ts_getInnerText(b[0].cells[SORT_COLUMN_INDEX]));
    else bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    if(typeof(a[0]) == "object") aa = ts_getInnerText(a[0].cells[SORT_COLUMN_INDEX]).toLowerCase();
	else aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
	if (typeof(b[0]) == "object") bb = ts_getInnerText(b[0].cells[SORT_COLUMN_INDEX]).toLowerCase();
    else bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    if(typeof(a[0]) == "object") aa = ts_getInnerText(a[0].cells[SORT_COLUMN_INDEX]);
   	else aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    if(typeof(b[0]) == "object") bb = ts_getInnerText(b[0].cells[SORT_COLUMN_INDEX]);
    else bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}


function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
} 

sortables_init();

