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