/* 
 * Note: A copy is to be placed in /content/javascript once updated
 * 
 * This plugin defines the sorting mechanism in all pages 
 */

$(document).ready(function(){
	$('table').each( function(index, element) {
		var $table = $(element);	
		if( $table.hasClass('sortable') ) {
			var thCollection = $table.find('th');
			$.each( thCollection, function(index, element) {
				// To paint the noSort arrow
				if($(element).hasClass('noSort')) {
					$a = $(element).find("a");
					if(!$a.find("span")[0]) {
						$a.html($a.html() + "<span>&nbsp;</span>"); 
					}
				} 
			});
		}
		
		if ($(element).attr("id") == 'docListTable') {
		    sortDocs = new TableSort($('#docListTable')[0]);
		    sortDocs.sort(0, "tSort");
			var thCollection = $("#docListTable").find('th');
			$.each( thCollection, function(index, element) {
				$( element ).bind('click', function(event) {
					event.preventDefault();
					
					var sortType = ( $(element).hasClass('data') ) ? 'Number' : null;
					if($(element).hasClass('date')){
						sortType = $(element).attr("_fmt");
					}
					
					sortDocs.sort(index, sortType);
				}); 
			});
	  	}
	});
});

function TableSort(oTable, oSortTypes) {

	this.sortTypes = oSortTypes || [];
	this.sortColumn = null;
	this.descending = null;
	this.lastImageId = null;
	this.sortImage 		= new Image();
	this.sortImageUp	= new Image();
	this.sortImageDown = new Image();

  /* Allow Multiple Arrow Styles, Read Prefix From XHTML */
  var sortEnt = $('#sort_key_0')[0];
  if(sortEnt) {
  	var sortSrc = sortEnt.src;
  	var srcBits = sortSrc.split("/");
  	var imgName = srcBits[srcBits.length-1];
  	var imgBits = imgName.split("_");
  	var imgPrefix = imgBits[0];
	this.sortImage.src = "/images/" + imgPrefix + "_sort.gif";
	this.sortImageUp.src = "/images/" + imgPrefix + "_sort_up.gif";
	this.sortImageDown.src = "/images/" + imgPrefix + "_sort_down.gif";
  }

  var oThis = this;

  this._headerOnclick = function (e) {
		oThis.headerOnclick(e);
	};

	if (oTable) {
		this.setTable( oTable );
		this.document = oTable.ownerDocument || oTable.document;
	} else {
		this.document = document;
	}

	// only IE needs this
	var win = this.document.defaultView || this.document.parentWindow;
	this._onunload = function () {
		oThis.destroy();
	};
	if (win && typeof win.attachEvent != "undefined") {
		win.attachEvent("onunload", this._onunload);
	}
}

TableSort.gecko = navigator.product == "Gecko";
TableSort.msie = /msie/i.test(navigator.userAgent);
// Mozilla is faster when doing the DOM manipulations on
// an orphaned element. MSIE is not
TableSort.removeBeforeSort = TableSort.gecko;

TableSort.prototype.onsort = function () {};
// shared between all instances. This is intentional to allow external files
// to modify the prototype
TableSort.prototype._sortTypeInfo = {};

TableSort.prototype.setTable = function (oTable) {
	this.element = oTable;
	this.setTBody( oTable.tBodies[0] );
};

TableSort.prototype.setTBody = function (oTBody) {
	this.tBody = oTBody;
};

TableSort.prototype.setSortTypes = function ( oSortTypes ) {
	this.sortTypes = oSortTypes || [];
};

// IE returns wrong cellIndex when columns are hidden
TableSort.getCellIndex = function (oTd) {
	var cells = oTd.parentNode.childNodes;
	var l = cells.length;
	var i;
	for (i = 0; cells[i] != oTd && i < l; i++) {}
	return i;
};

TableSort.prototype.getSortType = function (nColumn) {
	return this.sortTypes[nColumn] || "String";
};


TableSort.prototype.changeSortImage = function(nColumn) {
	var thCollection = $(this.element).find('th').removeClass('headerSortDown headerSortUp');
	var $th = $(thCollection[nColumn]);
	var tableSortInstance = (tableSortInstance) ? tableSortInstance : this;
	$th.addClass(tableSortInstance.descending ? 'headerSortUp' : 'headerSortDown');
};

