/*
	SortTable v2, original by Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
	Extensively modified by Partyflock
*/
 
sorttable = {
	init: function() {
/*		// quit if this function has already been called
		if (arguments.callee.done) return;
		// flag this function so we don't do the same thing twice
		arguments.callee.done = true;*/
		// kill the timer
//		if (_timer) clearInterval(_timer);
		
		if (!document.createElement || !document.getElementsByTagName) return;
		
		sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
		
		forEach(document.getElementsByTagName('table'), function(table) {
			if (	table.className.search(/\bsortable\b/) != -1
			&&	!table.getAttribute('madeSortable')
			) {
				sorttable.makeSortable(table);
//				setattr(table,'madeSortable',true);
			}
		});
		
	},
	get_symbol: function(sorted) {
		return	Browser.IE && Browser.version < 8
		?	(	sorted
			?	'<font face="webdings">'+(sorted == 'up' ? 5 : 6)+'</font>'
			:	'<font face="webdings">5</font>'
			)
		:	(	sorted
			?	'&#x25B'+(sorted == 'up' ? 4 : 'E')+';'
			:	'&#x25B4;'
			);
	},
	makeSortable: function(table) {
		if (table.getElementsByTagName('thead').length == 0) {
			// table doesn't have a tHead. Since it should have, create one and
			// put the first table row in it.
			var the = document.createElement('thead');
			the.appendChild(table.rows[0]);
			table.insertBefore(the,table.firstChild);
		}
		// Safari doesn't support table.tHead, sigh
		if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
		
		if (table.tHead.rows.length != 1) return; // can't cope with two header rows
		
		// Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
		// "total" rows, for example). This is B&R, since what you're supposed
		// to do is put them in a tfoot. So, if there are sortbottom rows,
		// for backwards compatibility, move them to tfoot (creating it if needed).
		var sortbottomrows = [];
		for (var i=0; i<table.rows.length; i++) {
			if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
				sortbottomrows.push(table.rows[i]);
			}
		}
		if (sortbottomrows) {
			if (table.tFoot == null) {
				// table doesn't have a tfoot. Create one.
				var tfo = document.createElement('tfoot');
				table.appendChild(tfo);
			}
			for (var i=0; i<sortbottomrows.length; i++) {
				tfo.appendChild(sortbottomrows[i]);
			}
			delete sortbottomrows;
		}
		// work through each column and calculate its type
		var headrows = [];
		var bodies = [];
		if (	table.tHead.rows.length
		&&	table.tHead.rows[0].cells.length
		) {
			headrows.push(table.tHead.rows[0].cells);
			bodies.push(table.tBodies[0]);
		} else {
			for (var i=0; i < table.tBodies.length; ++i) {
				var tBody = table.tBodies[i];
				if (tBody.getAttribute('data-sortable') == 'header') {
					headrows.push(tBody.rows[0].cells);
					bodies.push(table.tBodies[++i]);
				}
			}
		}
		for (var j=0; j<headrows.length; ++j) {
			var headrow = headrows[j];
			var body = bodies[j];
			for (var i=0; i<headrow.length; i++) {
				// manually override the type with a sorttable_type attribute
				var headnode = headrow[i];
				if (!headnode.className.match(/\bsorttable_nosort\b/)) { 
					addclass(headnode,'sortable');
					headnode.righty = headnode.className.match(/\bright\b/) ? true : false;
					var mtch = headnode.className.match(/\bsorttable_([a-z0-9_]+)\b/);
					if (mtch && typeof sorttable["sort_"+mtch[1]] == 'function')
						headnode.sorttable_sortfunction = sorttable["sort_"+mtch[1]];
					else	headnode.sorttable_sortfunction = sorttable.guessType(body,i);
					// make it clickable to sort
					headnode.sorttable_columnindex = i;
					headnode.sorttable_tbody = body;
					var sortind = document.createElement('span');
					var sorted = headnode.getAttribute('data-sorted');
					sortind.innerHTML = sorttable.get_symbol(sorted ? sorted : 'up');
					sortind.className = (headnode.righty ? 'rmrgn' : 'lmrgn')+(sorted ? '' : ' lighter');
					headnode.sortind = sortind;
					headnode.className += ' nowrap';
					if (headnode.righty) {
						headnode.insertBefore(sortind,headnode.firstChild);
					} else {
						headnode.appendChild(sortind);
					}
					if (!headnode.parentNode.sortinds)
						headnode.parentNode.sortinds = [sortind];
					else	headnode.parentNode.sortinds.push(sortind);

					addevent(headnode,'click',function(e){
						var sorted = this.getAttribute('data-sorted');
						if (sorted) {
							var newsorted = sorted == 'up' ? 'down' : 'up';
							sorttable.reverse(this.sorttable_tbody);
							this.setAttribute('data-sorted',newsorted);
							this.sortind.innerHTML = sorttable.get_symbol(newsorted);
							return;
						}
						var theadrow = this.parentNode;
						var csortind = this.sortind;
						forEach(theadrow.sortinds, function(sortind) {
							sortind.parentNode.removeAttribute('data-sorted');
							if (sortind == csortind) {
								remclass(sortind,'lighter');
							} else {
								addclass(sortind,'lighter');
							}
							sortind.innerHTML = sorttable.get_symbol('up');
						});
						this.setAttribute('data-sorted','up');
						this.sortind.innerHTML = sorttable.get_symbol('up');
						// build an array to sort. This is a Schwartzian transform thing,
						// i.e., we "decorate" each row with the actual sort key,
						// sort based on the sort keys, and then put the rows back in order
						// which is a lot faster because you only do getInnerText once per row
						var row_array = [];
						var col = this.sorttable_columnindex;
						var rows = this.sorttable_tbody.rows;
						for (var j=0; j<rows.length; j++) {
							row_array.push([sorttable.getInnerText(rows[j].cells[col]), rows[j]]);
						}
						/* If you want a stable sort, uncomment the following line */
						//sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
						/* and comment out this one */
						row_array.sort(this.sorttable_sortfunction);
						if (this.className.match(/\bis_sorted_asc\b/)) {
							row_array.reverse();
						}
						var tb = this.sorttable_tbody;
						for (var j=0; j<row_array.length; j++) {
							tb.appendChild(row_array[j][1]);
						}
						
						delete row_array;
						var table = tb.parentNode;
						if (/\bzebra\b/.test(table.className)) {
							for (var i = 0; i < tb.rows.length; ++i) {
								if (i&1)
									addclass(tb.rows[i],'zebra');
								else	remclass(tb.rows[i],'zebra');
							}
						}
					});
				}
			}
		}
	},
	
	guessType: function(body, column) {
		// guess the type of a column based on its first non-blank row
		var sortfn = sorttable.sort_alpha;
		for (var i=0; i<body.rows.length; i++) {
			var text = sorttable.getInnerText(body.rows[i].cells[column]);
			if (text != '') {
				if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
					return sorttable.sort_numeric;
				}
				// check for a date: dd/mm/yyyy or dd/mm/yy 
				// can have / or . or - as separator
				// can be mm/dd as well
				var possdate = text.match(sorttable.DATE_RE)
				if (possdate) {
					// looks like a date
					first = parseInt(possdate[1]);
					second = parseInt(possdate[2]);
					if (first > 12) {
						// definitely dd/mm
						return sorttable.sort_ddmm;
					} else if (second > 12) {
						return sorttable.sort_mmdd;
					} else {
						// looks like a date, but we can't tell which, so assume
						// that it's dd/mm (English imperialism!) and keep looking
						sortfn = sorttable.sort_ddmm;
					}
				}
			}
		}
		return sortfn;
	},
	
	getInnerText: function(node) {
		// gets the text we want to use for sorting for a cell.
		// strips leading and trailing whitespace.
		// this is *not* a generic getInnerText function; it's special to sorttable.
		// for example, you can override the cell text with a customkey attribute.
		// it also gets .value for <input> fields.
		if (!node) return '';
		var text = node.getAttribute('value');
		if (text !== null) return text;
		var text = getText(node);
		return text.replace(/^\s+|\s+$/g,'');
	},
	
	reverse: function(tbody) {
		var newrows = [];
		for (var i=0; i < tbody.rows.length; ++i) {
			newrows.push(tbody.rows[i]);
		}
		for (var i = newrows.length-1; i >= 0; --i) {
			 tbody.appendChild(newrows[i]);
		}
		delete newrows;
	},
	
	/* sort functions
		 each sort function takes two parameters, a and b
		 you are comparing a[0] and b[0] */
	sort_numeric: function(a,b) {
		if (!a || !b) {
			return;
		}
		var aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
		if (isNaN(aa)) aa = 0;
		var bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
		if (isNaN(bb)) bb = 0;
		return aa-bb;
	},
	sort_alphacase: function(a,b) {
		if (a[0]==b[0]) return 0;
		if (a[0]<b[0]) return -1;
		return 1;
	},
	sort_alpha: function(a,b) {
		a = a[0].toLowerCase();
		b = b[0].toLowerCase();
		if (a==b) return 0;
		if (a<b) return -1;
		return 1;
	}
