noalyss  Version-6.7.2
 All Data Structures Namespaces Files Functions Variables Enumerations
sorttable.js
Go to the documentation of this file.
00001 /**
00002  *
00003   SortTable
00004   version 2
00005   7th April 2007
00006   Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
00007 
00008   Instructions:
00009   Download this file
00010   Add <script src="sorttable.js"></script> to your HTML
00011   Add class="sortable" to any table you'd like to make sortable
00012   Click on the headers to sort
00013 
00014   Thanks to many, many people for contributions and suggestions.
00015   Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
00016   This basically means: do what you want with it.
00017 
00018 @note
00019 Documentation http://www.kryogenix.org/code/browser/sorttable/
00020 
00021 Show the default order
00022 example:
00023 <th class=" sorttable_sorted_reverse">
00024 ....<span id="sorttable_sortrevind">&nbsp;&blacktriangle;</span>
00025 <th class=" sorttable_sorted">
00026 ....<span id="sorttable_sortfwdind">&nbsp;&nbsp;&#x25BE;</span>
00027 
00028 Sort on date
00029 <td sorttable_customkey="<?=$row_bank['b_date']?>"> // format YYYYMMDD
00030 
00031 force as numeric (normally useless):
00032 <th class="sorttable_numeric">Part number</th>
00033 
00034 To avoid the sort on the last row, use tfoot
00035 
00036 */
00037 
00038 
00039 var stIsIE = /*@cc_on!@*/false;
00040 
00041 sorttable = {
00042   init: function() {
00043     // quit if this function has already been called
00044     if (arguments.callee.done) return;
00045     // flag this function so we don't do the same thing twice
00046     arguments.callee.done = true;
00047     // kill the timer
00048     if (_timer) clearInterval(_timer);
00049 
00050     if (!document.createElement || !document.getElementsByTagName) return;
00051 
00052     sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
00053 
00054     forEach(document.getElementsByTagName('table'), function(table) {
00055       if (table.className.search(/\bsortable\b/) != -1) {
00056         sorttable.makeSortable(table);
00057       }
00058     });
00059 
00060   },
00061 
00062   makeSortable: function(table) {
00063     if (table.getElementsByTagName('thead').length == 0) {
00064       // table doesn't have a tHead. Since it should have, create one and
00065       // put the first table row in it.
00066       the = document.createElement('thead');
00067       the.appendChild(table.rows[0]);
00068       table.insertBefore(the,table.firstChild);
00069     }
00070     // Safari doesn't support table.tHead, sigh
00071     if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
00072 
00073     if (table.tHead.rows.length != 1) return; // can't cope with two header rows
00074 
00075     // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
00076     // "total" rows, for example). This is B&R, since what you're supposed
00077     // to do is put them in a tfoot. So, if there are sortbottom rows,
00078     // for backwards compatibility, move them to tfoot (creating it if needed).
00079     sortbottomrows = [];
00080     for (var i=0; i<table.rows.length; i++) {
00081       if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
00082         sortbottomrows[sortbottomrows.length] = table.rows[i];
00083       }
00084     }
00085     if (sortbottomrows) {
00086       if (table.tFoot == null) {
00087         // table doesn't have a tfoot. Create one.
00088         tfo = document.createElement('tfoot');
00089         table.appendChild(tfo);
00090       }
00091       for (var i=0; i<sortbottomrows.length; i++) {
00092         tfo.appendChild(sortbottomrows[i]);
00093       }
00094       delete sortbottomrows;
00095     }
00096 
00097     // work through each column and calculate its type
00098     headrow = table.tHead.rows[0].cells;
00099     for (var i=0; i<headrow.length; i++) {
00100       // manually override the type with a sorttable_type attribute
00101       if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
00102         mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
00103         if (mtch) { override = mtch[1]; }
00104               if (mtch && typeof sorttable["sort_"+override] == 'function') {
00105                 headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
00106               } else {
00107                 headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
00108               }
00109               // make it clickable to sort
00110               headrow[i].sorttable_columnindex = i;
00111               headrow[i].sorttable_tbody = table.tBodies[0];
00112               dean_addEvent(headrow[i],"click", function(e) {
00113 
00114           if (this.className.search(/\bsorttable_sorted\b/) != -1) {
00115             // if we're already sorted by this column, just
00116             // reverse the table, which is quicker
00117             sorttable.reverse(this.sorttable_tbody);
00118             this.className = this.className.replace('sorttable_sorted',
00119                                                     'sorttable_sorted_reverse');
00120             this.removeChild(document.getElementById('sorttable_sortfwdind'));
00121             sortrevind = document.createElement('span');
00122             sortrevind.id = "sorttable_sortrevind";
00123             sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
00124             this.appendChild(sortrevind);
00125             return;
00126           }
00127           if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
00128             // if we're already sorted by this column in reverse, just
00129             // re-reverse the table, which is quicker
00130             sorttable.reverse(this.sorttable_tbody);
00131             this.className = this.className.replace('sorttable_sorted_reverse',
00132                                                     'sorttable_sorted');
00133             this.removeChild(document.getElementById('sorttable_sortrevind'));
00134             sortfwdind = document.createElement('span');
00135             sortfwdind.id = "sorttable_sortfwdind";
00136             sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
00137             this.appendChild(sortfwdind);
00138             return;
00139           }
00140 
00141           // remove sorttable_sorted classes
00142           theadrow = this.parentNode;
00143           forEach(theadrow.childNodes, function(cell) {
00144             if (cell.nodeType == 1) { // an element
00145               cell.className = cell.className.replace('sorttable_sorted_reverse','');
00146               cell.className = cell.className.replace('sorttable_sorted','');
00147             }
00148           });
00149           sortfwdind = document.getElementById('sorttable_sortfwdind');
00150           if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
00151           sortrevind = document.getElementById('sorttable_sortrevind');
00152           if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
00153 
00154           this.className += ' sorttable_sorted';
00155           sortfwdind = document.createElement('span');
00156           sortfwdind.id = "sorttable_sortfwdind";
00157           sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
00158           this.appendChild(sortfwdind);
00159 
00160                 // build an array to sort. This is a Schwartzian transform thing,
00161                 // i.e., we "decorate" each row with the actual sort key,
00162                 // sort based on the sort keys, and then put the rows back in order
00163                 // which is a lot faster because you only do getInnerText once per row
00164                 row_array = [];
00165                 col = this.sorttable_columnindex;
00166                 rows = this.sorttable_tbody.rows;
00167                 for (var j=0; j<rows.length; j++) {
00168                   row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
00169                 }
00170                 /* If you want a stable sort, uncomment the following line */
00171                 //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
00172                 /* and comment out this one */
00173                 row_array.sort(this.sorttable_sortfunction);
00174 
00175                 tb = this.sorttable_tbody;
00176                 for (var j=0; j<row_array.length; j++) {
00177                   tb.appendChild(row_array[j][1]);
00178                 }
00179 
00180                 delete row_array;
00181               });
00182             }
00183     }
00184   },
00185 
00186   guessType: function(table, column) {
00187     // guess the type of a column based on its first non-blank row
00188     sortfn = sorttable.sort_alpha;
00189     for (var i=0; i<table.tBodies[0].rows.length; i++) {
00190       text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
00191       if (text != '') {
00192         if (text.match(/^-?[�$�]?[\d,.]+%?$/)) {
00193           return sorttable.sort_numeric;
00194         }
00195         // check for a date: dd/mm/yyyy or dd/mm/yy
00196         // can have / or . or - as separator
00197         // can be mm/dd as well
00198         possdate = text.match(sorttable.DATE_RE)
00199         if (possdate) {
00200           // looks like a date
00201           first = parseInt(possdate[1]);
00202           second = parseInt(possdate[2]);
00203           if (first > 12) {
00204             // definitely dd/mm
00205             return sorttable.sort_ddmm;
00206           } else if (second > 12) {
00207             return sorttable.sort_mmdd;
00208           } else {
00209             // looks like a date, but we can't tell which, so assume
00210             // that it's dd/mm (English imperialism!) and keep looking
00211             sortfn = sorttable.sort_ddmm;
00212           }
00213         }
00214       }
00215     }
00216     return sortfn;
00217   },
00218 
00219   getInnerText: function(node) {
00220     // gets the text we want to use for sorting for a cell.
00221     // strips leading and trailing whitespace.
00222     // this is *not* a generic getInnerText function; it's special to sorttable.
00223     // for example, you can override the cell text with a customkey attribute.
00224     // it also gets .value for <input> fields.
00225 
00226     if (!node) return "";
00227 
00228     hasInputs = (typeof node.getElementsByTagName == 'function') &&
00229                  node.getElementsByTagName('input').length;
00230 
00231     if (node.getAttribute("sorttable_customkey") != null) {
00232       return node.getAttribute("sorttable_customkey");
00233     }
00234     else if (typeof node.textContent != 'undefined' && !hasInputs) {
00235       return node.textContent.replace(/^\s+|\s+$/g, '');
00236     }
00237     else if (typeof node.innerText != 'undefined' && !hasInputs) {
00238       return node.innerText.replace(/^\s+|\s+$/g, '');
00239     }
00240     else if (typeof node.text != 'undefined' && !hasInputs) {
00241       return node.text.replace(/^\s+|\s+$/g, '');
00242     }
00243     else {
00244       switch (node.nodeType) {
00245         case 3:
00246           if (node.nodeName.toLowerCase() == 'input') {
00247             return node.value.replace(/^\s+|\s+$/g, '');
00248           }
00249         case 4:
00250           return node.nodeValue.replace(/^\s+|\s+$/g, '');
00251           break;
00252         case 1:
00253         case 11:
00254           var innerText = '';
00255           for (var i = 0; i < node.childNodes.length; i++) {
00256             innerText += sorttable.getInnerText(node.childNodes[i]);
00257           }
00258           return innerText.replace(/^\s+|\s+$/g, '');
00259           break;
00260         default:
00261           return '';
00262       }
00263     }
00264   },
00265 
00266   reverse: function(tbody) {
00267     // reverse the rows in a tbody
00268     newrows = [];
00269     for (var i=0; i<tbody.rows.length; i++) {
00270       newrows[newrows.length] = tbody.rows[i];
00271     }
00272     for (var i=newrows.length-1; i>=0; i--) {
00273        tbody.appendChild(newrows[i]);
00274     }
00275     delete newrows;
00276   },
00277 
00278   /* sort functions
00279      each sort function takes two parameters, a and b
00280      you are comparing a[0] and b[0] */
00281   sort_numeric: function(a,b) {
00282     aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
00283     if (isNaN(aa)) aa = 0;
00284     bb = parseFloat(b[0].replace(/[^0-9.-]/g,''));
00285     if (isNaN(bb)) bb = 0;
00286     return aa-bb;
00287   },
00288   sort_alpha: function(a,b) {
00289     if (a[0]==b[0]) return 0;
00290     if (a[0]<b[0]) return -1;
00291     return 1;
00292   },
00293   sort_ddmm: function(a,b) {
00294     mtch = a[0].match(sorttable.DATE_RE);
00295     y = mtch[3]; m = mtch[2]; d = mtch[1];
00296     if (m.length == 1) m = '0'+m;
00297     if (d.length == 1) d = '0'+d;
00298     dt1 = y+m+d;
00299     mtch = b[0].match(sorttable.DATE_RE);
00300     y = mtch[3]; m = mtch[2]; d = mtch[1];
00301     if (m.length == 1) m = '0'+m;
00302     if (d.length == 1) d = '0'+d;
00303     dt2 = y+m+d;
00304     if (dt1==dt2) return 0;
00305     if (dt1<dt2) return -1;
00306     return 1;
00307   },
00308   sort_mmdd: function(a,b) {
00309     mtch = a[0].match(sorttable.DATE_RE);
00310     y = mtch[3]; d = mtch[2]; m = mtch[1];
00311     if (m.length == 1) m = '0'+m;
00312     if (d.length == 1) d = '0'+d;
00313     dt1 = y+m+d;
00314     mtch = b[0].match(sorttable.DATE_RE);
00315     y = mtch[3]; d = mtch[2]; m = mtch[1];
00316     if (m.length == 1) m = '0'+m;
00317     if (d.length == 1) d = '0'+d;
00318     dt2 = y+m+d;
00319     if (dt1==dt2) return 0;
00320     if (dt1<dt2) return -1;
00321     return 1;
00322   },
00323 
00324   shaker_sort: function(list, comp_func) {
00325     // A stable sort function to allow multi-level sorting of data
00326     // see: http://en.wikipedia.org/wiki/Cocktail_sort
00327     // thanks to Joseph Nahmias
00328     var b = 0;
00329     var t = list.length - 1;
00330     var swap = true;
00331 
00332     while(swap) {
00333         swap = false;
00334         for(var i = b; i < t; ++i) {
00335             if ( comp_func(list[i], list[i+1]) > 0 ) {
00336                 var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
00337                 swap = true;
00338             }
00339         } // for
00340         t--;
00341 
00342         if (!swap) break;
00343 
00344         for(var i = t; i > b; --i) {
00345             if ( comp_func(list[i], list[i-1]) < 0 ) {
00346                 var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
00347                 swap = true;
00348             }
00349         } // for
00350         b++;
00351 
00352     } // while(swap)
00353   }
00354 }
00355 
00356 /* ******************************************************************
00357    Supporting functions: bundled here to avoid depending on a library
00358    ****************************************************************** */
00359 
00360 // Dean Edwards/Matthias Miller/John Resig
00361 
00362 /* for Mozilla/Opera9 */
00363 if (document.addEventListener) {
00364     document.addEventListener("DOMContentLoaded", sorttable.init, false);
00365 }
00366 
00367 /* for Internet Explorer */
00368 /*@cc_on @*/
00369 /*@if (@_win32)
00370     document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
00371     var script = document.getElementById("__ie_onload");
00372     script.onreadystatechange = function() {
00373         if (this.readyState == "complete") {
00374             sorttable.init(); // call the onload handler
00375         }
00376     };
00377 /*@end @*/
00378 
00379 /* for Safari */
00380 if (/WebKit/i.test(navigator.userAgent)) { // sniff
00381     var _timer = setInterval(function() {
00382         if (/loaded|complete/.test(document.readyState)) {
00383             sorttable.init(); // call the onload handler
00384         }
00385     }, 10);
00386 }
00387 
00388 /* for other browsers */
00389 window.onload = sorttable.init;
00390 
00391 // written by Dean Edwards, 2005
00392 // with input from Tino Zijdel, Matthias Miller, Diego Perini
00393 
00394 // http://dean.edwards.name/weblog/2005/10/add-event/
00395 
00396 function dean_addEvent(element, type, handler) {
00397         if (element.addEventListener) {
00398                 element.addEventListener(type, handler, false);
00399         } else {
00400                 // assign each event handler a unique ID
00401                 if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
00402                 // create a hash table of event types for the element
00403                 if (!element.events) element.events = {};
00404                 // create a hash table of event handlers for each element/event pair
00405                 var handlers = element.events[type];
00406                 if (!handlers) {
00407                         handlers = element.events[type] = {};
00408                         // store the existing event handler (if there is one)
00409                         if (element["on" + type]) {
00410                                 handlers[0] = element["on" + type];
00411                         }
00412                 }
00413                 // store the event handler in the hash table
00414                 handlers[handler.$$guid] = handler;
00415                 // assign a global event handler to do all the work
00416                 element["on" + type] = handleEvent;
00417         }
00418 };
00419 // a counter used to create unique IDs
00420 dean_addEvent.guid = 1;
00421 
00422 function removeEvent(element, type, handler) {
00423         if (element.removeEventListener) {
00424                 element.removeEventListener(type, handler, false);
00425         } else {
00426                 // delete the event handler from the hash table
00427                 if (element.events && element.events[type]) {
00428                         delete element.events[type][handler.$$guid];
00429                 }
00430         }
00431 };
00432 
00433 function handleEvent(event) {
00434         var returnValue = true;
00435         // grab the event object (IE uses a global event object)
00436         event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
00437         // get a reference to the hash table of event handlers
00438         var handlers = this.events[event.type];
00439         // execute each event handler
00440         for (var i in handlers) {
00441                 this.$$handleEvent = handlers[i];
00442                 if (this.$$handleEvent(event) === false) {
00443                         returnValue = false;
00444                 }
00445         }
00446         return returnValue;
00447 };
00448 
00449 function fixEvent(event) {
00450         // add W3C standard event methods
00451         event.preventDefault = fixEvent.preventDefault;
00452         event.stopPropagation = fixEvent.stopPropagation;
00453         return event;
00454 };
00455 fixEvent.preventDefault = function() {
00456         this.returnValue = false;
00457 };
00458 fixEvent.stopPropagation = function() {
00459   this.cancelBubble = true;
00460 }
00461 
00462 // Dean's forEach: http://dean.edwards.name/base/forEach.js
00463 /*
00464         forEach, version 1.0
00465         Copyright 2006, Dean Edwards
00466         License: http://www.opensource.org/licenses/mit-license.php
00467 */
00468 
00469 // array-like enumeration
00470 if (!Array.forEach) { // mozilla already supports this
00471         Array.forEach = function(array, block, context) {
00472                 for (var i = 0; i < array.length; i++) {
00473                         block.call(context, array[i], i, array);
00474                 }
00475         };
00476 }
00477 
00478 // generic enumeration
00479 Function.prototype.forEach = function(object, block, context) {
00480         for (var key in object) {
00481                 if (typeof this.prototype[key] == "undefined") {
00482                         block.call(context, object[key], key, object);
00483                 }
00484         }
00485 };
00486 
00487 // character enumeration
00488 String.forEach = function(string, block, context) {
00489         Array.forEach(string.split(""), function(chr, index) {
00490                 block.call(context, chr, index, string);
00491         });
00492 };
00493 
00494 // globally resolve forEach enumeration
00495 var forEach = function(object, block, context) {
00496         if (object) {
00497                 var resolve = Object; // default
00498                 if (object instanceof Function) {
00499                         // functions have a "length" property
00500                         resolve = Function;
00501                 } else if (object.forEach instanceof Function) {
00502                         // the object implements a custom forEach method so use that
00503                         object.forEach(block, context);
00504                         return;
00505                 } else if (typeof object == "string") {
00506                         // the object is a string
00507                         resolve = String;
00508                 } else if (typeof object.length == "number") {
00509                         // the object is array-like
00510                         resolve = Array;
00511                 }
00512                 resolve.forEach(object, block, context);
00513         }
00514 };
00515 
 All Data Structures Namespaces Files Functions Variables Enumerations