// only nColumn is required
// if bDescending is left out the old value is taken into account
// if sSortType is left out the sort type is found from the sortTypes array
TableSort.prototype.sort = function (nColumn, sSortType, direction) {
  if (!this.tBody) {
	return;
  }
  if (sSortType == null) {
	sSortType = this.getSortType(nColumn);
  }

  if (this.sortColumn != nColumn) {
    this.descending = (sSortType=="String" || sSortType=="CareersString" || sSortType=="Date"
    	 || sSortType=="ExpenseRatio" || sSortType == "Number"  ) ? false : true;
  } else {
    this.descending = !this.descending;
  }

  this.changeSortImage(nColumn);
  this.sortColumn = nColumn;

  if (typeof this.onbeforesort == "function") {
	this.onbeforesort();
  }

  var f = this.getSortFunction(sSortType, nColumn);
  var a = this.getCache(sSortType, nColumn);
  
  // Only perform sorting when array is not null 
  if(a != null) {
	  var tBody = this.tBody;

	  a.sort(f);

	  if (this.descending) {
		  a.reverse();
	  }
		
	  if (TableSort.removeBeforeSort) {
		// remove from doc
		var nextSibling = tBody.nextSibling;
		var p = tBody.parentNode;
		p.removeChild(tBody);
	  }
		
	  // insert in the new order
	  var l = a.length;
	  for (var i = 0; i < l; i++) {
		tBody.appendChild(a[i].element);
	  }
		
	  this.setRowColor(tBody);
		
	  if (TableSort.removeBeforeSort) {
		// insert into doc
		p.insertBefore(tBody, nextSibling);
	  }
		
	  this.destroyCache(a);
		
	  if (typeof this.onsort == "function") {
		  this.onsort();
	  }
  }
};

TableSort.prototype.getCache = function (sType, nColumn) {
	if (!this.tBody) return [];
	var rows = this.tBody.rows;
	var l = rows.length;
	var a = new Array(l);
	var r;
	var allValuesAreTheSame = true;
	for (var i = 0; i < l; i++) {
		r = rows[i];
		a[i] = {
			value:		this.getRowValue(r, sType, nColumn),
			element:	r
		};
		if(i > 0) {
			if(a[i].value != a[i - 1].value) {
				allValuesAreTheSame = false;
			}
		}
	};
	// There is no point to sort if all the values are same, hence return null to skip sorting
	if(allValuesAreTheSame) {
		return null;
	} else {
		return a;
	}
};

TableSort.prototype.destroyCache = function (oArray) {
	var l = oArray.length;
	for (var i = 0; i < l; i++) {
		oArray[i].value = null;
		oArray[i].element = null;
		oArray[i] = null;
	}
};

TableSort.prototype.getRowValue = function (oRow, sType, nColumn) {
	// if we have defined a custom getRowValue use that
	if (this._sortTypeInfo[sType] && this._sortTypeInfo[sType].getRowValue) {
		return this._sortTypeInfo[sType].getRowValue(oRow, nColumn);
	}

	var s;
	var c = oRow.cells[nColumn];
	if (typeof c.innerText != "undefined") {
		s = c.innerText;
	} else {
		s = TableSort.getInnerText(c);
	}	

	return this.getValueFromString(s, sType);
};

TableSort.getInnerText = function (oNode) {
	var s = "";
	var cs = oNode.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				s += TableSort.getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				s += cs[i].nodeValue;
				break;
		}
	}
	return s;
};

TableSort.prototype.getValueFromString = function (sText, sType) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].getValueFromString( sText );
	return sText;
};

TableSort.prototype.getSortFunction = function (sType, nColumn) {
	if (this._sortTypeInfo[sType])
		return this._sortTypeInfo[sType].compare;
	return TableSort.basicCompare;
};

TableSort.prototype.destroy = function () {
	var win = this.document.parentWindow;
	if (win && typeof win.detachEvent != "undefined") {	// only IE needs this
		win.detachEvent("onunload", this._onunload);
	}
	this._onunload = null;
	this.element = null;
	this.tBody = null;
	this.document = null;
	this._headerOnclick = null;
	this.sortTypes = null;
	this.onsort = null;
};

// Adds a sort type to all instance of TableSort
// sType : String - the identifier of the sort type
// fGetValueFromString : function ( s : string ) : T - A function that takes a
//    string and casts it to a desired format. If left out the string is just
//    returned
// fCompareFunction : function ( n1 : T, n2 : T ) : Number - A normal JS sort
//    compare function. Takes two values and compares them. If left out less than,
//    <, compare is used
// fGetRowValue : function( oRow : HTMLTRElement, nColumn : int ) : T - A function
//    that takes the row and the column index and returns the value used to compare.
//    If left out then the innerText is first taken for the cell and then the
//    fGetValueFromString is used to convert that string the desired value and type

TableSort.prototype.addSortType = function (sType, fGetValueFromString, fCompareFunction, fGetRowValue) {
	this._sortTypeInfo[sType] = {
		type:				sType,
		getValueFromString:	fGetValueFromString || TableSort.idFunction,
		compare:			fCompareFunction || TableSort.basicCompare,
		getRowValue:		fGetRowValue
	};
};

// this removes the sort type from all instances of TableSort
TableSort.prototype.removeSortType = function (sType) {
	delete this._sortTypeInfo[sType];
};

TableSort.basicCompare = function compare(n1, n2) {
	if (n1.value < n2.value)
		return -1;
	if (n2.value < n1.value)
		return 1;
	return 0;
};

TableSort.idFunction = function (x) {
	return x;
};

TableSort.toUpperCase = function (s) {
	return s.toUpperCase();
};

TableSort.careersString = function (s) {
  var tempString = s.toUpperCase();

  return tempString.replace(/^\s+/, '');
};

