//table sorter v0.6 tom pearson
//20-6-2007 added facility to classify columns "unsortable"
//13-8-2007 made the default sort funciton ignore quotation marks
var _SORT_COLUMN_INDEX;

newsi.TableSorter = function(o){
	this.init(o);
}

newsi.SortUtil = function(){
	this.init();
}

newsi.TableSorter.prototype.init = function(o){
	// 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) && (thisTbl.id)){
			//initTable(thisTbl.id);
			this.makeSortable(thisTbl, o);
		}
	}
}

newsi.TableSorter.prototype.makeSortable = function(table, o){
	var util = new newsi.SortUtil();
	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 unless it has an 'unsortable' class associated
	for (var i=0;i<firstRow.cells.length;i++){
		var cell = firstRow.cells[i];
		var class_string = cell.className;
		var check = /unsortable/;
		if(!check.test(class_string)){	//need to use a regular expression here to assure that multiple classes can still be associated with the cell i.e. also a styling class if necessary
			var txt = util.getInnerText(cell);
			cell.innerHTML = '<a href="#" class="sortheader" '+ 'onclick="' + o.name + '.resortTable(this, '+i+');return false;">' + txt+'<span class="sortarrow"></span></a>';
		}
	}
}

newsi.SortUtil.prototype.init = function(){
	return true;
}

newsi.SortUtil.prototype.getInnerText = function(el){
	if (typeof el == "string") return el;
	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
				str += this.getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

newsi.TableSorter.prototype.resortTable = function(lnk,clid){
	//instantiate a utility class
	var util = new newsi.SortUtil();
	// 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 spantext = util.getInnerText(span);
	var td = lnk.parentNode;
	var column = clid || td.cellIndex;
	var table = this.getParent(td,'TABLE');
	
	// Work out a type for the column
	if (table.rows.length <= 1) return;
	var check_row = 1;
	var itm = util.getInnerText(table.rows[check_row].cells[column]);
	sortfn = this.sort_caseinsensitive;		//the standard anything goes type sort
	while (itm.match(/[nN]\/[aA]/)){
		check_row ++;
		itm = util.getInnerText(table.rows[check_row].cells[column]);
	}
	if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)){ 
		sortfn = this.sort_date;
	}else if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)){ 
		sortfn = this.sort_date;
	}else if (itm.match(/^[£$]/)){ 
		sortfn = this.sort_currency;
	}else if (itm.match(/^[\d\,\.]+$/)){ 
		sortfn = this.sort_num_commas;
	}else if (itm.match(/^[\d\.]+$/)){ 
		sortfn = this.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++){ 
		newRows[j-1] = table.rows[j]; 
	}

	newRows.sort(sortfn);
// the ARROW variable can be used to specify a sort icon, HTML etc.
	if (span.getAttribute("sortdir") == 'down'){
		ARROW = '';
		newRows.reverse();
		span.setAttribute('sortdir','up');
	} else{
		ARROW = '';
		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++){ 
		if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))){
			table.tBodies[0].appendChild(newRows[i]);
		}
	}
	// do sortbottom rows only
	for (i=0;i<newRows.length;i++){ 
		if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) {
			table.tBodies[0].appendChild(newRows[i]);
		}
	}
	
	// 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 (this.getParent(allspans[ci],"table") == this.getParent(lnk,"table")){ // in the same table as us?
				allspans[ci].innerHTML = '';
			}
		}
	}
		
	span.innerHTML = ARROW;
	this.setRowClasses(table);
}

newsi.TableSorter.prototype.setRowClasses = function(table){
	var rows = table.rows.length;
	var r_even=false;
	for (var colour_row = 1; colour_row<rows; colour_row++){
		if(!r_even){
			table.rows[colour_row].className = "odd_row"; 
		}else{
			table.rows[colour_row].className = "even_row"; 
		}
		r_even = !r_even;
	}
}

newsi.TableSorter.prototype.sortFunction = function(itm){
}

newsi.TableSorter.prototype.getParent = function(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 this.getParent(el.parentNode, pTagName);
}


//HERE ARE THE SORT FUNCTIONS
newsi.TableSorter.prototype.sort_date = function(a,b){
	var util = new newsi.SortUtil();
	// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
	aa = util.getInnerText(a.cells[_SORT_COLUMN_INDEX]);
	bb = util.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;
}

newsi.TableSorter.prototype.sort_currency = function(a,b){ 
	var util = new newsi.SortUtil();
	aa = util.getInnerText(a.cells[_SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
	bb = util.getInnerText(b.cells[_SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
	return parseFloat(aa) - parseFloat(bb);
}

newsi.TableSorter.prototype.sort_numeric = function(a,b){ 
	var util = new newsi.SortUtil();
	aa = parseFloat(util.getInnerText(a.cells[_SORT_COLUMN_INDEX]));
	if (isNaN(aa)){
		aa = 0;
	}
	bb = parseFloat(util.getInnerText(b.cells[_SORT_COLUMN_INDEX])); 
	if (isNaN(bb)){
		bb = 0;
	}
	return aa-bb;
}
	

newsi.TableSorter.prototype.sort_num_commas = function(a,b){
	var util = new newsi.SortUtil();
	astring = util.getInnerText(a.cells[_SORT_COLUMN_INDEX]);
	bstring = util.getInnerText(b.cells[_SORT_COLUMN_INDEX])

	temp_array_a = astring.split(",");
	temp_array_b = bstring.split(",");

	astring = temp_array_a.join("");
	bstring = temp_array_b.join("");

	aa = parseFloat(astring);
	if (isNaN(aa)) aa = 0;
	bb = parseFloat(bstring); 
	if (isNaN(bb)) bb = 0;
	return aa-bb;
}

newsi.TableSorter.prototype.sort_caseinsensitive = function(a,b){
	var util = new newsi.SortUtil();
	
	aa = util.getInnerText(a.cells[_SORT_COLUMN_INDEX]).toLowerCase();
	bb = util.getInnerText(b.cells[_SORT_COLUMN_INDEX]).toLowerCase();
	var temp = aa.split('"');
	aa = temp.join("");
	var temp = bb.split('"');
	bb = temp.join("");
	
	if(aa=="N/A"){			// N/A always gets sent to the bottom
		return -1;
	}
	if (aa==bb) return 0;
	if (aa<bb) return -1;
	return 1;
}

newsi.TableSorter.prototype.sort_default = function(a,b){
	var util = new newsi.SortUtil();
	aa = util.getInnerText(a.cells[_SORT_COLUMN_INDEX]);
	bb = util.getInnerText(b.cells[_SORT_COLUMN_INDEX]);
	if(aa=="N/A"){			// N/A always gets sent to the bottom
		return -1;
	}
	if (aa==bb) return 0;
	if (aa<bb) return -1;
	return 1;
}