Update jquery.tablesorter for r97145: emulate <thead> if there is no <thead> in the...
[mediawiki.git] / resources / jquery / jquery.tablesorter.js
blobc17f3f2943030d3701a3d346c3b7518cc6c3f6a5
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          * @param $table jQuery object for a <table>
228          */ 
229         function emulateTHead( $table ) {
230                 var $thead = $( '<thead>' );
231                 $table.find( 'tr' ).each( function() {
232                         if ( $(this).find( 'td' ).length > 0 ) {
233                                 // This row contains a <td>, so it's not a header row
234                                 // Stop here
235                                 return false;
236                         }
237                         $thead.append( this );
238                 } );
239                 $table.prepend( $thead );
240         }
242         function buildHeaders( table, msg ) {
243                 var     maxSeen = 0,
244                         longest,
245                         realCellIndex = 0,
246                         $tableHeaders = $( 'thead:eq(0) tr', table );
247                 if ( $tableHeaders.length > 1 ) {
248                         $tableHeaders.each( function() {
249                                 if ( this.cells.length > maxSeen ) {
250                                         maxSeen = this.cells.length;
251                                         longest = this;
252                                 }
253                         });
254                         $tableHeaders = $( longest );
255                 }
256                 $tableHeaders = $tableHeaders.find( 'th' ).each( function( index ) {
257                         this.column = realCellIndex;
259                         var colspan = this.colspan;
260                         colspan = colspan ? parseInt( colspan, 10 ) : 1;
261                         realCellIndex += colspan;
263                         this.order = 0;
264                         this.count = 0;
266                         if ( $( this ).is( '.unsortable' ) ) {
267                                 this.sortDisabled = true;
268                         }
270                         if ( !this.sortDisabled ) {
271                                 var $th = $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
272                         }
274                         // add cell to headerList
275                         table.config.headerList[index] = this;
276                 } );
278                 return $tableHeaders;
280         }
282         function isValueInArray( v, a ) {
283                 var l = a.length;
284                 for ( var i = 0; i < l; i++ ) {
285                         if ( a[i][0] == v ) {
286                                 return true;
287                         }
288                 }
289                 return false;
290         }
292         function setHeadersCss( table, $headers, list, css, msg ) {
293                 // Remove all header information
294                 $headers.removeClass( css[0] ).removeClass( css[1] );
296                 var h = [];
297                 $headers.each( function( offset ) {
298                         if ( !this.sortDisabled ) {
299                                 h[this.column] = $( this );
300                         }
301                 } );
303                 var l = list.length;
304                 for ( var i = 0; i < l; i++ ) {
305                         h[ list[i][0] ].addClass( css[ list[i][1] ] ).attr( 'title', msg[ list[i][1] ] );
306                 }
307         }
309         function sortText( a, b ) {
310                 return ( (a < b) ? false : ((a > b) ? true : 0) );
311         }
313         function sortTextDesc( a, b ) {
314                 return ( (b < a) ? false : ((b > a) ? true : 0) );
315         }
317         function checkSorting( array1, array2, sortList ) {
318                 var col, fn, ret;
319                 for ( var i = 0, len = sortList.length; i < len; i++ ) {
320                         col = sortList[i][0];
321                         fn = ( sortList[i][1] ) ? sortTextDesc : sortText;
322                         ret = fn.call( this, array1[col], array2[col] );
323                         if ( ret !== 0 ) {
324                                 return ret;
325                         }
326                 }
327                 return ret;
328         }
330         // Merge sort algorithm
331         // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
332         function mergeSortHelper( array, begin, beginRight, end, sortList ) {
333                 for ( ; begin < beginRight; ++begin ) {
334                         if ( checkSorting( array[begin], array[beginRight], sortList ) ) {
335                                 var v = array[begin];
336                                 array[begin] = array[beginRight];
337                                 var begin2 = beginRight;
338                                 while ( begin2 + 1 < end && checkSorting( v, array[begin2 + 1], sortList ) ) {
339                                         var tmp = array[begin2];
340                                         array[begin2] = array[begin2 + 1];
341                                         array[begin2 + 1] = tmp;
342                                         ++begin2;
343                                 }
344                                 array[begin2] = v;
345                         }
346                 }
347         }
349         function mergeSort(array, begin, end, sortList) {
350                 var size = end - begin;
351                 if ( size < 2 ) {
352                         return;
353                 }
355                 var beginRight = begin + Math.floor(size / 2);
357                 mergeSort( array, begin, beginRight, sortList );
358                 mergeSort( array, beginRight, end, sortList );
359                 mergeSortHelper( array, begin, beginRight, end, sortList );
360         }
362         function multisort( table, sortList, cache ) {
363                 var i = sortList.length;
364                 mergeSort( cache.normalized, 0, cache.normalized.length, sortList );
366                 return cache;
367         }
369         function buildTransformTable() {
370                 var digits = '0123456789,.'.split( '' );
371                 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
372                 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
373                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
374                         ts.transformTable = false;
375                 } else {
376                         ts.transformTable = {};
378                         // Unpack the transform table
379                         var ascii = separatorTransformTable[0].split( "\t" ).concat( digitTransformTable[0].split( "\t" ) );
380                         var localised = separatorTransformTable[1].split( "\t" ).concat( digitTransformTable[1].split( "\t" ) );
382                         // Construct regex for number identification
383                         for ( var i = 0; i < ascii.length; i++ ) {
384                                 ts.transformTable[localised[i]] = ascii[i];
385                                 digits.push( $.escapeRE( localised[i] ) );
386                         }
387                 }
388                 var digitClass = '[' + digits.join( '', digits ) + ']';
390                 // We allow a trailing percent sign, which we just strip. This works fine
391                 // if percents and regular numbers aren't being mixed.
392                 ts.numberRegex = new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
393                 "|" + "[-+\u2212]?" + digitClass + "+[\\s\\xa0]*%?" + // Generic localised
394                 ")$", "i");
395         }
397         function buildDateTable() {
398                 var regex = [];
399                 ts.monthNames = [
400                         [],
401                         []
402                 ];
404                 for ( var i = 1; i < 13; i++ ) {
405                         ts.monthNames[0][i] = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
406                         ts.monthNames[1][i] = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
407                         regex.push( $.escapeRE( ts.monthNames[0][i] ) );
408                         regex.push( $.escapeRE( ts.monthNames[1][i] ) );
409                 }
411                 // Build piped string
412                 regex = regex.join( '|' );
414                 // Build RegEx
415                 // Any date formated with . , ' - or /
416                 ts.dateRegex[0] = new RegExp( /^\s*\d{1,2}[\,\.\-\/'\s]{1,2}\d{1,2}[\,\.\-\/'\s]{1,2}\d{2,4}\s*?/i);
418                 // Written Month name, dmy
419                 ts.dateRegex[1] = new RegExp( '^\\s*\\d{1,2}[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
421                 // Written Month name, mdy
422                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*\\d{1,2}[\\,\\.\\-\\/\'\\s]*\\d{2,4}\\s*$', 'i' );
424         }
426         function explodeRowspans( $table ) {
427                 // Split multi row cells into multiple cells with the same content
428                 $table.find( '[rowspan]' ).each(function() {
429                         var rowSpan = this.rowSpan;
430                         this.rowSpan = 1;
431                         var cell = $( this );
432                         var next = cell.parent().nextAll();
433                         for ( var i = 0; i < rowSpan - 1; i++ ) {
434                                 var td = next.eq( i ).find( 'td' );
435                                 if ( !td.length ) {
436                                         next.eq( i ).append( cell.clone() );
437                                 } else if ( this.cellIndex === 0 ) {
438                                         td.eq( this.cellIndex ).before( cell.clone() );
439                                 } else {
440                                         td.eq( this.cellIndex - 1 ).after( cell.clone() );
441                                 }
442                         }
443                 });
444         }
446         function buildCollationTable() {
447                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
448                 ts.collationRegex = null;
449                 if ( ts.collationTable ) {
450                         var keys = [];
452                         // Build array of key names
453                         for ( var key in ts.collationTable ) {
454                                 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
455                                         keys.push(key);
456                                 }
457                         }
458                         if (keys.length) {
459                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
460                         }
461                 }
462         }
464         function cacheRegexs() {
465                 if ( ts.rgx ) {
466                         return;
467                 }
468                 ts.rgx = {
469                         IPAddress: [
470                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
471                         ],
472                         currency: [
473                                 new RegExp( /^[£$€?.]/),
474                                 new RegExp( /[£$€]/g)
475                         ],
476                         url: [
477                                 new RegExp( /^(https?|ftp|file):\/\/$/),
478                                 new RegExp( /(https?|ftp|file):\/\//)
479                         ],
480                         isoDate: [
481                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
482                         ],
483                         usLongDate: [
484                                 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)))$/)
485                         ],
486                         time: [
487                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
488                         ]
489                 };
490         }
492         /* Public scope */
494         $.tablesorter = {
496                         defaultOptions: {
497                                 cssHeader: 'headerSort',
498                                 cssAsc: 'headerSortUp',
499                                 cssDesc: 'headerSortDown',
500                                 cssChildRow: 'expand-child',
501                                 sortInitialOrder: 'asc',
502                                 sortMultiSortKey: 'shiftKey',
503                                 sortLocaleCompare: false,
504                                 parsers: {},
505                                 widgets: [],
506                                 headers: {},
507                                 cancelSelection: true,
508                                 sortList: [],
509                                 headerList: [],
510                                 selectorHeaders: 'thead tr:eq(0) th',
511                                 debug: false
512                         },
514                         dateRegex: [],
515                         monthNames: [],
517                         /**
518                          * @param $tables {jQuery}
519                          * @param settings {Object} (optional)
520                          */
521                         construct: function( $tables, settings ) {
522                                 return $tables.each( function( i, table ) {
523                                         // Declare and cache.
524                                         var     $document, $headers, cache, config, sortOrder,
525                                                 $table = $( table ),
526                                                 shiftDown = 0,
527                                                 firstTime = true;
529                                         // Quit if no tbody
530                                         if ( !table.tBodies ) {
531                                                 return;
532                                         }
533                                         if ( !table.tHead ) {
534                                                 // No thead found. Look for rows with <th>s and
535                                                 // move them into a <thead> tag
536                                                 emulateTHead( $table );
537                                                 
538                                                 // Still no thead? Then quit
539                                                 if ( !table.tHead ) {
540                                                         return;
541                                                 }
542                                         }
544                                         // New config object.
545                                         table.config = {};
547                                         // Merge and extend.
548                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
550                                         // Save the settings where they read
551                                         $.data( table, 'tablesorter', config );
553                                         // Get the CSS class names, could be done else where.
554                                         var sortCSS = [ config.cssDesc, config.cssAsc ];
555                                         var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
557                                         // Build headers
558                                         $headers = buildHeaders( table, sortMsg );
560                                         // Grab and process locale settings
561                                         buildTransformTable();
562                                         buildDateTable();
563                                         buildCollationTable();
565                                         // Precaching regexps can bring 10 fold
566                                         // performance improvements in some browsers.
567                                         cacheRegexs();
569                                         // Apply event handling to headers
570                                         // this is to big, perhaps break it out?
571                                         $headers.click( function( e ) {
573                                                 if ( firstTime ) {
574                                                         firstTime = false;
576                                                         // Legacy fix of .sortbottoms
577                                                         // Wrap them inside inside a tfoot (because that's what they actually want to be) &
578                                                         // and put the <tfoot> at the end of the <table>
579                                                         var $sortbottoms = $table.find( 'tr.sortbottom' );
580                                                         if ( $sortbottoms.length ) {
581                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) )
582                                                         }
584                                                         explodeRowspans( $table );
585                                                         // try to auto detect column type, and store in tables config
586                                                         table.config.parsers = buildParserCache( table, $headers );
587                                                         // build the cache for the tbody cells
588                                                         cache = buildCache( table );
589                                                 }
590                                                 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
591                                                 if ( !table.sortDisabled && totalRows > 0 ) {
593                                                         // Cache jQuery object
594                                                         var $cell = $( this );
596                                                         // Get current column index
597                                                         var i = this.column;
599                                                         // Get current column sort order
600                                                         this.order = this.count % 2;
601                                                         this.count++;
603                                                         // User only wants to sort on one column
604                                                         if ( !e[config.sortMultiSortKey] ) {
605                                                                 // Flush the sort list
606                                                                 config.sortList = [];
607                                                                 // Add column to sort list
608                                                                 config.sortList.push( [i, this.order] );
610                                                         // Multi column sorting
611                                                         } else {
612                                                                 // The user has clicked on an already sorted column.
613                                                                 if ( isValueInArray( i, config.sortList ) ) {
614                                                                         // Reverse the sorting direction for all tables.
615                                                                         for ( var j = 0; j < config.sortList.length; j++ ) {
616                                                                                 var s = config.sortList[j],
617                                                                                         o = config.headerList[s[0]];
618                                                                                 if ( s[0] == i ) {
619                                                                                         o.count = s[1];
620                                                                                         o.count++;
621                                                                                         s[1] = o.count % 2;
622                                                                                 }
623                                                                         }
624                                                                 } else {
625                                                                         // Add column to sort list array
626                                                                         config.sortList.push( [i, this.order] );
627                                                                 }
628                                                         }
630                                                         // Set CSS for headers
631                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg );
632                                                         appendToTable(
633                                                                 $table[0], multisort( $table[0], config.sortList, cache )
634                                                         );
636                                                         // Stop normal event by returning false
637                                                         return false;
638                                                 }
640                                         // Cancel selection
641                                         } ).mousedown( function() {
642                                                 if ( config.cancelSelection ) {
643                                                         this.onselectstart = function() {
644                                                                 return false;
645                                                         };
646                                                         return false;
647                                                 }
648                                         } );
650                                 } );
651                         },
653                         addParser: function( parser ) {
654                                 var     l = parsers.length,
655                                         a = true;
656                                 for ( var i = 0; i < l; i++ ) {
657                                         if ( parsers[i].id.toLowerCase() == parser.id.toLowerCase() ) {
658                                                 a = false;
659                                         }
660                                 }
661                                 if ( a ) {
662                                         parsers.push( parser );
663                                 }
664                         },
666                         formatDigit: function( s ) {
667                                 if ( ts.transformTable !== false ) {
668                                         var     out = '',
669                                                 c;
670                                         for ( var p = 0; p < s.length; p++ ) {
671                                                 c = s.charAt(p);
672                                                 if ( c in ts.transformTable ) {
673                                                         out += ts.transformTable[c];
674                                                 } else {
675                                                         out += c;
676                                                 }
677                                         }
678                                         s = out;
679                                 }
680                                 var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
681                                 return ( isNaN(i)) ? 0 : i;
682                         },
684                         formatFloat: function( s ) {
685                                 var i = parseFloat(s);
686                                 return ( isNaN(i)) ? 0 : i;
687                         },
689                         formatInt: function( s ) {
690                                 var i = parseInt( s, 10 );
691                                 return ( isNaN(i)) ? 0 : i;
692                         },
694                         clearTableBody: function( table ) {
695                                 if ( $.browser.msie ) {
696                                         var empty = function( el ) {
697                                                 while ( el.firstChild ) {
698                                                         el.removeChild( el.firstChild );
699                                                 }
700                                         };
701                                         empty( table.tBodies[0] );
702                                 } else {
703                                         table.tBodies[0].innerHTML = '';
704                                 }
705                         }
706                 };
708         // Shortcut
709         ts = $.tablesorter;
711         // Register as jQuery prototype method
712         $.fn.tablesorter = function( settings ) {
713                 return ts.construct( this, settings );
714         };
716         // Add default parsers
717         ts.addParser( {
718                 id: 'text',
719                 is: function( s ) {
720                         return true;
721                 },
722                 format: function( s ) {
723                         s = $.trim( s.toLowerCase() );
724                         if ( ts.collationRegex ) {
725                                 var tsc = ts.collationTable;
726                                 s = s.replace( ts.collationRegex, function( match ) {
727                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
728                                         return r.toLowerCase();
729                                 } );
730                         }
731                         return s;
732                 },
733                 type: 'text'
734         } );
736         ts.addParser( {
737                 id: 'IPAddress',
738                 is: function( s ) {
739                         return ts.rgx.IPAddress[0].test(s);
740                 },
741                 format: function( s ) {
742                         var     a = s.split( '.' ),
743                                 r = '',
744                                 l = a.length;
745                         for ( var i = 0; i < l; i++ ) {
746                                 var item = a[i];
747                                 if ( item.length == 1 ) {
748                                         r += '00' + item;
749                                 } else if ( item.length == 2 ) {
750                                         r += '0' + item;
751                                 } else {
752                                         r += item;
753                                 }
754                         }
755                         return $.tablesorter.formatFloat(r);
756                 },
757                 type: 'numeric'
758         } );
760         ts.addParser( {
761                 id: 'currency',
762                 is: function( s ) {
763                         return ts.rgx.currency[0].test(s);
764                 },
765                 format: function( s ) {
766                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
767                 },
768                 type: 'numeric'
769         } );
771         ts.addParser( {
772                 id: 'url',
773                 is: function( s ) {
774                         return ts.rgx.url[0].test(s);
775                 },
776                 format: function( s ) {
777                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
778                 },
779                 type: 'text'
780         } );
782         ts.addParser( {
783                 id: 'isoDate',
784                 is: function( s ) {
785                         return ts.rgx.isoDate[0].test(s);
786                 },
787                 format: function( s ) {
788                         return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
789                         new RegExp( /-/g), '/')).getTime() : '0' );
790                 },
791                 type: 'numeric'
792         } );
794         ts.addParser( {
795                 id: 'usLongDate',
796                 is: function( s ) {
797                         return ts.rgx.usLongDate[0].test(s);
798                 },
799                 format: function( s ) {
800                         return $.tablesorter.formatFloat( new Date(s).getTime() );
801                 },
802                 type: 'numeric'
803         } );
805         ts.addParser( {
806                 id: 'date',
807                 is: function( s ) {
808                         return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
809                 },
810                 format: function( s, table ) {
811                         s = $.trim( s.toLowerCase() );
813                         for ( var i = 1, j = 0; i < 13 && j < 2; i++ ) {
814                                 s = s.replace( ts.monthNames[j][i], i );
815                                 if ( i == 12 ) {
816                                         j++;
817                                         i = 0;
818                                 }
819                         }
821                         s = s.replace( /[\-\.\,' ]/g, '/' );
823                         // Replace double slashes
824                         s = s.replace( /\/\//g, '/' );
825                         s = s.replace( /\/\//g, '/' );
826                         s = s.split( '/' );
828                         // Pad Month and Day
829                         if ( s[0] && s[0].length == 1 ) {
830                                 s[0] = '0' + s[0];
831                         }
832                         if ( s[1] && s[1].length == 1 ) {
833                                 s[1] = '0' + s[1];
834                         }
835                         var y;
837                         if ( !s[2] ) {
838                                 // Fix yearless dates
839                                 s[2] = 2000;
840                         } else if ( ( y = parseInt( s[2], 10) ) < 100 ) {
841                                 // Guestimate years without centuries
842                                 if ( y < 30 ) {
843                                         s[2] = 2000 + y;
844                                 } else {
845                                         s[2] = 1900 + y;
846                                 }
847                         }
848                         // Resort array depending on preferences
849                         if ( mw.config.get( 'wgDefaultDateFormat' ) == 'mdy' || mw.config.get( 'wgContentLanguage' ) == 'en' ) {
850                                 s.push( s.shift() );
851                                 s.push( s.shift() );
852                         } else if ( mw.config.get( 'wgDefaultDateFormat' ) == 'dmy' ) {
853                                 var d = s.shift();
854                                 s.push( s.shift() );
855                                 s.push(d);
856                         }
857                         return parseInt( s.join( '' ), 10 );
858                 },
859                 type: 'numeric'
860         } );
862         ts.addParser( {
863                 id: 'time',
864                 is: function( s ) {
865                         return ts.rgx.time[0].test(s);
866                 },
867                 format: function( s ) {
868                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
869                 },
870                 type: 'numeric'
871         } );
873         ts.addParser( {
874                 id: 'number',
875                 is: function( s, table ) {
876                         return $.tablesorter.numberRegex.test( $.trim( s ));
877                 },
878                 format: function( s ) {
879                         return $.tablesorter.formatDigit(s);
880                 },
881                 type: 'numeric'
882         } );
884 } )( jQuery );