/*	shaker_sort: function(list, comp_func) {
		// A stable sort function to allow multi-level sorting of data
		// see: http://en.wikipedia.org/wiki/Cocktail_sort
		// thanks to Joseph Nahmias
		var b = 0;
		var t = list.length - 1;
		var swap = true;

		while(swap) {
				swap = false;
				for(var i = b; i < t; ++i) {
						if ( comp_func(list[i], list[i+1]) > 0 ) {
								var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
								swap = true;
						}
				} // for
				t--;

				if (!swap) break;

				for(var i = t; i > b; --i) {
						if ( comp_func(list[i], list[i-1]) < 0 ) {
								var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
								swap = true;
						}
				} // for
				b++;

		} // while(swap)
	}	
*/
}

// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
	forEach, version 1.0
	Copyright 2006, Dean Edwards
	License: http://www.opensource.org/licenses/mit-license.php
*/

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
	Array.forEach = function(array, block, context) {
		for (var i = 0; i < array.length; i++) {
			block.call(context, array[i], i, array);
		}
	};
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
	for (var key in object) {
		if (typeof this.prototype[key] == "undefined") {
			block.call(context, object[key], key, object);
		}
	}
};
// character enumeration
String.forEach = function(string, block, context) {
	Array.forEach(string.split(""), function(chr, index) {
		block.call(context, chr, index, string);
	});
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
	if (object) {
		var resolve = Object; // default
		if (object instanceof Function) {
			// functions have a "length" property
			resolve = Function;
		} else if (object.forEach instanceof Function) {
			// the object implements a custom forEach method so use that
			object.forEach(block, context);
			return;
		} else if (typeof object == "string") {
			// the object is a string
			resolve = String;
		} else if (typeof object.length == "number") {
			// the object is array-like
			resolve = Array;
		}
		resolve.forEach(object, block, context);
	}
};

addreadyevent(sorttable.init);

