PageSourceSearch

https://www.borderstates.com/_ui/responsive/common/js/sorttable.js

js borderstates.com collected 2026-10-03 21:44:21 UTC 16,900 bytes, 496 lines download raw bytes

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", sorttable.innerSortFunction = 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            return;
106          }
107          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
108            // if we're already sorted by this column in reverse, just
109            // re-reverse the table, which is quicker
110            sorttable.reverse(this.sorttable_tbody);
111            this.className = this.className.replace('sorttable_sorted_reverse',
112                                                    'sorttable_sorted');
113            this.removeChild(document.getElementById('sorttable_sortrevind'));
114            sortfwdind = document.createElement('span');
115            sortfwdind.id = "sorttable_sortfwdind";
116            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
117            this.appendChild(sortfwdind);
118            return;
119          }
120
121          // remove sorttable_sorted classes
122          theadrow = this.parentNode;
123          forEach(theadrow.childNodes, function(cell) {
124            if (cell.nodeType == 1) { // an element
125              cell.className = cell.className.replace('sorttable_sorted_reverse','');
126              cell.className = cell.className.replace('sorttable_sorted','');
127            }
128          });
129          sortfwdind = document.getElementById('sorttable_sortfwdind');
130          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
131          sortrevind = document.getElementById('sorttable_sortrevind');
132          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
133
134          this.className += ' sorttable_sorted';
135          sortfwdind = document.createElement('span');
136          sortfwdind.id = "sorttable_sortfwdind";
137          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
138          this.appendChild(sortfwdind);
139
140	        // build an array to sort. This is a Schwartzian transform thing,
141	        // i.e., we "decorate" each row with the actual sort key,
142	        // sort based on the sort keys, and then put the rows back in order
143	        // which is a lot faster because you only do getInnerText once per row
144	        row_array = [];
145	        col = this.sorttable_columnindex;
146	        rows = this.sorttable_tbody.rows;
147	        for (var j=0; j<rows.length; j++) {
148	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
149	        }
150	        /* If you want a stable sort, uncomment the following line */
151	        //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
152	        /* and comment out this one */
153	        row_array.sort(this.sorttable_sortfunction);
154
155	        tb = this.sorttable_tbody;
156	        for (var j=0; j<row_array.length; j++) {
157	          tb.appendChild(row_array[j][1]);
158	        }
159
160	        delete row_array;
161	      });
162	    }
163    }
164  },
165
166  guessType: function(table, column) {
167    // guess the type of a column based on its first non-blank row
168    sortfn = sorttable.sort_alpha;
169    for (var i=0; i<table.tBodies[0].rows.length; i++) {
170      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
171      if (text != '') {
172        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
173          return sorttable.sort_numeric;
174        }
175        // check for a date: dd/mm/yyyy or dd/mm/yy
176        // can have / or . or - as separator
177        // can be mm/dd as well
178        possdate = text.match(sorttable.DATE_RE)
179        if (possdate) {
180          // looks like a date
181          first = parseInt(possdate[1]);
182          second = parseInt(possdate[2]);
183          if (first > 12) {
184            // definitely dd/mm
185            return sorttable.sort_ddmm;
186          } else if (second > 12) {
187            return sorttable.sort_mmdd;
188          } else {
189            // looks like a date, but we can't tell which, so assume
190            // that it's dd/mm (English imperialism!) and keep looking
191            sortfn = sorttable.sort_ddmm;
192          }
193        }
194      }
195    }
196    return sortfn;
197  },
198
199  getInnerText: function(node) {
200    // gets the text we want to use for sorting for a cell.
201    // strips leading and trailing whitespace.
202    // this is *not* a generic getInnerText function; it's special to sorttable.
203    // for example, you can override the cell text with a customkey attribute.
204    // it also gets .value for <input> fields.
205
206    if (!node) return "";
207
208    hasInputs = (typeof node.getElementsByTagName == 'function') &&
209                 node.getElementsByTagName('input').length;
210
211    if (node.getAttribute("sorttable_customkey") != null) {
212      return node.getAttribute("sorttable_customkey");
213    }
214    else if (typeof node.textContent != 'undefined' && !hasInputs) {
215      return node.textContent.replace(/^\s+|\s+$/g, '');
216    }
217    else if (typeof node.innerText != 'undefined' && !hasInputs) {
218      return node.innerText.replace(/^\s+|\s+$/g, '');
219    }
220    else if (typeof node.text != 'undefined' && !hasInputs) {
221      return node.text.replace(/^\s+|\s+$/g, '');
222    }
223    else {
224      switch (node.nodeType) {
225        case 3:
226          if (node.nodeName.toLowerCase() == 'input') {
227            return node.value.replace(/^\s+|\s+$/g, '');
228          }
229        case 4:
230          return node.nodeValue.replace(/^\s+|\s+$/g, '');
231          break;
232        case 1:
233        case 11:
234          var innerText = '';
235          for (var i = 0; i < node.childNodes.length; i++) {
236            innerText += sorttable.getInnerText(node.childNodes[i]);
237          }
238          return innerText.replace(/^\s+|\s+$/g, '');
239          break;
240        default:
241          return '';
242      }
243    }
244  },
245
246  reverse: function(tbody) {
247    // reverse the rows in a tbody
248    newrows = [];
249    for (var i=0; i<tbody.rows.length; i++) {
250      newrows[newrows.length] = tbody.rows[i];
251    }
252    for (var i=newrows.length-1; i>=0; i--) {
253       tbody.appendChild(newrows[i]);
254    }
255    delete newrows;
256  },
257
258  /* sort functions
259     each sort function takes two parameters, a and b
260     you are comparing a[0] and b[0] */
261  sort_numeric: function(a,b) {
262    console.log(this);
263    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
264    if (isNaN(aa)) aa = 0;
265    bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
266    if (isNaN(bb)) bb = 0;
267    return aa-bb;
268  },
269  sort_alpha: function(a,b) {
270    if (a[0]==b[0]) return 0;
271    if (a[0]<b[0]) return -1;
272    return 1;
273  },
274  sort_ddmm: function(a,b) {
275    mtch = a[0].match(sorttable.DATE_RE);
276    y = mtch[3]; m = mtch[2]; d = mtch[1];
277    if (m.length == 1) m = '0'+m;
278    if (d.length == 1) d = '0'+d;
279    dt1 = y+m+d;
280    mtch = b[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    dt2 = y+m+d;
285    if (dt1==dt2) return 0;
286    if (dt1<dt2) return -1;
287    return 1;
288  },
289  sort_mmdd: function(a,b) {
290    mtch = a[0].match(sorttable.DATE_RE);
291    y = mtch[3]; d = mtch[2]; m = mtch[1];
292    if (m.length == 1) m = '0'+m;
293    if (d.length == 1) d = '0'+d;
294    dt1 = y+m+d;
295    mtch = b[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    dt2 = y+m+d;
300    if (dt1==dt2) return 0;
301    if (dt1<dt2) return -1;
302    return 1;
303  },
304
305  shaker_sort: function(list, comp_func) {
306    // A stable sort function to allow multi-level sorting of data
307    // see: http://en.wikipedia.org/wiki/Cocktail_sort
308    // thanks to Joseph Nahmias
309    var b = 0;
310    var t = list.length - 1;
311    var swap = true;
312
313    while(swap) {
314        swap = false;
315        for(var i = b; i < t; ++i) {
316            if ( comp_func(list[i], list[i+1]) > 0 ) {
317                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
318                swap = true;
319            }
320        } // for
321        t--;
322
323        if (!swap) break;
324
325        for(var i = t; i > b; --i) {
326            if ( comp_func(list[i], list[i-1]) < 0 ) {
327                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
328                swap = true;
329            }
330        } // for
331        b++;
332
333    } // while(swap)
334  }
335}
336
337/* ******************************************************************
338   Supporting functions: bundled here to avoid depending on a library
339   ****************************************************************** */
340
341// Dean Edwards/Matthias Miller/John Resig
342
343/* for Mozilla/Opera9 */
344if (document.addEventListener) {
345    document.addEventListener("DOMContentLoaded", sorttable.init, false);
346}
347
348/* for Internet Explorer */
349/*@cc_on @*/
350/*@if (@_win32)
351    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
352    var script = document.getElementById("__ie_onload");
353    script.onreadystatechange = function() {
354        if (this.readyState == "complete") {
355            sorttable.init(); // call the onload handler
356        }
357    };
358/*@end @*/
359
360/* for Safari */
361if (/WebKit/i.test(navigator.userAgent)) { // sniff
362    var _timer = setInterval(function() {
363        if (/loaded|complete/.test(document.readyState)) {
364            sorttable.init(); // call the onload handler
365        }
366    }, 10);
367}
368
369/* for other browsers */
370window.onload = sorttable.init;
371
372// written by Dean Edwards, 2005
373// with input from Tino Zijdel, Matthias Miller, Diego Perini
374
375// http://dean.edwards.name/weblog/2005/10/add-event/
376
377function dean_addEvent(element, type, handler) {
378	if (element.addEventListener) {
379		element.addEventListener(type, handler, false);
380	} else {
381		// assign each event handler a unique ID
382		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
383		// create a hash table of event types for the element
384		if (!element.events) element.events = {};
385		// create a hash table of event handlers for each element/event pair
386		var handlers = element.events[type];
387		if (!handlers) {
388			handlers = element.events[type] = {};
389			// store the existing event handler (if there is one)
390			if (element["on" + type]) {
391				handlers[0] = element["on" + type];
392			}
393		}
394		// store the event handler in the hash table
395		handlers[handler.$$guid] = handler;
396		// assign a global event handler to do all the work
397		element["on" + type] = handleEvent;
398	}
399};
400// a counter used to create unique IDs
401dean_addEvent.guid = 1;
402
403function removeEvent(element, type, handler) {
404	if (element.removeEventListener) {
405		element.removeEventListener(type, handler, false);
406	} else {
407		// delete the event handler from the hash table
408		if (element.events && element.events[type]) {
409			delete element.events[type][handler.$$guid];
410		}
411	}
412};
413
414function handleEvent(event) {
415	var returnValue = true;
416	// grab the event object (IE uses a global event object)
417	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
418	// get a reference to the hash table of event handlers
419	var handlers = this.events[event.type];
420	// execute each event handler
421	for (var i in handlers) {
422		this.$$handleEvent = handlers[i];
423		if (this.$$handleEvent(event) === false) {
424			returnValue = false;
425		}
426	}
427	return returnValue;
428};
429
430function fixEvent(event) {
431	// add W3C standard event methods
432	event.preventDefault = fixEvent.preventDefault;
433	event.stopPropagation = fixEvent.stopPropagation;
434	return event;
435};
436fixEvent.preventDefault = function() {
437	this.returnValue = false;
438};
439fixEvent.stopPropagation = function() {
440  this.cancelBubble = true;
441}
442
443// Dean's forEach: http://dean.edwards.name/base/forEach.js
444/*
445	forEach, version 1.0
446	Copyright 2006, Dean Edwards
447	License: http://www.opensource.org/licenses/mit-license.php
448*/
449
450// array-like enumeration
451if (!Array.forEach) { // mozilla already supports this
452	Array.forEach = function(array, block, context) {
453		for (var i = 0; i < array.length; i++) {
454			block.call(context, array[i], i, array);
455		}
456	};
457}
458
459// generic enumeration
460Function.prototype.forEach = function(object, block, context) {
461	for (var key in object) {
462		if (typeof this.prototype[key] == "undefined") {
463			block.call(context, object[key], key, object);
464		}
465	}
466};
467
468// character enumeration
469String.forEach = function(string, block, context) {
470	Array.forEach(string.split(""), function(chr, index) {
471		block.call(context, chr, index, string);
472	});
473};
474
475// globally resolve forEach enumeration
476var forEach = function(object, block, context) {
477	if (object) {
478		var resolve = Object; // default
479		if (object instanceof Function) {
480			// functions have a "length" property
481			resolve = Function;
482		} else if (object.forEach instanceof Function) {
483			// the object implements a custom forEach method so use that
484			object.forEach(block, context);
485			return;
486		} else if (typeof object == "string") {
487			// the object is a string
488			resolve = String;
489		} else if (typeof object.length == "number") {
490			// the object is array-like
491			resolve = Array;
492		}
493		resolve.forEach(object, block, context);
494	}
495};
496

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.