1/*
2  SortTable
3  version 2
4  7th April 2007
5  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
6
7  Instructions:
8  Download this file
9  Add <script src="sorttable.js"></script> to your HTML
10  Add class="sortable" to any table you'd like to make sortable
11  Click on the headers to sort
12
13  Thanks to many, many people for contributions and suggestions.
14  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
15  This basically means: do what you want with it.
16*/
17
18
19var stIsIE = /*@cc_on!@*/false;
20
21sorttable = {
22  init: function() {
23    // quit if this function has already been called
24    if (arguments.callee.done) return;
25    // flag this function so we don't do the same thing twice
26    arguments.callee.done = true;
27    // kill the timer
28    if (_timer) clearInterval(_timer);
29
30    if (!document.createElement || !document.getElementsByTagName) return;
31
32    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
33
34    forEach(document.getElementsByTagName('table'), function(table) {
35      if (table.className.search(/\bsortable\b/) != -1) {
36        sorttable.makeSortable(table);
37      }
38    });
39
40  },
41
42  makeSortable: function(table) {
43    if (table.getElementsByTagName('thead').length == 0) {
44      // table doesn't have a tHead. Since it should have, create one and
45      // put the first table row in it.
46      the = document.createElement('thead');
47      the.appendChild(table.rows[0]);
48      table.insertBefore(the,table.firstChild);
49    }
50    // Safari doesn't support table.tHead, sigh
51    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
52
53    if (table.tHead.rows.length != 1) return; // can't cope with two header rows
54
55    // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
56    // "total" rows, for example). This is B&R, since what you're supposed
57    // to do is put them in a tfoot. So, if there are sortbottom rows,
58    // for backwards compatibility, move them to tfoot (creating it if needed).
59    sortbottomrows = [];
60    for (var i=0; i<table.rows.length; i++) {
61      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
62        sortbottomrows[sortbottomrows.length] = table.rows[i];
63      }
64    }
65    if (sortbottomrows) {
66      if (table.tFoot == null) {
67        // table doesn't have a tfoot. Create one.
68        tfo = document.createElement('tfoot');
69        table.appendChild(tfo);
70      }
71      for (var i=0; i<sortbottomrows.length; i++) {
72        tfo.appendChild(sortbottomrows[i]);
73      }
74      delete sortbottomrows;
75    }
76
77    // work through each column and calculate its type
78    headrow = table.tHead.rows[0].cells;
79    for (var i=0; i<headrow.length; i++) {
80      // manually override the type with a sorttable_type attribute
81      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
82        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
83        if (mtch) { override = mtch[1]; }
84	      if (mtch && typeof sorttable["sort_"+override] == 'function') {
85	        headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
86	      } else {
87	        headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
88	      }
89	      // make it clickable to sort
90	      headrow[i].sorttable_columnindex = i;
91	      headrow[i].sorttable_tbody = table.tBodies[0];
92	      dean_addEvent(headrow[i],"click", function(e) {
93
94          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
95            // if we're already sorted by this column, just
96            // reverse the table, which is quicker
97            sorttable.reverse(this.sorttable_tbody);
98            this.className = this.className.replace('sorttable_sorted',
99                                                    'sorttable_sorted_reverse');
100            this.removeChild(document.getElementById('sorttable_sortfwdind'));
101            sortrevind = document.createElement('span');
102            sortrevind.id = "sorttable_sortrevind";
103            //sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
104            this.appendChild(sortrevind);
105            adjust_column_backColor();
106            return;
107          }
108          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
109            // if we're already sorted by this column in reverse, just
110            // re-reverse the table, which is quicker
111            sorttable.reverse(this.sorttable_tbody);
112            this.className = this.className.replace('sorttable_sorted_reverse',
113                                                    'sorttable_sorted');
114            this.removeChild(document.getElementById('sorttable_sortrevind'));
115            sortfwdind = document.createElement('span');
116            sortfwdind.id = "sorttable_sortfwdind";
117            //sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
118            this.appendChild(sortfwdind);
119            adjust_column_backColor();
120            return;
121          }
122
123          // remove sorttable_sorted classes
124          theadrow = this.parentNode;
125          forEach(theadrow.childNodes, function(cell) {
126            if (cell.nodeType == 1) { // an element
127              cell.className = cell.className.replace('sorttable_sorted_reverse','');
128              cell.className = cell.className.replace('sorttable_sorted','');
129            }
130          });
131          sortfwdind = document.getElementById('sorttable_sortfwdind');
132          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
133          sortrevind = document.getElementById('sorttable_sortrevind');
134          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
135
136          this.className += ' sorttable_sorted';
137          sortfwdind = document.createElement('span');
138          sortfwdind.id = "sorttable_sortfwdind";
139          //sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
140          this.appendChild(sortfwdind);
141
142	        // build an array to sort. This is a Schwartzian transform thing,
143	        // i.e., we "decorate" each row with the actual sort key,
144	        // sort based on the sort keys, and then put the rows back in order
145	        // which is a lot faster because you only do getInnerText once per row
146	        row_array = [];
147	        col = this.sorttable_columnindex;
148	        rows = this.sorttable_tbody.rows;
149	        for (var j=0; j<rows.length; j++) {
150	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
151	        }
152	        /* If you want a stable sort, uncomment the following line */
153	        //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
154	        /* and comment out this one */
155	        row_array.sort(this.sorttable_sortfunction);
156
157	        tb = this.sorttable_tbody;
158	        for (var j=0; j<row_array.length; j++) {
159	          tb.appendChild(row_array[j][1]);
160	        }
161
162            adjust_column_backColor();
163	        delete row_array;
164
165	      });
166	    }
167    }
168  },
169
170  guessType: function(table, column) {
171    // guess the type of a column based on its first non-blank row
172    sortfn = sorttable.sort_alpha;
173    for (var i=0; i<table.tBodies[0].rows.length; i++) {
174      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
175      if (text != '') {
176        if(text.match(/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/)) {
177            return sorttable.sort_ipaddr;
178        }
179
180        if (text.match(/^-?[�G$?]?[\d,.]+%?$/)) {
181          return sorttable.sort_numeric;
182        }
183        // check for a date: dd/mm/yyyy or dd/mm/yy
184        // can have / or . or - as separator
185        // can be mm/dd as well
186        possdate = text.match(sorttable.DATE_RE)
187        if (possdate) {
188          // looks like a date
189          first = parseInt(possdate[1]);
190          second = parseInt(possdate[2]);
191          if (first > 12) {
192            // definitely dd/mm
193            return sorttable.sort_ddmm;
194          } else if (second > 12) {
195            return sorttable.sort_mmdd;
196          } else {
197            // looks like a date, but we can't tell which, so assume
198            // that it's dd/mm (English imperialism!) and keep looking
199            sortfn = sorttable.sort_ddmm;
200          }
201        }
202      }
203    }
204    return sortfn;
205  },
206
207  getInnerText: function(node) {
208    // gets the text we want to use for sorting for a cell.
209    // strips leading and trailing whitespace.
210    // this is *not* a generic getInnerText function; it's special to sorttable.
211    // for example, you can override the cell text with a customkey attribute.
212    // it also gets .value for <input> fields.
213
214    hasInputs = (typeof node.getElementsByTagName == 'function') &&
215                 node.getElementsByTagName('input').length;
216
217    if (node.getAttribute("sorttable_customkey") != null) {
218      return node.getAttribute("sorttable_customkey");
219    }
220    else if (typeof node.textContent != 'undefined' && !hasInputs) {
221      return node.textContent.replace(/^\s+|\s+$/g, '');
222    }
223    else if (typeof node.innerText != 'undefined' && !hasInputs) {
224      return node.innerText.replace(/^\s+|\s+$/g, '');
225    }
226    else if (typeof node.text != 'undefined' && !hasInputs) {
227      return node.text.replace(/^\s+|\s+$/g, '');
228    }
229    else {
230      switch (node.nodeType) {
231        case 3:
232          if (node.nodeName.toLowerCase() == 'input') {
233            return node.value.replace(/^\s+|\s+$/g, '');
234          }
235        case 4:
236          return node.nodeValue.replace(/^\s+|\s+$/g, '');
237          break;
238        case 1:
239        case 11:
240          var innerText = '';
241          for (var i = 0; i < node.childNodes.length; i++) {
242            innerText += sorttable.getInnerText(node.childNodes[i]);
243          }
244          return innerText.replace(/^\s+|\s+$/g, '');
245          break;
246        default:
247          return '';
248      }
249    }
250  },
251
252  reverse: function(tbody) {
253    // reverse the rows in a tbody
254    newrows = [];
255    for (var i=0; i<tbody.rows.length; i++) {
256      newrows[newrows.length] = tbody.rows[i];
257    }
258    for (var i=newrows.length-1; i>=0; i--) {
259       tbody.appendChild(newrows[i]);
260    }
261    delete newrows;
262  },
263
264  /* sort functions
265     each sort function takes two parameters, a and b
266     you are comparing a[0] and b[0] */
267  sort_numeric: function(a,b) {
268    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
269    if (isNaN(aa)) aa = 0;
270    bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
271    if (isNaN(bb)) bb = 0;
272    return aa-bb;
273  },
274  sort_alpha: function(a,b) {
275    if (a[0]==b[0]) return 0;
276    if (a[0]<b[0]) return -1;
277    return 1;
278  },
279  sort_ddmm: function(a,b) {
280    mtch = a[0].match(sorttable.DATE_RE);
281    y = mtch[3]; m = mtch[2]; d = mtch[1];
282    if (m.length == 1) m = '0'+m;
283    if (d.length == 1) d = '0'+d;
284    dt1 = y+m+d;
285    mtch = b[0].match(sorttable.DATE_RE);
286    y = mtch[3]; m = mtch[2]; d = mtch[1];
287    if (m.length == 1) m = '0'+m;
288    if (d.length == 1) d = '0'+d;
289    dt2 = y+m+d;
290    if (dt1==dt2) return 0;
291    if (dt1<dt2) return -1;
292    return 1;
293  },
294  sort_mmdd: function(a,b) {
295    mtch = a[0].match(sorttable.DATE_RE);
296    y = mtch[3]; d = mtch[2]; m = mtch[1];
297    if (m.length == 1) m = '0'+m;
298    if (d.length == 1) d = '0'+d;
299    dt1 = y+m+d;
300    mtch = b[0].match(sorttable.DATE_RE);
301    y = mtch[3]; d = mtch[2]; m = mtch[1];
302    if (m.length == 1) m = '0'+m;
303    if (d.length == 1) d = '0'+d;
304    dt2 = y+m+d;
305    if (dt1==dt2) return 0;
306    if (dt1<dt2) return -1;
307    return 1;
308  },
309  sort_ipaddr: function(a,b) {
310	if(a[0] == "--")
311		return 1;
312	if(b[0] == "--")
313		return -1;
314
315    var aa = a[0].split("."),
316	r1 = "",
317	l1 = aa.length;
318    var bb = b[0].split("."),
319	r2 = "",
320	l2 = bb.length;
321	for (var i = 0; i < l1; i++) {
322		var item1 = aa[i];
323		var item2 = bb[i];
324		if (item1.length == 2) {
325			r1 += "0" + item1;
326		} else if (item1.length == 1) {
327			r1 += "00" + item1;
328		} else {
329			r1 += item1;
330		}
331		if (item2.length == 2) {
332			r2 += "0" + item2;
333		} else if (item2.length == 1) {
334			r2 += "00" + item2;
335		} else {
336			r2 += item2;
337		}
338	}
339	if(r1==r2) return 0;
340	if(r1<r2) return -1;
341	return 1;
342  },
343
344  shaker_sort: function(list, comp_func) {
345    // A stable sort function to allow multi-level sorting of data
346    // see: http://en.wikipedia.org/wiki/Cocktail_sort
347    // thanks to Joseph Nahmias
348    var b = 0;
349    var t = list.length - 1;
350    var swap = true;
351
352    while(swap) {
353        swap = false;
354        for(var i = b; i < t; ++i) {
355            if ( comp_func(list[i], list[i+1]) > 0 ) {
356                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
357                swap = true;
358            }
359        } // for
360        t--;
361
362        if (!swap) break;
363
364        for(var i = t; i > b; --i) {
365            if ( comp_func(list[i], list[i-1]) < 0 ) {
366                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
367                swap = true;
368            }
369        } // for
370        b++;
371
372    } // while(swap)
373  }
374}
375
376/* ******************************************************************
377   Supporting functions: bundled here to avoid depending on a library
378   ****************************************************************** */
379
380// Dean Edwards/Matthias Miller/John Resig
381
382/* for Mozilla/Opera9 */
383if (document.addEventListener) {
384    document.addEventListener("DOMContentLoaded", sorttable.init, false);
385}
386
387/* for Internet Explorer */
388/*@cc_on @*/
389/*@if (@_win32)
390    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
391    var script = document.getElementById("__ie_onload");
392    script.onreadystatechange = function() {
393        if (this.readyState == "complete") {
394            sorttable.init(); // call the onload handler
395        }
396    };
397/*@end @*/
398
399/* for Safari */
400if (/WebKit/i.test(navigator.userAgent)) { // sniff
401    var _timer = setInterval(function() {
402        if (/loaded|complete/.test(document.readyState)) {
403            sorttable.init(); // call the onload handler
404        }
405    }, 10);
406}
407
408/* for other browsers */
409window.onload = sorttable.init;
410
411// written by Dean Edwards, 2005
412// with input from Tino Zijdel, Matthias Miller, Diego Perini
413
414// http://dean.edwards.name/weblog/2005/10/add-event/
415
416function dean_addEvent(element, type, handler) {
417	if (element.addEventListener) {
418		element.addEventListener(type, handler, false);
419	} else {
420		// assign each event handler a unique ID
421		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
422		// create a hash table of event types for the element
423		if (!element.events) element.events = {};
424		// create a hash table of event handlers for each element/event pair
425		var handlers = element.events[type];
426		if (!handlers) {
427			handlers = element.events[type] = {};
428			// store the existing event handler (if there is one)
429			if (element["on" + type]) {
430				handlers[0] = element["on" + type];
431			}
432		}
433		// store the event handler in the hash table
434		handlers[handler.$$guid] = handler;
435		// assign a global event handler to do all the work
436		element["on" + type] = handleEvent;
437	}
438};
439// a counter used to create unique IDs
440dean_addEvent.guid = 1;
441
442function removeEvent(element, type, handler) {
443	if (element.removeEventListener) {
444		element.removeEventListener(type, handler, false);
445	} else {
446		// delete the event handler from the hash table
447		if (element.events && element.events[type]) {
448			delete element.events[type][handler.$$guid];
449		}
450	}
451};
452
453function handleEvent(event) {
454	var returnValue = true;
455	// grab the event object (IE uses a global event object)
456	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
457	// get a reference to the hash table of event handlers
458	var handlers = this.events[event.type];
459	// execute each event handler
460	for (var i in handlers) {
461		this.$$handleEvent = handlers[i];
462		if (this.$$handleEvent(event) === false) {
463			returnValue = false;
464		}
465	}
466	return returnValue;
467};
468
469function fixEvent(event) {
470	// add W3C standard event methods
471	event.preventDefault = fixEvent.preventDefault;
472	event.stopPropagation = fixEvent.stopPropagation;
473	return event;
474};
475fixEvent.preventDefault = function() {
476	this.returnValue = false;
477};
478fixEvent.stopPropagation = function() {
479  this.cancelBubble = true;
480}
481
482// Dean's forEach: http://dean.edwards.name/base/forEach.js
483/*
484	forEach, version 1.0
485	Copyright 2006, Dean Edwards
486	License: http://www.opensource.org/licenses/mit-license.php
487*/
488
489// array-like enumeration
490if (!Array.forEach) { // mozilla already supports this
491	Array.forEach = function(array, block, context) {
492		for (var i = 0; i < array.length; i++) {
493			block.call(context, array[i], i, array);
494		}
495	};
496}
497
498// generic enumeration
499Function.prototype.forEach = function(object, block, context) {
500	for (var key in object) {
501		if (typeof this.prototype[key] == "undefined") {
502			block.call(context, object[key], key, object);
503		}
504	}
505};
506
507// character enumeration
508String.forEach = function(string, block, context) {
509	Array.forEach(string.split(""), function(chr, index) {
510		block.call(context, chr, index, string);
511	});
512};
513
514// globally resolve forEach enumeration
515var forEach = function(object, block, context) {
516	if (object) {
517		var resolve = Object; // default
518		if (object instanceof Function) {
519			// functions have a "length" property
520			resolve = Function;
521		} else if (object.forEach instanceof Function) {
522			// the object implements a custom forEach method so use that
523			object.forEach(block, context);
524			return;
525		} else if (typeof object == "string") {
526			// the object is a string
527			resolve = String;
528		} else if (typeof object.length == "number") {
529			// the object is array-like
530			resolve = Array;
531		}
532		resolve.forEach(object, block, context);
533	}
534};
535