(bug 36991) Fix jquery.tablesorter date sorting
[mediawiki.git] / resources / jquery / jquery.tablesorter.js
blob21e1f968e8e942aea464189582dc0ca231dd22b8
1 /**
2  * TableSorter for MediaWiki
3  *
4  * Written 2011 Leo Koppelkamm
5  * Based on tablesorter.com plugin, written (c) 2007 Christian Bach.
6  *
7  * Dual licensed under the MIT and GPL licenses:
8  * http://www.opensource.org/licenses/mit-license.php
9  * http://www.gnu.org/licenses/gpl.html
10  *
11  * Depends on mw.config (wgDigitTransformTable, wgMonthNames, wgMonthNamesShort,
12  * wgDefaultDateFormat, wgContentLanguage)
13  * Uses 'tableSorterCollation' in mw.config (if available)
14  */
15 /**
16  *
17  * @description Create a sortable table with multi-column sorting capabilitys
18  *
19  * @example $( 'table' ).tablesorter();
20  * @desc Create a simple tablesorter interface.
21  *
22  * @option String cssHeader ( optional ) A string of the class name to be appended
23  *         to sortable tr elements in the thead of the table. Default value:
24  *         "header"
25  *
26  * @option String cssAsc ( optional ) A string of the class name to be appended to
27  *         sortable tr elements in the thead on a ascending sort. Default value:
28  *         "headerSortUp"
29  *
30  * @option String cssDesc ( optional ) A string of the class name to be appended
31  *         to sortable tr elements in the thead on a descending sort. Default
32  *         value: "headerSortDown"
33  *
34  * @option String sortInitialOrder ( optional ) A string of the inital sorting
35  *         order can be asc or desc. Default value: "asc"
36  *
37  * @option String sortMultisortKey ( optional ) A string of the multi-column sort
38  *         key. Default value: "shiftKey"
39  *
40  * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
41  *         to use String.localeCampare method or not. Set to false.
42  *
43  * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
44  *         tablesorter should cancel selection of the table headers text.
45  *         Default value: true
46  *
47  * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
48  *         should display debuging information usefull for development.
49  *
50  * @type jQuery
51  *
52  * @name tablesorter
53  *
54  * @cat Plugins/Tablesorter
55  *
56  * @author Christian Bach/christian.bach@polyester.se
57  */
59 ( function( $ ) {
61         /* Local scope */
63         var     ts,
64                 parsers = [];
66         /* Parser utility functions */
68         function getParserById( name ) {
69                 var len = parsers.length;
70                 for ( var i = 0; i < len; i++ ) {
71                         if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
72                                 return parsers[i];
73                         }
74                 }
75                 return false;
76         }
78         function getElementText( node ) {
79                 var $node = $( node ),
80                         data = $node.attr( 'data-sort-value' );
81                 if ( data !== undefined ) {
82                         return data;
83                 } else {
84                         return $node.text();
85                 }
86         }
88         function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
89                 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
90                         return $.trim( getElementText( rows[rowIndex].cells[cellIndex] ) );
91                 } else {
92                         return '';
93                 }
94         }
96         function detectParserForColumn( table, rows, cellIndex ) {
97                 var     l = parsers.length,
98                         nodeValue,
99                         // Start with 1 because 0 is the fallback parser
100                         i = 1,
101                         rowIndex = 0,
102                         concurrent = 0,
103                         needed = ( rows.length > 4 ) ? 5 : rows.length;
105                 while( i < l ) {
106                         nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
107                         if ( nodeValue !== '') {
108                                 if ( parsers[i].is( nodeValue, table ) ) {
109                                         concurrent++;
110                                         rowIndex++;
111                                         if ( concurrent >= needed ) {
112                                                 // Confirmed the parser for multiple cells, let's return it
113                                                 return parsers[i];
114                                         }
115                                 } else {
116                                         // Check next parser, reset rows
117                                         i++;
118                                         rowIndex = 0;
119                                         concurrent = 0;
120                                 }
121                         } else {
122                                 // Empty cell
123                                 rowIndex++;
124                                 if ( rowIndex > rows.length ) {
125                                         rowIndex = 0;
126                                         i++;
127                                 }
128                         }
129                 }
131                 // 0 is always the generic parser (text)
132                 return parsers[0];
133         }
135         function buildParserCache( table, $headers ) {
136                 var     rows = table.tBodies[0].rows,
137                         sortType,
138                         parsers = [];
140                 if ( rows[0] ) {
142                         var     cells = rows[0].cells,
143                                 len = cells.length,
144                                 i, parser;
146                         for ( i = 0; i < len; i++ ) {
147                                 parser = false;
148                                 sortType = $headers.eq( i ).data( 'sort-type' );
149                                 if ( sortType !== undefined ) {
150                                         parser = getParserById( sortType );
151                                 }
153                                 if ( parser === false ) {
154                                         parser = detectParserForColumn( table, rows, i );
155                                 }
157                                 parsers.push( parser );
158                         }
159                 }
160                 return parsers;
161         }
163         /* Other utility functions */
165         function buildCache( table ) {
166                 var     totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
167                         totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
168                         parsers = table.config.parsers,
169                         cache = {
170                                 row: [],
171                                 normalized: []
172                         };
174                 for ( var i = 0; i < totalRows; ++i ) {
176                         // Add the table data to main data array
177                         var     $row = $( table.tBodies[0].rows[i] ),
178                                 cols = [];
180                         // if this is a child row, add it to the last row's children and
181                         // continue to the next row
182                         if ( $row.hasClass( table.config.cssChildRow ) ) {
183                                 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
184                                 // go to the next for loop
185                                 continue;
186                         }
188                         cache.row.push( $row );
190                         for ( var j = 0; j < totalCells; ++j ) {
191                                 cols.push( parsers[j].format( getElementText( $row[0].cells[j] ), table, $row[0].cells[j] ) );
192                         }
194                         cols.push( cache.normalized.length ); // add position for rowCache
195                         cache.normalized.push( cols );
196                         cols = null;
197                 }
199                 return cache;
200         }
202         function appendToTable( table, cache ) {
203                 var     row = cache.row,
204                         normalized = cache.normalized,
205                         totalRows = normalized.length,
206                         checkCell = ( normalized[0].length - 1 ),
207                         fragment = document.createDocumentFragment();
209                 for ( var i = 0; i < totalRows; i++ ) {
210                         var pos = normalized[i][checkCell];
212                         var l = row[pos].length;
214                         for ( var j = 0; j < l; j++ ) {
215                                 fragment.appendChild( row[pos][j] );
216                         }
218                 }
219                 table.tBodies[0].appendChild( fragment );
220         }
221         
222         /**
223          * Find all header rows in a thead-less table and put them in a <thead> tag.
224          * This only treats a row as a header row if it contains only <th>s (no <td>s)
225          * and if it is preceded entirely by header rows. The algorithm stops when
226          * it encounters the first non-header row.
227          * 
228          * After this, it will look at all rows at the bottom for footer rows
229          * And place these in a tfoot using similar rules.
230          * @param $table jQuery object for a <table>
231          */ 
232         function emulateTHeadAndFoot( $table ) {
233                 var $rows = $table.find( '> tbody > tr' );
234                 if( !$table.get(0).tHead ) {
235                         var $thead = $( '<thead>' );
236                         $rows.each( function() {
237                                 if ( $(this).children( 'td' ).length > 0 ) {
238                                         // This row contains a <td>, so it's not a header row
239                                         // Stop here
240                                         return false;
241                                 }
242                                 $thead.append( this );
243                         } );
244                         $table.find(' > tbody:first').before( $thead );
245                 }
246                 if( !$table.get(0).tFoot ) {
247                         var $tfoot = $( '<tfoot>' );
248                         var len = $rows.length;
249                         for ( var i = len-1; i >= 0; i-- ) {
250                                 if( $( $rows[i] ).children( 'td' ).length > 0 ){
251                                         break;
252                                 }
253                                 $tfoot.prepend( $( $rows[i] ));
254                         } 
255                         $table.append( $tfoot );
256                 }
257         }
259         function buildHeaders( table, msg ) {
260                 var     maxSeen = 0,
261                         longest,
262                         realCellIndex = 0,
263                         $tableHeaders = $( 'thead:eq(0) > tr', table );
264                 if ( $tableHeaders.length > 1 ) {
265                         $tableHeaders.each( function() {
266                                 if ( this.cells.length > maxSeen ) {
267                                         maxSeen = this.cells.length;
268                                         longest = this;
269                                 }
270                         });
271                         $tableHeaders = $( longest );
272                 }
273                 $tableHeaders = $tableHeaders.children( 'th' ).each( function( index ) {
274                         this.column = realCellIndex;
276                         var colspan = this.colspan;
277                         colspan = colspan ? parseInt( colspan, 10 ) : 1;
278                         realCellIndex += colspan;
280                         this.order = 0;
281                         this.count = 0;
283                         if ( $( this ).is( '.unsortable' ) ) {
284                                 this.sortDisabled = true;
285                         }
287                         if ( !this.sortDisabled ) {
288                                 var $th = $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
289                         }
291                         // add cell to headerList
292                         table.config.headerList[index] = this;
293                 } );
295                 return $tableHeaders;
297         }
299         function isValueInArray( v, a ) {
300                 var l = a.length;
301                 for ( var i = 0; i < l; i++ ) {
302                         if ( a[i][0] == v ) {
303                                 return true;
304                         }
305                 }
306                 return false;
307         }
309         function setHeadersCss( table, $headers, list, css, msg ) {
310                 // Remove all header information
311                 $headers.removeClass( css[0] ).removeClass( css[1] );
313                 var h = [];
314                 $headers.each( function( offset ) {
315                         if ( !this.sortDisabled ) {
316                                 h[this.column] = $( this );
317                         }
318                 } );
320                 var l = list.length;
321                 for ( var i = 0; i < l; i++ ) {
322                         h[ list[i][0] ].addClass( css[ list[i][1] ] ).attr( 'title', msg[ list[i][1] ] );
323                 }
324         }
326         function sortText( a, b ) {
327                 return ( (a < b) ? false : ((a > b) ? true : 0) );
328         }
330         function sortTextDesc( a, b ) {
331                 return ( (b < a) ? false : ((b > a) ? true : 0) );
332         }
334         function checkSorting( array1, array2, sortList ) {
335                 var col, fn, ret;
336                 for ( var i = 0, len = sortList.length; i < len; i++ ) {
337                         col = sortList[i][0];
338                         fn = ( sortList[i][1] ) ? sortTextDesc : sortText;
339                         ret = fn.call( this, array1[col], array2[col] );
340                         if ( ret !== 0 ) {
341                                 return ret;
342                         }
343                 }
344                 return ret;
345         }
347         // Merge sort algorithm
348         // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
349         function mergeSortHelper( array, begin, beginRight, end, sortList ) {
350                 for ( ; begin < beginRight; ++begin ) {
351                         if ( checkSorting( array[begin], array[beginRight], sortList ) ) {
352                                 var v = array[begin];
353                                 array[begin] = array[beginRight];
354                                 var begin2 = beginRight;
355                                 while ( begin2 + 1 < end && checkSorting( v, array[begin2 + 1], sortList ) ) {
356                                         var tmp = array[begin2];
357                                         array[begin2] = array[begin2 + 1];
358                                         array[begin2 + 1] = tmp;
359                                         ++begin2;
360                                 }
361                                 array[begin2] = v;
362                         }
363                 }
364         }
366         function mergeSort(array, begin, end, sortList) {
367                 var size = end - begin;
368                 if ( size < 2 ) {
369                         return;
370                 }
372                 var beginRight = begin + Math.floor(size / 2);
374                 mergeSort( array, begin, beginRight, sortList );
375                 mergeSort( array, beginRight, end, sortList );
376                 mergeSortHelper( array, begin, beginRight, end, sortList );
377         }
379         function multisort( table, sortList, cache ) {
380                 var i = sortList.length;
381                 mergeSort( cache.normalized, 0, cache.normalized.length, sortList );
383                 return cache;
384         }
386         function buildTransformTable() {
387                 var digits = '0123456789,.'.split( '' );
388                 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
389                 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
390                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
391                         ts.transformTable = false;
392                 } else {
393                         ts.transformTable = {};
395                         // Unpack the transform table
396                         var ascii = separatorTransformTable[0].split( "\t" ).concat( digitTransformTable[0].split( "\t" ) );
397                         var localised = separatorTransformTable[1].split( "\t" ).concat( digitTransformTable[1].split( "\t" ) );
399                         // Construct regex for number identification
400                         for ( var i = 0; i < ascii.length; i++ ) {
401                                 ts.transformTable[localised[i]] = ascii[i];
402                                 digits.push( $.escapeRE( localised[i] ) );
403                         }
404                 }
405                 var digitClass = '[' + digits.join( '', digits ) + ']';
407                 // We allow a trailing percent sign, which we just strip. This works fine
408                 // if percents and regular numbers aren't being mixed.
409                 ts.numberRegex = new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
410                 "|" + "[-+\u2212]?" + digitClass + "+[\\s\\xa0]*%?" + // Generic localised
411                 ")$", "i");
412         }
414         function buildDateTable() {
415                 var regex = [];
416                 ts.monthNames = {};
418                 for ( var i = 1; i < 13; i++ ) {
419                         var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
420                         ts.monthNames[name] = i;
421                         regex.push( $.escapeRE( name ) );
422                         name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
423                         ts.monthNames[name] = i;
424                         regex.push( $.escapeRE( name ) );
425                 }
427                 // Build piped string
428                 regex = regex.join( '|' );
430                 // Build RegEx
431                 // Any date formated with . , ' - or /
432                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
434                 // Written Month name, dmy
435                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
437                 // Written Month name, mdy
438                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
440         }
442         function explodeRowspans( $table ) {
443                 // Split multi row cells into multiple cells with the same content
444                 $table.find( '> tbody > tr > [rowspan]' ).each(function() {
445                         var rowSpan = this.rowSpan;
446                         this.rowSpan = 1;
447                         var cell = $( this );
448                         var next = cell.parent().nextAll();
449                         for ( var i = 0; i < rowSpan - 1; i++ ) {
450                                 var td = next.eq( i ).children( 'td' );
451                                 if ( !td.length ) {
452                                         next.eq( i ).append( cell.clone() );
453                                 } else if ( this.cellIndex === 0 ) {
454                                         td.eq( this.cellIndex ).before( cell.clone() );
455                                 } else {
456                                         td.eq( this.cellIndex - 1 ).after( cell.clone() );
457                                 }
458                         }
459                 });
460         }
462         function buildCollationTable() {
463                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
464                 ts.collationRegex = null;
465                 if ( ts.collationTable ) {
466                         var keys = [];
468                         // Build array of key names
469                         for ( var key in ts.collationTable ) {
470                                 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
471                                         keys.push(key);
472                                 }
473                         }
474                         if (keys.length) {
475                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
476                         }
477                 }
478         }
480         function cacheRegexs() {
481                 if ( ts.rgx ) {
482                         return;
483                 }
484                 ts.rgx = {
485                         IPAddress: [
486                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
487                         ],
488                         currency: [
489                                 new RegExp( /^[£$€?.]/),
490                                 new RegExp( /[£$€]/g)
491                         ],
492                         url: [
493                                 new RegExp( /^(https?|ftp|file):\/\/$/),
494                                 new RegExp( /(https?|ftp|file):\/\//)
495                         ],
496                         isoDate: [
497                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
498                         ],
499                         usLongDate: [
500                                 new RegExp( /^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/)
501                         ],
502                         time: [
503                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
504                         ]
505                 };
506         }
508         /* Public scope */
510         $.tablesorter = {
512                         defaultOptions: {
513                                 cssHeader: 'headerSort',
514                                 cssAsc: 'headerSortUp',
515                                 cssDesc: 'headerSortDown',
516                                 cssChildRow: 'expand-child',
517                                 sortInitialOrder: 'asc',
518                                 sortMultiSortKey: 'shiftKey',
519                                 sortLocaleCompare: false,
520                                 parsers: {},
521                                 widgets: [],
522                                 headers: {},
523                                 cancelSelection: true,
524                                 sortList: [],
525                                 headerList: [],
526                                 selectorHeaders: 'thead tr:eq(0) th',
527                                 debug: false
528                         },
530                         dateRegex: [],
531                         monthNames: {},
533                         /**
534                          * @param $tables {jQuery}
535                          * @param settings {Object} (optional)
536                          */
537                         construct: function( $tables, settings ) {
538                                 return $tables.each( function( i, table ) {
539                                         // Declare and cache.
540                                         var     $document, $headers, cache, config, sortOrder,
541                                                 $table = $( table ),
542                                                 shiftDown = 0,
543                                                 firstTime = true;
545                                         // Quit if no tbody
546                                         if ( !table.tBodies ) {
547                                                 return;
548                                         }
549                                         if ( !table.tHead ) {
550                                                 // No thead found. Look for rows with <th>s and
551                                                 // move them into a <thead> tag or a <tfoot> tag
552                                                 emulateTHeadAndFoot( $table );
553                                                 
554                                                 // Still no thead? Then quit
555                                                 if ( !table.tHead ) {
556                                                         return;
557                                                 }
558                                         }
559                                         $table.addClass( "jquery-tablesorter" );
561                                         // New config object.
562                                         table.config = {};
564                                         // Merge and extend.
565                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
567                                         // Save the settings where they read
568                                         $.data( table, 'tablesorter', config );
570                                         // Get the CSS class names, could be done else where.
571                                         var sortCSS = [ config.cssDesc, config.cssAsc ];
572                                         var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
574                                         // Build headers
575                                         $headers = buildHeaders( table, sortMsg );
577                                         // Grab and process locale settings
578                                         buildTransformTable();
579                                         buildDateTable();
580                                         buildCollationTable();
582                                         // Precaching regexps can bring 10 fold
583                                         // performance improvements in some browsers.
584                                         cacheRegexs();
586                                         // Apply event handling to headers
587                                         // this is too big, perhaps break it out?
588                                         $headers.click( function( e ) {
589                                                 if ( e.target.nodeName.toLowerCase() == 'a' ) {
590                                                         // The user clicked on a link inside a table header
591                                                         // Do nothing and let the default link click action continue
592                                                         return true;
593                                                 }
595                                                 if ( firstTime ) {
596                                                         firstTime = false;
598                                                         // Legacy fix of .sortbottoms
599                                                         // Wrap them inside inside a tfoot (because that's what they actually want to be) &
600                                                         // and put the <tfoot> at the end of the <table>
601                                                         var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
602                                                         if ( $sortbottoms.length ) {
603                                                                 var $tfoot = $table.children( 'tfoot' );
604                                                                 if ( $tfoot.length ) {
605                                                                         $tfoot.eq(0).prepend( $sortbottoms );
606                                                                 } else {
607                                                                         $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
608                                                                 }
609                                                         }
611                                                         explodeRowspans( $table );
612                                                         // try to auto detect column type, and store in tables config
613                                                         table.config.parsers = buildParserCache( table, $headers );
614                                                         // build the cache for the tbody cells
615                                                         cache = buildCache( table );
616                                                 }
617                                                 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
618                                                 if ( !table.sortDisabled && totalRows > 0 ) {
620                                                         // Cache jQuery object
621                                                         var $cell = $( this );
623                                                         // Get current column index
624                                                         var i = this.column;
626                                                         // Get current column sort order
627                                                         this.order = this.count % 2;
628                                                         this.count++;
630                                                         // User only wants to sort on one column
631                                                         if ( !e[config.sortMultiSortKey] ) {
632                                                                 // Flush the sort list
633                                                                 config.sortList = [];
634                                                                 // Add column to sort list
635                                                                 config.sortList.push( [i, this.order] );
637                                                         // Multi column sorting
638                                                         } else {
639                                                                 // The user has clicked on an already sorted column.
640                                                                 if ( isValueInArray( i, config.sortList ) ) {
641                                                                         // Reverse the sorting direction for all tables.
642                                                                         for ( var j = 0; j < config.sortList.length; j++ ) {
643                                                                                 var s = config.sortList[j],
644                                                                                         o = config.headerList[s[0]];
645                                                                                 if ( s[0] == i ) {
646                                                                                         o.count = s[1];
647                                                                                         o.count++;
648                                                                                         s[1] = o.count % 2;
649                                                                                 }
650                                                                         }
651                                                                 } else {
652                                                                         // Add column to sort list array
653                                                                         config.sortList.push( [i, this.order] );
654                                                                 }
655                                                         }
657                                                         // Set CSS for headers
658                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg );
659                                                         appendToTable(
660                                                                 $table[0], multisort( $table[0], config.sortList, cache )
661                                                         );
663                                                         // Stop normal event by returning false
664                                                         return false;
665                                                 }
667                                         // Cancel selection
668                                         } ).mousedown( function() {
669                                                 if ( config.cancelSelection ) {
670                                                         this.onselectstart = function() {
671                                                                 return false;
672                                                         };
673                                                         return false;
674                                                 }
675                                         } );
676                                 } );
677                         },
679                         addParser: function( parser ) {
680                                 var     l = parsers.length,
681                                         a = true;
682                                 for ( var i = 0; i < l; i++ ) {
683                                         if ( parsers[i].id.toLowerCase() == parser.id.toLowerCase() ) {
684                                                 a = false;
685                                         }
686                                 }
687                                 if ( a ) {
688                                         parsers.push( parser );
689                                 }
690                         },
692                         formatDigit: function( s ) {
693                                 if ( ts.transformTable !== false ) {
694                                         var     out = '',
695                                                 c;
696                                         for ( var p = 0; p < s.length; p++ ) {
697                                                 c = s.charAt(p);
698                                                 if ( c in ts.transformTable ) {
699                                                         out += ts.transformTable[c];
700                                                 } else {
701                                                         out += c;
702                                                 }
703                                         }
704                                         s = out;
705                                 }
706                                 var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
707                                 return ( isNaN(i)) ? 0 : i;
708                         },
710                         formatFloat: function( s ) {
711                                 var i = parseFloat(s);
712                                 return ( isNaN(i)) ? 0 : i;
713                         },
715                         formatInt: function( s ) {
716                                 var i = parseInt( s, 10 );
717                                 return ( isNaN(i)) ? 0 : i;
718                         },
720                         clearTableBody: function( table ) {
721                                 if ( $.browser.msie ) {
722                                         var empty = function( el ) {
723                                                 while ( el.firstChild ) {
724                                                         el.removeChild( el.firstChild );
725                                                 }
726                                         };
727                                         empty( table.tBodies[0] );
728                                 } else {
729                                         table.tBodies[0].innerHTML = '';
730                                 }
731                         }
732                 };
734         // Shortcut
735         ts = $.tablesorter;
737         // Register as jQuery prototype method
738         $.fn.tablesorter = function( settings ) {
739                 return ts.construct( this, settings );
740         };
742         // Add default parsers
743         ts.addParser( {
744                 id: 'text',
745                 is: function( s ) {
746                         return true;
747                 },
748                 format: function( s ) {
749                         s = $.trim( s.toLowerCase() );
750                         if ( ts.collationRegex ) {
751                                 var tsc = ts.collationTable;
752                                 s = s.replace( ts.collationRegex, function( match ) {
753                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
754                                         return r.toLowerCase();
755                                 } );
756                         }
757                         return s;
758                 },
759                 type: 'text'
760         } );
762         ts.addParser( {
763                 id: 'IPAddress',
764                 is: function( s ) {
765                         return ts.rgx.IPAddress[0].test(s);
766                 },
767                 format: function( s ) {
768                         var     a = s.split( '.' ),
769                                 r = '',
770                                 l = a.length;
771                         for ( var i = 0; i < l; i++ ) {
772                                 var item = a[i];
773                                 if ( item.length == 1 ) {
774                                         r += '00' + item;
775                                 } else if ( item.length == 2 ) {
776                                         r += '0' + item;
777                                 } else {
778                                         r += item;
779                                 }
780                         }
781                         return $.tablesorter.formatFloat(r);
782                 },
783                 type: 'numeric'
784         } );
786         ts.addParser( {
787                 id: 'currency',
788                 is: function( s ) {
789                         return ts.rgx.currency[0].test(s);
790                 },
791                 format: function( s ) {
792                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
793                 },
794                 type: 'numeric'
795         } );
797         ts.addParser( {
798                 id: 'url',
799                 is: function( s ) {
800                         return ts.rgx.url[0].test(s);
801                 },
802                 format: function( s ) {
803                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
804                 },
805                 type: 'text'
806         } );
808         ts.addParser( {
809                 id: 'isoDate',
810                 is: function( s ) {
811                         return ts.rgx.isoDate[0].test(s);
812                 },
813                 format: function( s ) {
814                         return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
815                         new RegExp( /-/g), '/')).getTime() : '0' );
816                 },
817                 type: 'numeric'
818         } );
820         ts.addParser( {
821                 id: 'usLongDate',
822                 is: function( s ) {
823                         return ts.rgx.usLongDate[0].test(s);
824                 },
825                 format: function( s ) {
826                         return $.tablesorter.formatFloat( new Date(s).getTime() );
827                 },
828                 type: 'numeric'
829         } );
831         ts.addParser( {
832                 id: 'date',
833                 is: function( s ) {
834                         return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
835                 },
836                 format: function( s, table ) {
837                         s = $.trim( s.toLowerCase() );
839                         var match;
840                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
841                                 if ( mw.config.get( 'wgDefaultDateFormat' ) == 'mdy' || mw.config.get( 'wgContentLanguage' ) == 'en' ) {
842                                         s = [ match[3], match[1], match[2] ];
843                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
844                                         s = [ match[3], match[2], match[1] ];
845                                 }
846                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
847                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
848                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
849                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
850                         } else {
851                                 // Should never get here
852                                 return '99999999';
853                         }
855                         // Pad Month and Day
856                         if ( s[1].length == 1 ) {
857                                 s[1] = '0' + s[1];
858                         }
859                         if ( s[2].length == 1 ) {
860                                 s[2] = '0' + s[2];
861                         }
863                         var y;
864                         if ( ( y = parseInt( s[0], 10) ) < 100 ) {
865                                 // Guestimate years without centuries
866                                 if ( y < 30 ) {
867                                         s[0] = 2000 + y;
868                                 } else {
869                                         s[0] = 1900 + y;
870                                 }
871                         }
872                         while ( s[0].length < 4 ) {
873                                 s[0] = '0' + s[0];
874                         }
875                         return parseInt( s.join( '' ), 10 );
876                 },
877                 type: 'numeric'
878         } );
880         ts.addParser( {
881                 id: 'time',
882                 is: function( s ) {
883                         return ts.rgx.time[0].test(s);
884                 },
885                 format: function( s ) {
886                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
887                 },
888                 type: 'numeric'
889         } );
891         ts.addParser( {
892                 id: 'number',
893                 is: function( s, table ) {
894                         return $.tablesorter.numberRegex.test( $.trim( s ));
895                 },
896                 format: function( s ) {
897                         return $.tablesorter.formatDigit(s);
898                 },
899                 type: 'numeric'
900         } );
902 } )( jQuery );