//Removes all non-ascii characters (bewtween 64 & 90, 97 & 122 incl.)
//so that the crazy-bad production search that doesn't search normally
//will be mimiced here. In the improved version.
TableSort.toCrazyLetterOnlyCase = function (s) {
	var t= "";
	var z = s.length;
	for (var i = 0; i < z; i++){
		var c = s.charCodeAt(i);
		if ((c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123))
			t += s.charAt(i);
	}
	return t.toUpperCase();
};

//Makes strings with NA a super priority.
TableSort.NASearch = function (s) {
	if (s.indexOf("N/A") == 0)
		return " ";
	else if (s.replace(/^\s+|\s+$/g,"") == "-")
		return " ";
	else return s;
};

TableSort.toDate = function (s) {
  var parts = s.split("/");
	var d = new Date(0);
  //year, month, day for parameters
  d.setFullYear(parts[2],parts[0],parts[1]);
  return d.valueOf();
};

TableSort.toDateShortFormat = function (s) {
  var parts = s.split("-");
  
  if(parts.length == 3) {
	  var d = new Date(0);
	  var month;
	  var year;
	
	  if(parts[1] == 'Jan') {
		  month = 1;
	  } else if(parts[1] == 'Feb') {
		  month = 2;
	  } else if(parts[1] == 'Mar') {
		  month = 3;
	  } else if(parts[1] == 'Apr') {
		  month = 4;
	  } else if(parts[1] == 'May') {
		  month = 5;
	  } else if(parts[1] == 'Jun') {
		  month = 6;
	  } else if(parts[1] == 'Jul') {
		  month = 7;
	  } else if(parts[1] == 'Aug') {
		  month = 8;
	  } else if(parts[1] == 'Sep') {
		  month = 9;
	  } else if(parts[1] == 'Oct') {
		  month = 10;
	  } else if(parts[1] == 'Nov') {
		  month = 11;
	  } else if(parts[1] == 'Dec') {
		  month = 12;
	  }
	
	  year = parts[2];
	  year = year.substring(0,4);
	
	  d.setFullYear(year,month,parts[0]);
	  return d.valueOf();
  } else {
	  return TableSort.toDateChineseOrJapaneseFormat(s);
  }
};


TableSort.toDateChineseOrJapaneseFormat = function (s) {
  var d = new Date(0);
  var month;
  var year;
  var day;

  year = s.substring(0,4);
  month = s.substring(5,7);
  day = s.substring(8,10);

  if(isNaN(day)){
	day = s.substring(8,9);
  }

  d.setFullYear(year,month,day);
  return d.valueOf();
};

TableSort.getNumber = function (s) {
  //remove commas, currency signs and asterisks before testing number
  s = s.replace(/[$*,%K]/g,"");
  if (isNaN(Number(s))) {
    s="-9999999";
  }

  return Number(s);
};

TableSort.getSuperscript = function (s) {	
  //remove spaces, new lines and paranthesis before testing number  
  s = s.replace(/[\n,\s]/g,"");
  s = s.replace(/\(\d\)/g,"");
  s = s.replace(/N\/A/g,"-9999999");
  if (isNaN(Number(s))) {
    s="-9999999";
  }
  return Number(s);
};

TableSort.mixOfNumbersAndAlphabets = function (s) {
	s = $.trim(s);
	if (!isNaN(Number(s))) {
		var zeros = "0000000000";
		if(s.length < zeros.length) {
			s = zeros.substring(0, zeros.length - s.length) + s;
		}
	}
	return s.toUpperCase();
};

// add sort types
TableSort.prototype.addSortType("Number", TableSort.getNumber);
TableSort.prototype.addSortType("ExpenseRatio", TableSort.getNumber);
TableSort.prototype.addSortType("Superscript", TableSort.getSuperscript);
TableSort.prototype.addSortType("CaseInsensitiveString", TableSort.toUpperCase);
TableSort.prototype.addSortType("Date", TableSort.toDate);
TableSort.prototype.addSortType("DateShortFormat", TableSort.toDateShortFormat);
TableSort.prototype.addSortType("DateChineseFormat", TableSort.toDateChineseOrJapaneseFormat);
TableSort.prototype.addSortType("DateDescend", TableSort.toDate);
TableSort.prototype.addSortType("String", TableSort.toUpperCase);
TableSort.prototype.addSortType("CareersString", TableSort.careersString);
TableSort.prototype.addSortType("Options", TableSort.toUpperCase);
//where we DON'T sort in the normal alphabetical manner! Hooray for diversity!
TableSort.prototype.addSortType("tSort", TableSort.toCrazyLetterOnlyCase);
TableSort.prototype.addSortType("mixSort", TableSort.mixOfNumbersAndAlphabets);
TableSort.prototype.addSortType("na", TableSort.NASearch);
// None is a special case

//Apply alternating backgroundColor on each row after sort.
TableSort.prototype.setRowColor = function(tBody) {
	var $trCollection = $(tBody).find('tr');
	$.each( $trCollection, function(index, element) {
		var $element = $(element);
		(index %2 == 0) ? $element.attr('className', 'even') : $element.attr('className', 'odd');
	});
};
