$.tablesorter: remove and inline getTextFromRowAndCellIndex()
[mediawiki.git] / resources / jquery / jquery.tablesorter.js
blobe252ba549c4933a7c6fe4331119374d6df1c3274
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  * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
23  * @desc Create a tablesorter interface initially sorting on the first and second column.
24  *
25  * @option String cssHeader ( optional ) A string of the class name to be appended
26  *         to sortable tr elements in the thead of the table. Default value:
27  *         "header"
28  *
29  * @option String cssAsc ( optional ) A string of the class name to be appended to
30  *         sortable tr elements in the thead on a ascending sort. Default value:
31  *         "headerSortUp"
32  *
33  * @option String cssDesc ( optional ) A string of the class name to be appended
34  *         to sortable tr elements in the thead on a descending sort. Default
35  *         value: "headerSortDown"
36  *
37  * @option String sortInitialOrder ( optional ) A string of the inital sorting
38  *         order can be asc or desc. Default value: "asc"
39  *
40  * @option String sortMultisortKey ( optional ) A string of the multi-column sort
41  *         key. Default value: "shiftKey"
42  *
43  * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
44  *         to use String.localeCampare method or not. Set to false.
45  *
46  * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
47  *         tablesorter should cancel selection of the table headers text.
48  *         Default value: true
49  *
50  * @option Array sortList ( optional ) An array containing objects specifying sorting.
51  *         By passing more than one object, multi-sorting will be applied. Object structure:
52  *         { <Integer column index>: <String 'asc' or 'desc'> }
53  *         Default value: []
54  *
55  * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
56  *         should display debuging information usefull for development.
57  *
58  * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
59  *
60  * @type jQuery
61  *
62  * @name tablesorter
63  *
64  * @cat Plugins/Tablesorter
65  *
66  * @author Christian Bach/christian.bach@polyester.se
67  */
69 ( function ( $, mw ) {
70         /*jshint onevar:false */
72         /* Local scope */
74         var ts,
75                 parsers = [];
77         /* Parser utility functions */
79         function getParserById( name ) {
80                 var len = parsers.length;
81                 for ( var i = 0; i < len; i++ ) {
82                         if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
83                                 return parsers[i];
84                         }
85                 }
86                 return false;
87         }
89         function getElementSortKey( node ) {
90                 var $node = $( node ),
91                         // Use data-sort-value attribute.
92                         // Use data() instead of attr() so that live value changes
93                         // are processed as well (bug 38152).
94                         data = $node.data( 'sortValue' );
96                 if ( data !== null && data !== undefined ) {
97                         // Cast any numbers or other stuff to a string, methods
98                         // like charAt, toLowerCase and split are expected.
99                         return String( data );
100                 } else {
101                         if ( node.tagName.toLowerCase() === 'img' ) {
102                                 return $node.attr( 'alt' ) || ''; // handle undefined alt
103                         } else {
104                                 return $.map( $.makeArray( node.childNodes ), function( elem ) {
105                                         // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
106                                         if ( elem.nodeType === 1 ) {
107                                                 return getElementSortKey( elem );
108                                         } else {
109                                                 return $.text( elem );
110                                         }
111                                 } ).join( '' );
112                         }
113                 }
114         }
116         function detectParserForColumn( table, rows, cellIndex ) {
117                 var l = parsers.length,
118                         nodeValue,
119                         // Start with 1 because 0 is the fallback parser
120                         i = 1,
121                         rowIndex = 0,
122                         concurrent = 0,
123                         needed = ( rows.length > 4 ) ? 5 : rows.length;
125                 while ( i < l ) {
126                         if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
127                                 nodeValue = $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
128                         } else {
129                                 nodeValue = '';
130                         }
132                         if ( nodeValue !== '') {
133                                 if ( parsers[i].is( nodeValue, table ) ) {
134                                         concurrent++;
135                                         rowIndex++;
136                                         if ( concurrent >= needed ) {
137                                                 // Confirmed the parser for multiple cells, let's return it
138                                                 return parsers[i];
139                                         }
140                                 } else {
141                                         // Check next parser, reset rows
142                                         i++;
143                                         rowIndex = 0;
144                                         concurrent = 0;
145                                 }
146                         } else {
147                                 // Empty cell
148                                 rowIndex++;
149                                 if ( rowIndex > rows.length ) {
150                                         rowIndex = 0;
151                                         i++;
152                                 }
153                         }
154                 }
156                 // 0 is always the generic parser (text)
157                 return parsers[0];
158         }
160         function buildParserCache( table, $headers ) {
161                 var rows = table.tBodies[0].rows,
162                         sortType,
163                         parsers = [];
165                 if ( rows[0] ) {
167                         var cells = rows[0].cells,
168                                 len = cells.length,
169                                 i, parser;
171                         for ( i = 0; i < len; i++ ) {
172                                 parser = false;
173                                 sortType = $headers.eq( i ).data( 'sortType' );
174                                 if ( sortType !== undefined ) {
175                                         parser = getParserById( sortType );
176                                 }
178                                 if ( parser === false ) {
179                                         parser = detectParserForColumn( table, rows, i );
180                                 }
182                                 parsers.push( parser );
183                         }
184                 }
185                 return parsers;
186         }
188         /* Other utility functions */
190         function buildCache( table ) {
191                 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
192                         totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
193                         parsers = table.config.parsers,
194                         cache = {
195                                 row: [],
196                                 normalized: []
197                         };
199                 for ( var i = 0; i < totalRows; ++i ) {
201                         // Add the table data to main data array
202                         var $row = $( table.tBodies[0].rows[i] ),
203                                 cols = [];
205                         // if this is a child row, add it to the last row's children and
206                         // continue to the next row
207                         if ( $row.hasClass( table.config.cssChildRow ) ) {
208                                 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
209                                 // go to the next for loop
210                                 continue;
211                         }
213                         cache.row.push( $row );
215                         for ( var j = 0; j < totalCells; ++j ) {
216                                 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
217                         }
219                         cols.push( cache.normalized.length ); // add position for rowCache
220                         cache.normalized.push( cols );
221                         cols = null;
222                 }
224                 return cache;
225         }
227         function appendToTable( table, cache ) {
228                 var row = cache.row,
229                         normalized = cache.normalized,
230                         totalRows = normalized.length,
231                         checkCell = ( normalized[0].length - 1 ),
232                         fragment = document.createDocumentFragment();
234                 for ( var i = 0; i < totalRows; i++ ) {
235                         var pos = normalized[i][checkCell];
237                         var l = row[pos].length;
239                         for ( var j = 0; j < l; j++ ) {
240                                 fragment.appendChild( row[pos][j] );
241                         }
243                 }
244                 table.tBodies[0].appendChild( fragment );
246                 $( table ).trigger( 'sortEnd.tablesorter' );
247         }
249         /**
250          * Find all header rows in a thead-less table and put them in a <thead> tag.
251          * This only treats a row as a header row if it contains only <th>s (no <td>s)
252          * and if it is preceded entirely by header rows. The algorithm stops when
253          * it encounters the first non-header row.
254          *
255          * After this, it will look at all rows at the bottom for footer rows
256          * And place these in a tfoot using similar rules.
257          * @param $table jQuery object for a <table>
258          */
259         function emulateTHeadAndFoot( $table ) {
260                 var $rows = $table.find( '> tbody > tr' );
261                 if( !$table.get(0).tHead ) {
262                         var $thead = $( '<thead>' );
263                         $rows.each( function () {
264                                 if ( $(this).children( 'td' ).length > 0 ) {
265                                         // This row contains a <td>, so it's not a header row
266                                         // Stop here
267                                         return false;
268                                 }
269                                 $thead.append( this );
270                         } );
271                         $table.find(' > tbody:first').before( $thead );
272                 }
273                 if( !$table.get(0).tFoot ) {
274                         var $tfoot = $( '<tfoot>' );
275                         var len = $rows.length;
276                         for ( var i = len-1; i >= 0; i-- ) {
277                                 if( $( $rows[i] ).children( 'td' ).length > 0 ){
278                                         break;
279                                 }
280                                 $tfoot.prepend( $( $rows[i] ));
281                         }
282                         $table.append( $tfoot );
283                 }
284         }
286         function buildHeaders( table, msg ) {
287                 var maxSeen = 0,
288                         longest,
289                         realCellIndex = 0,
290                         $tableHeaders = $( 'thead:eq(0) > tr', table );
291                 if ( $tableHeaders.length > 1 ) {
292                         $tableHeaders.each( function () {
293                                 if ( this.cells.length > maxSeen ) {
294                                         maxSeen = this.cells.length;
295                                         longest = this;
296                                 }
297                         });
298                         $tableHeaders = $( longest );
299                 }
300                 $tableHeaders = $tableHeaders.children( 'th' ).each( function ( index ) {
301                         this.column = realCellIndex;
303                         var colspan = this.colspan;
304                         colspan = colspan ? parseInt( colspan, 10 ) : 1;
305                         realCellIndex += colspan;
307                         this.order = 0;
308                         this.count = 0;
310                         if ( $( this ).is( '.unsortable' ) ) {
311                                 this.sortDisabled = true;
312                         }
314                         if ( !this.sortDisabled ) {
315                                 $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
316                         }
318                         // add cell to headerList
319                         table.config.headerList[index] = this;
320                 } );
322                 return $tableHeaders;
324         }
326         function isValueInArray( v, a ) {
327                 var l = a.length;
328                 for ( var i = 0; i < l; i++ ) {
329                         if ( a[i][0] === v ) {
330                                 return true;
331                         }
332                 }
333                 return false;
334         }
336         function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
337                 // Remove all header information and reset titles to default message
338                 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
340                 for ( var i = 0; i < list.length; i++ ) {
341                         $headers.eq( columnToHeader[ list[i][0] ] )
342                                 .addClass( css[ list[i][1] ] )
343                                 .attr( 'title', msg[ list[i][1] ] );
344                 }
345         }
347         function sortText( a, b ) {
348                 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
349         }
351         function sortTextDesc( a, b ) {
352                 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
353         }
355         function multisort( table, sortList, cache ) {
356                 var sortFn = [];
357                 var len = sortList.length;
358                 for ( var i = 0; i < len; i++ ) {
359                         sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
360                 }
361                 cache.normalized.sort( function ( array1, array2 ) {
362                         var col, ret;
363                         for ( var i = 0; i < len; i++ ) {
364                                 col = sortList[i][0];
365                                 ret = sortFn[i].call( this, array1[col], array2[col] );
366                                 if ( ret !== 0 ) {
367                                         return ret;
368                                 }
369                         }
370                         // Fall back to index number column to ensure stable sort
371                         return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
372                 } );
373                 return cache;
374         }
376         function buildTransformTable() {
377                 var digits = '0123456789,.'.split( '' );
378                 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
379                 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
380                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
381                         ts.transformTable = false;
382                 } else {
383                         ts.transformTable = {};
385                         // Unpack the transform table
386                         var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
387                         var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
389                         // Construct regex for number identification
390                         for ( var i = 0; i < ascii.length; i++ ) {
391                                 ts.transformTable[localised[i]] = ascii[i];
392                                 digits.push( $.escapeRE( localised[i] ) );
393                         }
394                 }
395                 var digitClass = '[' + digits.join( '', digits ) + ']';
397                 // We allow a trailing percent sign, which we just strip. This works fine
398                 // if percents and regular numbers aren't being mixed.
399                 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
400                 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
401                 ')$', 'i');
402         }
404         function buildDateTable() {
405                 var regex = [];
406                 ts.monthNames = {};
408                 for ( var i = 1; i < 13; i++ ) {
409                         var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
410                         ts.monthNames[name] = i;
411                         regex.push( $.escapeRE( name ) );
412                         name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
413                         ts.monthNames[name] = i;
414                         regex.push( $.escapeRE( name ) );
415                 }
417                 // Build piped string
418                 regex = regex.join( '|' );
420                 // Build RegEx
421                 // Any date formated with . , ' - or /
422                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
424                 // Written Month name, dmy
425                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
427                 // Written Month name, mdy
428                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
430         }
432         function explodeRowspans( $table ) {
433                 // Split multi row cells into multiple cells with the same content
434                 $table.find( '> tbody > tr > [rowspan]' ).each(function () {
435                         var rowSpan = this.rowSpan;
436                         this.rowSpan = 1;
437                         var cell = $( this );
438                         var next = cell.parent().nextAll();
439                         for ( var i = 0; i < rowSpan - 1; i++ ) {
440                                 var td = next.eq( i ).children( 'td' );
441                                 if ( !td.length ) {
442                                         next.eq( i ).append( cell.clone() );
443                                 } else if ( this.cellIndex === 0 ) {
444                                         td.eq( this.cellIndex ).before( cell.clone() );
445                                 } else {
446                                         td.eq( this.cellIndex - 1 ).after( cell.clone() );
447                                 }
448                         }
449                 });
450         }
452         function buildCollationTable() {
453                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
454                 ts.collationRegex = null;
455                 if ( ts.collationTable ) {
456                         var keys = [];
458                         // Build array of key names
459                         for ( var key in ts.collationTable ) {
460                                 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
461                                         keys.push(key);
462                                 }
463                         }
464                         if (keys.length) {
465                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
466                         }
467                 }
468         }
470         function cacheRegexs() {
471                 if ( ts.rgx ) {
472                         return;
473                 }
474                 ts.rgx = {
475                         IPAddress: [
476                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
477                         ],
478                         currency: [
479                                 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
480                                 new RegExp( /[£$€¥]/g)
481                         ],
482                         url: [
483                                 new RegExp( /^(https?|ftp|file):\/\/$/),
484                                 new RegExp( /(https?|ftp|file):\/\//)
485                         ],
486                         isoDate: [
487                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
488                         ],
489                         usLongDate: [
490                                 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)))$/)
491                         ],
492                         time: [
493                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
494                         ]
495                 };
496         }
498         /**
499          * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
500          * structure [ [ Integer , Integer ], ... ]
501          *
502          * @param sortObjects {Array} List of sort objects.
503          * @return {Array} List of internal sort definitions.
504          */
506         function convertSortList( sortObjects ) {
507                 var sortList = [];
508                 $.each( sortObjects, function( i, sortObject ) {
509                         $.each ( sortObject, function( columnIndex, order ) {
510                                 var orderIndex = ( order === 'desc' ) ? 1 : 0;
511                                 sortList.push( [columnIndex, orderIndex] );
512                         } );
513                 } );
514                 return sortList;
515         }
517         /* Public scope */
519         $.tablesorter = {
521                         defaultOptions: {
522                                 cssHeader: 'headerSort',
523                                 cssAsc: 'headerSortUp',
524                                 cssDesc: 'headerSortDown',
525                                 cssChildRow: 'expand-child',
526                                 sortInitialOrder: 'asc',
527                                 sortMultiSortKey: 'shiftKey',
528                                 sortLocaleCompare: false,
529                                 parsers: {},
530                                 widgets: [],
531                                 headers: {},
532                                 cancelSelection: true,
533                                 sortList: [],
534                                 headerList: [],
535                                 selectorHeaders: 'thead tr:eq(0) th',
536                                 debug: false
537                         },
539                         dateRegex: [],
540                         monthNames: {},
542                         /**
543                          * @param $tables {jQuery}
544                          * @param settings {Object} (optional)
545                          */
546                         construct: function ( $tables, settings ) {
547                                 return $tables.each( function ( i, table ) {
548                                         // Declare and cache.
549                                         var $headers, cache, config,
550                                                 headerToColumns, columnToHeader, colspanOffset,
551                                                 $table = $( table ),
552                                                 firstTime = true;
554                                         // Quit if no tbody
555                                         if ( !table.tBodies ) {
556                                                 return;
557                                         }
558                                         if ( !table.tHead ) {
559                                                 // No thead found. Look for rows with <th>s and
560                                                 // move them into a <thead> tag or a <tfoot> tag
561                                                 emulateTHeadAndFoot( $table );
563                                                 // Still no thead? Then quit
564                                                 if ( !table.tHead ) {
565                                                         return;
566                                                 }
567                                         }
568                                         $table.addClass( 'jquery-tablesorter' );
570                                         // FIXME config should probably not be stored in the plain table node
571                                         // New config object.
572                                         table.config = {};
574                                         // Merge and extend.
575                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
577                                         // Save the settings where they read
578                                         $.data( table, 'tablesorter', { config: config } );
580                                         // Get the CSS class names, could be done else where.
581                                         var sortCSS = [ config.cssDesc, config.cssAsc ];
582                                         var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
584                                         // Build headers
585                                         $headers = buildHeaders( table, sortMsg );
587                                         // Grab and process locale settings
588                                         buildTransformTable();
589                                         buildDateTable();
590                                         buildCollationTable();
592                                         // Precaching regexps can bring 10 fold
593                                         // performance improvements in some browsers.
594                                         cacheRegexs();
596                                         function setupForFirstSort() {
597                                                 firstTime = false;
599                                                 // Legacy fix of .sortbottoms
600                                                 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
601                                                 // and put the <tfoot> at the end of the <table>
602                                                 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
603                                                 if ( $sortbottoms.length ) {
604                                                         var $tfoot = $table.children( 'tfoot' );
605                                                         if ( $tfoot.length ) {
606                                                                 $tfoot.eq(0).prepend( $sortbottoms );
607                                                         } else {
608                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
609                                                         }
610                                                 }
612                                                 explodeRowspans( $table );
614                                                 // try to auto detect column type, and store in tables config
615                                                 table.config.parsers = buildParserCache( table, $headers );
616                                         }
618                                         // as each header can span over multiple columns (using colspan=N),
619                                         // we have to bidirectionally map headers to their columns and columns to their headers
620                                         headerToColumns = [];
621                                         columnToHeader = [];
622                                         colspanOffset = 0;
623                                         $headers.each( function ( headerIndex ) {
624                                                 var columns = [];
625                                                 for ( var i = 0; i < this.colSpan; i++ ) {
626                                                         columnToHeader[ colspanOffset + i ] = headerIndex;
627                                                         columns.push( colspanOffset + i );
628                                                 }
630                                                 headerToColumns[ headerIndex ] = columns;
631                                                 colspanOffset += this.colSpan;
632                                         } );
634                                         // Apply event handling to headers
635                                         // this is too big, perhaps break it out?
636                                         $headers.filter( ':not(.unsortable)' ).click( function ( e ) {
637                                                 if ( e.target.nodeName.toLowerCase() === 'a' ) {
638                                                         // The user clicked on a link inside a table header
639                                                         // Do nothing and let the default link click action continue
640                                                         return true;
641                                                 }
643                                                 if ( firstTime ) {
644                                                         setupForFirstSort();
645                                                 }
647                                                 // Build the cache for the tbody cells
648                                                 // to share between calculations for this sort action.
649                                                 // Re-calculated each time a sort action is performed due to possiblity
650                                                 // that sort values change. Shouldn't be too expensive, but if it becomes
651                                                 // too slow an event based system should be implemented somehow where
652                                                 // cells get event .change() and bubbles up to the <table> here
653                                                 cache = buildCache( table );
655                                                 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
656                                                 if ( !table.sortDisabled && totalRows > 0 ) {
657                                                         // Get current column sort order
658                                                         this.order = this.count % 2;
659                                                         this.count++;
661                                                         var cell = this;
662                                                         // Get current column index
663                                                         var columns = headerToColumns[this.column];
664                                                         var newSortList = $.map( columns, function (c) {
665                                                                 // jQuery "helpfully" flattens the arrays...
666                                                                 return [[c, cell.order]];
667                                                         });
668                                                         // Index of first column belonging to this header
669                                                         var i = columns[0];
671                                                         if ( !e[config.sortMultiSortKey] ) {
672                                                                 // User only wants to sort on one column set
673                                                                 // Flush the sort list and add new columns
674                                                                 config.sortList = newSortList;
675                                                         } else {
676                                                                 // Multi column sorting
677                                                                 // It is not possible for one column to belong to multiple headers,
678                                                                 // so this is okay - we don't need to check for every value in the columns array
679                                                                 if ( isValueInArray( i, config.sortList ) ) {
680                                                                         // The user has clicked on an already sorted column.
681                                                                         // Reverse the sorting direction for all tables.
682                                                                         for ( var j = 0; j < config.sortList.length; j++ ) {
683                                                                                 var s = config.sortList[j],
684                                                                                         o = config.headerList[s[0]];
685                                                                                 if ( isValueInArray( s[0], newSortList ) ) {
686                                                                                         o.count = s[1];
687                                                                                         o.count++;
688                                                                                         s[1] = o.count % 2;
689                                                                                 }
690                                                                         }
691                                                                 } else {
692                                                                         // Add columns to sort list array
693                                                                         config.sortList = config.sortList.concat( newSortList );
694                                                                 }
695                                                         }
697                                                         // Set CSS for headers
698                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, columnToHeader );
699                                                         appendToTable(
700                                                                 $table[0], multisort( $table[0], config.sortList, cache )
701                                                         );
703                                                         // Stop normal event by returning false
704                                                         return false;
705                                                 }
707                                         // Cancel selection
708                                         } ).mousedown( function () {
709                                                 if ( config.cancelSelection ) {
710                                                         this.onselectstart = function () {
711                                                                 return false;
712                                                         };
713                                                         return false;
714                                                 }
715                                         } );
717                                         /**
718                                          * Sorts the table. If no sorting is specified by passing a list of sort
719                                          * objects, the table is sorted according to the initial sorting order.
720                                          * Passing an empty array will reset sorting (basically just reset the headers
721                                          * making the table appear unsorted).
722                                          *
723                                          * @param sortList {Array} (optional) List of sort objects.
724                                          */
725                                         $table.data( 'tablesorter' ).sort = function( sortList ) {
727                                                 if ( firstTime ) {
728                                                         setupForFirstSort();
729                                                 }
731                                                 if ( sortList === undefined ) {
732                                                         sortList = config.sortList;
733                                                 } else if ( sortList.length > 0 ) {
734                                                         sortList = convertSortList( sortList );
735                                                 }
737                                                 // re-build the cache for the tbody cells
738                                                 cache = buildCache( table );
740                                                 // set css for headers
741                                                 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, columnToHeader );
743                                                 // sort the table and append it to the dom
744                                                 appendToTable( table, multisort( table, sortList, cache ) );
745                                         };
747                                         // sort initially
748                                         if ( config.sortList.length > 0 ) {
749                                                 setupForFirstSort();
750                                                 config.sortList = convertSortList( config.sortList );
751                                                 $table.data( 'tablesorter' ).sort();
752                                         }
754                                 } );
755                         },
757                         addParser: function ( parser ) {
758                                 var l = parsers.length,
759                                         a = true;
760                                 for ( var i = 0; i < l; i++ ) {
761                                         if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
762                                                 a = false;
763                                         }
764                                 }
765                                 if ( a ) {
766                                         parsers.push( parser );
767                                 }
768                         },
770                         formatDigit: function ( s ) {
771                                 var out, c, p, i;
772                                 if ( ts.transformTable !== false ) {
773                                         out = '';
774                                         for ( p = 0; p < s.length; p++ ) {
775                                                 c = s.charAt(p);
776                                                 if ( c in ts.transformTable ) {
777                                                         out += ts.transformTable[c];
778                                                 } else {
779                                                         out += c;
780                                                 }
781                                         }
782                                         s = out;
783                                 }
784                                 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
785                                 return isNaN( i ) ? 0 : i;
786                         },
788                         formatFloat: function ( s ) {
789                                 var i = parseFloat(s);
790                                 return isNaN( i ) ? 0 : i;
791                         },
793                         formatInt: function ( s ) {
794                                 var i = parseInt( s, 10 );
795                                 return isNaN( i ) ? 0 : i;
796                         },
798                         clearTableBody: function ( table ) {
799                                 $( table.tBodies[0] ).empty();
800                         }
801                 };
803         // Shortcut
804         ts = $.tablesorter;
806         // Register as jQuery prototype method
807         $.fn.tablesorter = function ( settings ) {
808                 return ts.construct( this, settings );
809         };
811         // Add default parsers
812         ts.addParser( {
813                 id: 'text',
814                 is: function () {
815                         return true;
816                 },
817                 format: function ( s ) {
818                         s = $.trim( s.toLowerCase() );
819                         if ( ts.collationRegex ) {
820                                 var tsc = ts.collationTable;
821                                 s = s.replace( ts.collationRegex, function ( match ) {
822                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
823                                         return r.toLowerCase();
824                                 } );
825                         }
826                         return s;
827                 },
828                 type: 'text'
829         } );
831         ts.addParser( {
832                 id: 'IPAddress',
833                 is: function ( s ) {
834                         return ts.rgx.IPAddress[0].test(s);
835                 },
836                 format: function ( s ) {
837                         var a = s.split( '.' ),
838                                 r = '',
839                                 l = a.length;
840                         for ( var i = 0; i < l; i++ ) {
841                                 var item = a[i];
842                                 if ( item.length === 1 ) {
843                                         r += '00' + item;
844                                 } else if ( item.length === 2 ) {
845                                         r += '0' + item;
846                                 } else {
847                                         r += item;
848                                 }
849                         }
850                         return $.tablesorter.formatFloat(r);
851                 },
852                 type: 'numeric'
853         } );
855         ts.addParser( {
856                 id: 'currency',
857                 is: function ( s ) {
858                         return ts.rgx.currency[0].test(s);
859                 },
860                 format: function ( s ) {
861                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
862                 },
863                 type: 'numeric'
864         } );
866         ts.addParser( {
867                 id: 'url',
868                 is: function ( s ) {
869                         return ts.rgx.url[0].test(s);
870                 },
871                 format: function ( s ) {
872                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
873                 },
874                 type: 'text'
875         } );
877         ts.addParser( {
878                 id: 'isoDate',
879                 is: function ( s ) {
880                         return ts.rgx.isoDate[0].test(s);
881                 },
882                 format: function ( s ) {
883                         return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
884                         new RegExp( /-/g), '/')).getTime() : '0' );
885                 },
886                 type: 'numeric'
887         } );
889         ts.addParser( {
890                 id: 'usLongDate',
891                 is: function ( s ) {
892                         return ts.rgx.usLongDate[0].test(s);
893                 },
894                 format: function ( s ) {
895                         return $.tablesorter.formatFloat( new Date(s).getTime() );
896                 },
897                 type: 'numeric'
898         } );
900         ts.addParser( {
901                 id: 'date',
902                 is: function ( s ) {
903                         return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
904                 },
905                 format: function ( s ) {
906                         var match;
907                         s = $.trim( s.toLowerCase() );
909                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
910                                 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
911                                         s = [ match[3], match[1], match[2] ];
912                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
913                                         s = [ match[3], match[2], match[1] ];
914                                 } else {
915                                         // If we get here, we don't know which order the dd-dd-dddd
916                                         // date is in. So return something not entirely invalid.
917                                         return '99999999';
918                                 }
919                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
920                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
921                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
922                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
923                         } else {
924                                 // Should never get here
925                                 return '99999999';
926                         }
928                         // Pad Month and Day
929                         if ( s[1].length === 1 ) {
930                                 s[1] = '0' + s[1];
931                         }
932                         if ( s[2].length === 1 ) {
933                                 s[2] = '0' + s[2];
934                         }
936                         var y;
937                         if ( ( y = parseInt( s[0], 10) ) < 100 ) {
938                                 // Guestimate years without centuries
939                                 if ( y < 30 ) {
940                                         s[0] = 2000 + y;
941                                 } else {
942                                         s[0] = 1900 + y;
943                                 }
944                         }
945                         while ( s[0].length < 4 ) {
946                                 s[0] = '0' + s[0];
947                         }
948                         return parseInt( s.join( '' ), 10 );
949                 },
950                 type: 'numeric'
951         } );
953         ts.addParser( {
954                 id: 'time',
955                 is: function ( s ) {
956                         return ts.rgx.time[0].test(s);
957                 },
958                 format: function ( s ) {
959                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
960                 },
961                 type: 'numeric'
962         } );
964         ts.addParser( {
965                 id: 'number',
966                 is: function ( s ) {
967                         return $.tablesorter.numberRegex.test( $.trim( s ));
968                 },
969                 format: function ( s ) {
970                         return $.tablesorter.formatDigit(s);
971                 },
972                 type: 'numeric'
973         } );
975 }( jQuery, mediaWiki ) );