Merge "Improve documentation for $wgRecentChangesFlags"
[mediawiki.git] / resources / jquery / jquery.tablesorter.js
blobacf21d602bd01022e5812e1bc45b2b3f154a1bea
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 ) {
102                                 return $node.text();
103                         } else if ( node.tagName.toLowerCase() === 'img' ) {
104                                 return $node.attr( 'alt' ) || ''; // handle undefined alt
105                         } else {
106                                 return $.map( $.makeArray( node.childNodes ), function( elem ) {
107                                         // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
108                                         if ( elem.nodeType === 1 ) {
109                                                 return getElementSortKey( elem );
110                                         } else {
111                                                 return $.text( elem );
112                                         }
113                                 } ).join( '' );
114                         }
115                 }
116         }
118         function detectParserForColumn( table, rows, cellIndex ) {
119                 var l = parsers.length,
120                         nodeValue,
121                         // Start with 1 because 0 is the fallback parser
122                         i = 1,
123                         rowIndex = 0,
124                         concurrent = 0,
125                         needed = ( rows.length > 4 ) ? 5 : rows.length;
127                 while ( i < l ) {
128                         if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
129                                 nodeValue = $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
130                         } else {
131                                 nodeValue = '';
132                         }
134                         if ( nodeValue !== '') {
135                                 if ( parsers[i].is( nodeValue, table ) ) {
136                                         concurrent++;
137                                         rowIndex++;
138                                         if ( concurrent >= needed ) {
139                                                 // Confirmed the parser for multiple cells, let's return it
140                                                 return parsers[i];
141                                         }
142                                 } else {
143                                         // Check next parser, reset rows
144                                         i++;
145                                         rowIndex = 0;
146                                         concurrent = 0;
147                                 }
148                         } else {
149                                 // Empty cell
150                                 rowIndex++;
151                                 if ( rowIndex > rows.length ) {
152                                         rowIndex = 0;
153                                         i++;
154                                 }
155                         }
156                 }
158                 // 0 is always the generic parser (text)
159                 return parsers[0];
160         }
162         function buildParserCache( table, $headers ) {
163                 var rows = table.tBodies[0].rows,
164                         sortType,
165                         parsers = [];
167                 if ( rows[0] ) {
169                         var cells = rows[0].cells,
170                                 len = cells.length,
171                                 i, parser;
173                         for ( i = 0; i < len; i++ ) {
174                                 parser = false;
175                                 sortType = $headers.eq( i ).data( 'sortType' );
176                                 if ( sortType !== undefined ) {
177                                         parser = getParserById( sortType );
178                                 }
180                                 if ( parser === false ) {
181                                         parser = detectParserForColumn( table, rows, i );
182                                 }
184                                 parsers.push( parser );
185                         }
186                 }
187                 return parsers;
188         }
190         /* Other utility functions */
192         function buildCache( table ) {
193                 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
194                         totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
195                         parsers = table.config.parsers,
196                         cache = {
197                                 row: [],
198                                 normalized: []
199                         };
201                 for ( var i = 0; i < totalRows; ++i ) {
203                         // Add the table data to main data array
204                         var $row = $( table.tBodies[0].rows[i] ),
205                                 cols = [];
207                         // if this is a child row, add it to the last row's children and
208                         // continue to the next row
209                         if ( $row.hasClass( table.config.cssChildRow ) ) {
210                                 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
211                                 // go to the next for loop
212                                 continue;
213                         }
215                         cache.row.push( $row );
217                         for ( var j = 0; j < totalCells; ++j ) {
218                                 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
219                         }
221                         cols.push( cache.normalized.length ); // add position for rowCache
222                         cache.normalized.push( cols );
223                         cols = null;
224                 }
226                 return cache;
227         }
229         function appendToTable( table, cache ) {
230                 var row = cache.row,
231                         normalized = cache.normalized,
232                         totalRows = normalized.length,
233                         checkCell = ( normalized[0].length - 1 ),
234                         fragment = document.createDocumentFragment();
236                 for ( var i = 0; i < totalRows; i++ ) {
237                         var pos = normalized[i][checkCell];
239                         var l = row[pos].length;
241                         for ( var j = 0; j < l; j++ ) {
242                                 fragment.appendChild( row[pos][j] );
243                         }
245                 }
246                 table.tBodies[0].appendChild( fragment );
248                 $( table ).trigger( 'sortEnd.tablesorter' );
249         }
251         /**
252          * Find all header rows in a thead-less table and put them in a <thead> tag.
253          * This only treats a row as a header row if it contains only <th>s (no <td>s)
254          * and if it is preceded entirely by header rows. The algorithm stops when
255          * it encounters the first non-header row.
256          *
257          * After this, it will look at all rows at the bottom for footer rows
258          * And place these in a tfoot using similar rules.
259          * @param $table jQuery object for a <table>
260          */
261         function emulateTHeadAndFoot( $table ) {
262                 var $rows = $table.find( '> tbody > tr' );
263                 if( !$table.get(0).tHead ) {
264                         var $thead = $( '<thead>' );
265                         $rows.each( function () {
266                                 if ( $(this).children( 'td' ).length > 0 ) {
267                                         // This row contains a <td>, so it's not a header row
268                                         // Stop here
269                                         return false;
270                                 }
271                                 $thead.append( this );
272                         } );
273                         $table.find(' > tbody:first').before( $thead );
274                 }
275                 if( !$table.get(0).tFoot ) {
276                         var $tfoot = $( '<tfoot>' );
277                         var len = $rows.length;
278                         for ( var i = len-1; i >= 0; i-- ) {
279                                 if( $( $rows[i] ).children( 'td' ).length > 0 ){
280                                         break;
281                                 }
282                                 $tfoot.prepend( $( $rows[i] ));
283                         }
284                         $table.append( $tfoot );
285                 }
286         }
288         function buildHeaders( table, msg ) {
289                 var maxSeen = 0,
290                         colspanOffset = 0,
291                         longest,
292                         columns,
293                         i,
294                         $tableHeaders = $( [] ),
295                         $tableRows = $( 'thead:eq(0) > tr', table );
296                 if ( $tableRows.length <= 1 ) {
297                         $tableHeaders = $tableRows.children( 'th' );
298                 } else {
299                         // We need to find the cells of the row containing the most columns
300                         var rowspan,
301                                 headersIndex = [];
302                         $tableRows.each( function ( rowIndex ) {
303                                 $.each( this.cells, function( index2, cell ) {
304                                         rowspan = Number( cell.rowSpan );
305                                         for ( i = 0; i < rowspan; i++ ) {
306                                                 if ( headersIndex[rowIndex+i] === undefined ) {
307                                                         headersIndex[rowIndex+i] = $( [] );
308                                                 }
309                                                 headersIndex[rowIndex+i].push( cell );
310                                         }
311                                 } );
312                         } );
313                         $.each( headersIndex, function ( index, cellArray ) {
314                                 if ( cellArray.length >= maxSeen ) {
315                                         maxSeen = cellArray.length;
316                                         longest = index;
317                                 }
318                         } );
319                         $tableHeaders = headersIndex[longest];
320                 }
322                 // as each header can span over multiple columns (using colspan=N),
323                 // we have to bidirectionally map headers to their columns and columns to their headers
324                 table.headerToColumns = [];
325                 table.columnToHeader = [];
327                 $tableHeaders.each( function ( headerIndex ) {
328                         columns = [];
329                         for ( i = 0; i < this.colSpan; i++ ) {
330                                 table.columnToHeader[ colspanOffset + i ] = headerIndex;
331                                 columns.push( colspanOffset + i );
332                         }
334                         table.headerToColumns[ headerIndex ] = columns;
335                         colspanOffset += this.colSpan;
337                         this.headerIndex = headerIndex;
338                         this.order = 0;
339                         this.count = 0;
341                         if ( $( this ).hasClass( table.config.unsortableClass ) ) {
342                                 this.sortDisabled = true;
343                         }
345                         if ( !this.sortDisabled ) {
346                                 $( this )
347                                         .addClass( table.config.cssHeader )
348                                         .attr( 'title', msg[1] )
349                                         .prop( 'tabIndex', 0 ).attr( 'role', 'button' );
350                         }
352                         // add cell to headerList
353                         table.config.headerList[headerIndex] = this;
354                 } );
356                 return $tableHeaders;
358         }
360         /**
361          * Sets the sort count of the columns that are not affected by the sorting to have them sorted
362          * in default (ascending) order when their header cell is clicked the next time.
363          *
364          * @param {jQuery} $headers
365          * @param {Number[][]} sortList
366          * @param {Number[][]} headerToColumns
367          */
368         function setHeadersOrder( $headers, sortList, headerToColumns ) {
369                 // Loop through all headers to retrieve the indices of the columns the header spans across:
370                 $.each( headerToColumns, function( headerIndex, columns ) {
372                         $.each( columns, function( i, columnIndex ) {
373                                 var header = $headers[headerIndex];
375                                 if ( !isValueInArray( columnIndex, sortList ) ) {
376                                         // Column shall not be sorted: Reset header count and order.
377                                         header.order = 0;
378                                         header.count = 0;
379                                 } else {
380                                         // Column shall be sorted: Apply designated count and order.
381                                         $.each( sortList, function( j, sortColumn ) {
382                                                 if ( sortColumn[0] === i ) {
383                                                         header.order = sortColumn[1];
384                                                         header.count = sortColumn[1] + 1;
385                                                         return false;
386                                                 }
387                                         } );
388                                 }
389                         } );
391                 } );
392         }
394         function isValueInArray( v, a ) {
395                 var l = a.length;
396                 for ( var i = 0; i < l; i++ ) {
397                         if ( a[i][0] === v ) {
398                                 return true;
399                         }
400                 }
401                 return false;
402         }
404         function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
405                 // Remove all header information and reset titles to default message
406                 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
408                 for ( var i = 0; i < list.length; i++ ) {
409                         $headers.eq( columnToHeader[ list[i][0] ] )
410                                 .addClass( css[ list[i][1] ] )
411                                 .attr( 'title', msg[ list[i][1] ] );
412                 }
413         }
415         function sortText( a, b ) {
416                 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
417         }
419         function sortTextDesc( a, b ) {
420                 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
421         }
423         function multisort( table, sortList, cache ) {
424                 var sortFn = [];
425                 var len = sortList.length;
426                 for ( var i = 0; i < len; i++ ) {
427                         sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
428                 }
429                 cache.normalized.sort( function ( array1, array2 ) {
430                         var col, ret;
431                         for ( var i = 0; i < len; i++ ) {
432                                 col = sortList[i][0];
433                                 ret = sortFn[i].call( this, array1[col], array2[col] );
434                                 if ( ret !== 0 ) {
435                                         return ret;
436                                 }
437                         }
438                         // Fall back to index number column to ensure stable sort
439                         return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
440                 } );
441                 return cache;
442         }
444         function buildTransformTable() {
445                 var digits = '0123456789,.'.split( '' );
446                 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
447                 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
448                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
449                         ts.transformTable = false;
450                 } else {
451                         ts.transformTable = {};
453                         // Unpack the transform table
454                         var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
455                         var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
457                         // Construct regex for number identification
458                         for ( var i = 0; i < ascii.length; i++ ) {
459                                 ts.transformTable[localised[i]] = ascii[i];
460                                 digits.push( $.escapeRE( localised[i] ) );
461                         }
462                 }
463                 var digitClass = '[' + digits.join( '', digits ) + ']';
465                 // We allow a trailing percent sign, which we just strip. This works fine
466                 // if percents and regular numbers aren't being mixed.
467                 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
468                 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
469                 ')$', 'i');
470         }
472         function buildDateTable() {
473                 var regex = [];
474                 ts.monthNames = {};
476                 for ( var i = 1; i < 13; i++ ) {
477                         var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
478                         ts.monthNames[name] = i;
479                         regex.push( $.escapeRE( name ) );
480                         name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
481                         ts.monthNames[name] = i;
482                         regex.push( $.escapeRE( name ) );
483                 }
485                 // Build piped string
486                 regex = regex.join( '|' );
488                 // Build RegEx
489                 // Any date formated with . , ' - or /
490                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
492                 // Written Month name, dmy
493                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
495                 // Written Month name, mdy
496                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
498         }
500         /**
501          * Replace all rowspanned cells in the body with clones in each row, so sorting
502          * need not worry about them.
503          *
504          * @param $table jQuery object for a <table>
505          */
506         function explodeRowspans( $table ) {
507                 var rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
509                 // Short circuit
510                 if ( !rowspanCells.length ) {
511                         return;
512                 }
514                 // First, we need to make a property like cellIndex but taking into
515                 // account colspans. We also cache the rowIndex to avoid having to take
516                 // cell.parentNode.rowIndex in the sorting function below.
517                 $table.find( '> tbody > tr' ).each( function () {
518                         var col = 0;
519                         var l = this.cells.length;
520                         for ( var i = 0; i < l; i++ ) {
521                                 this.cells[i].realCellIndex = col;
522                                 this.cells[i].realRowIndex = this.rowIndex;
523                                 col += this.cells[i].colSpan;
524                         }
525                 } );
527                 // Split multi row cells into multiple cells with the same content.
528                 // Sort by column then row index to avoid problems with odd table structures.
529                 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
530                 // might change the sort order.
531                 function resortCells() {
532                         rowspanCells = rowspanCells.sort( function ( a, b ) {
533                                 var ret = a.realCellIndex - b.realCellIndex;
534                                 if ( !ret ) {
535                                         ret = a.realRowIndex - b.realRowIndex;
536                                 }
537                                 return ret;
538                         } );
539                         $.each( rowspanCells, function () {
540                                 this.needResort = false;
541                         } );
542                 }
543                 resortCells();
545                 var spanningRealCellIndex, rowSpan, colSpan;
546                 function filterfunc() {
547                         return this.realCellIndex >= spanningRealCellIndex;
548                 }
550                 function fixTdCellIndex() {
551                         this.realCellIndex += colSpan;
552                         if ( this.rowSpan > 1 ) {
553                                 this.needResort = true;
554                         }
555                 }
557                 while ( rowspanCells.length ) {
558                         if ( rowspanCells[0].needResort ) {
559                                 resortCells();
560                         }
562                         var cell = rowspanCells.shift();
563                         rowSpan = cell.rowSpan;
564                         colSpan = cell.colSpan;
565                         spanningRealCellIndex = cell.realCellIndex;
566                         cell.rowSpan = 1;
567                         var $nextRows = $( cell ).parent().nextAll();
568                         for ( var i = 0; i < rowSpan - 1; i++ ) {
569                                 var $tds = $( $nextRows[i].cells ).filter( filterfunc );
570                                 var $clone = $( cell ).clone();
571                                 $clone[0].realCellIndex = spanningRealCellIndex;
572                                 if ( $tds.length ) {
573                                         $tds.each( fixTdCellIndex );
574                                         $tds.first().before( $clone );
575                                 } else {
576                                         $nextRows.eq( i ).append( $clone );
577                                 }
578                         }
579                 }
580         }
582         function buildCollationTable() {
583                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
584                 ts.collationRegex = null;
585                 if ( ts.collationTable ) {
586                         var keys = [];
588                         // Build array of key names
589                         for ( var key in ts.collationTable ) {
590                                 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
591                                         keys.push(key);
592                                 }
593                         }
594                         if (keys.length) {
595                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
596                         }
597                 }
598         }
600         function cacheRegexs() {
601                 if ( ts.rgx ) {
602                         return;
603                 }
604                 ts.rgx = {
605                         IPAddress: [
606                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
607                         ],
608                         currency: [
609                                 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
610                                 new RegExp( /[£$€¥]/g)
611                         ],
612                         url: [
613                                 new RegExp( /^(https?|ftp|file):\/\/$/),
614                                 new RegExp( /(https?|ftp|file):\/\//)
615                         ],
616                         isoDate: [
617                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
618                         ],
619                         usLongDate: [
620                                 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)))$/)
621                         ],
622                         time: [
623                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
624                         ]
625                 };
626         }
628         /**
629          * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
630          * structure [ [ Integer , Integer ], ... ]
631          *
632          * @param sortObjects {Array} List of sort objects.
633          * @return {Array} List of internal sort definitions.
634          */
636         function convertSortList( sortObjects ) {
637                 var sortList = [];
638                 $.each( sortObjects, function( i, sortObject ) {
639                         $.each ( sortObject, function( columnIndex, order ) {
640                                 var orderIndex = ( order === 'desc' ) ? 1 : 0;
641                                 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
642                         } );
643                 } );
644                 return sortList;
645         }
647         /* Public scope */
649         $.tablesorter = {
651                         defaultOptions: {
652                                 cssHeader: 'headerSort',
653                                 cssAsc: 'headerSortUp',
654                                 cssDesc: 'headerSortDown',
655                                 cssChildRow: 'expand-child',
656                                 sortInitialOrder: 'asc',
657                                 sortMultiSortKey: 'shiftKey',
658                                 sortLocaleCompare: false,
659                                 unsortableClass: 'unsortable',
660                                 parsers: {},
661                                 widgets: [],
662                                 headers: {},
663                                 cancelSelection: true,
664                                 sortList: [],
665                                 headerList: [],
666                                 selectorHeaders: 'thead tr:eq(0) th',
667                                 debug: false
668                         },
670                         dateRegex: [],
671                         monthNames: {},
673                         /**
674                          * @param $tables {jQuery}
675                          * @param settings {Object} (optional)
676                          */
677                         construct: function ( $tables, settings ) {
678                                 return $tables.each( function ( i, table ) {
679                                         // Declare and cache.
680                                         var $headers, cache, config,
681                                                 $table = $( table ),
682                                                 firstTime = true;
684                                         // Quit if no tbody
685                                         if ( !table.tBodies ) {
686                                                 return;
687                                         }
688                                         if ( !table.tHead ) {
689                                                 // No thead found. Look for rows with <th>s and
690                                                 // move them into a <thead> tag or a <tfoot> tag
691                                                 emulateTHeadAndFoot( $table );
693                                                 // Still no thead? Then quit
694                                                 if ( !table.tHead ) {
695                                                         return;
696                                                 }
697                                         }
698                                         $table.addClass( 'jquery-tablesorter' );
700                                         // FIXME config should probably not be stored in the plain table node
701                                         // New config object.
702                                         table.config = {};
704                                         // Merge and extend.
705                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
707                                         // Save the settings where they read
708                                         $.data( table, 'tablesorter', { config: config } );
710                                         // Get the CSS class names, could be done else where.
711                                         var sortCSS = [ config.cssDesc, config.cssAsc ];
712                                         var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
714                                         // Build headers
715                                         $headers = buildHeaders( table, sortMsg );
717                                         // Grab and process locale settings
718                                         buildTransformTable();
719                                         buildDateTable();
720                                         buildCollationTable();
722                                         // Precaching regexps can bring 10 fold
723                                         // performance improvements in some browsers.
724                                         cacheRegexs();
726                                         function setupForFirstSort() {
727                                                 firstTime = false;
729                                                 // Legacy fix of .sortbottoms
730                                                 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
731                                                 // and put the <tfoot> at the end of the <table>
732                                                 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
733                                                 if ( $sortbottoms.length ) {
734                                                         var $tfoot = $table.children( 'tfoot' );
735                                                         if ( $tfoot.length ) {
736                                                                 $tfoot.eq(0).prepend( $sortbottoms );
737                                                         } else {
738                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
739                                                         }
740                                                 }
742                                                 explodeRowspans( $table );
744                                                 // try to auto detect column type, and store in tables config
745                                                 table.config.parsers = buildParserCache( table, $headers );
746                                         }
748                                         // Apply event handling to headers
749                                         // this is too big, perhaps break it out?
750                                         $headers.not( '.' + table.config.unsortableClass ).on( 'keypress click', function ( e ) {
751                                                 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
752                                                         // The user clicked on a link inside a table header.
753                                                         // Do nothing and let the default link click action continue.
754                                                         return true;
755                                                 }
757                                                 if ( e.type === 'keypress' && e.which !== 13 ) {
758                                                         // Only handle keypresses on the "Enter" key.
759                                                         return true;
760                                                 }
762                                                 if ( firstTime ) {
763                                                         setupForFirstSort();
764                                                 }
766                                                 // Build the cache for the tbody cells
767                                                 // to share between calculations for this sort action.
768                                                 // Re-calculated each time a sort action is performed due to possiblity
769                                                 // that sort values change. Shouldn't be too expensive, but if it becomes
770                                                 // too slow an event based system should be implemented somehow where
771                                                 // cells get event .change() and bubbles up to the <table> here
772                                                 cache = buildCache( table );
774                                                 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
775                                                 if ( !table.sortDisabled && totalRows > 0 ) {
776                                                         // Get current column sort order
777                                                         this.order = this.count % 2;
778                                                         this.count++;
780                                                         var cell = this;
781                                                         // Get current column index
782                                                         var columns = table.headerToColumns[ this.headerIndex ];
783                                                         var newSortList = $.map( columns, function (c) {
784                                                                 // jQuery "helpfully" flattens the arrays...
785                                                                 return [[c, cell.order]];
786                                                         });
787                                                         // Index of first column belonging to this header
788                                                         var i = columns[0];
790                                                         if ( !e[config.sortMultiSortKey] ) {
791                                                                 // User only wants to sort on one column set
792                                                                 // Flush the sort list and add new columns
793                                                                 config.sortList = newSortList;
794                                                         } else {
795                                                                 // Multi column sorting
796                                                                 // It is not possible for one column to belong to multiple headers,
797                                                                 // so this is okay - we don't need to check for every value in the columns array
798                                                                 if ( isValueInArray( i, config.sortList ) ) {
799                                                                         // The user has clicked on an already sorted column.
800                                                                         // Reverse the sorting direction for all tables.
801                                                                         for ( var j = 0; j < config.sortList.length; j++ ) {
802                                                                                 var s = config.sortList[j],
803                                                                                         o = config.headerList[s[0]];
804                                                                                 if ( isValueInArray( s[0], newSortList ) ) {
805                                                                                         o.count = s[1];
806                                                                                         o.count++;
807                                                                                         s[1] = o.count % 2;
808                                                                                 }
809                                                                         }
810                                                                 } else {
811                                                                         // Add columns to sort list array
812                                                                         config.sortList = config.sortList.concat( newSortList );
813                                                                 }
814                                                         }
816                                                         // Reset order/counts of cells not affected by sorting
817                                                         setHeadersOrder( $headers, config.sortList, table.headerToColumns );
819                                                         // Set CSS for headers
820                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, table.columnToHeader );
821                                                         appendToTable(
822                                                                 $table[0], multisort( $table[0], config.sortList, cache )
823                                                         );
825                                                         // Stop normal event by returning false
826                                                         return false;
827                                                 }
829                                         // Cancel selection
830                                         } ).mousedown( function () {
831                                                 if ( config.cancelSelection ) {
832                                                         this.onselectstart = function () {
833                                                                 return false;
834                                                         };
835                                                         return false;
836                                                 }
837                                         } );
839                                         /**
840                                          * Sorts the table. If no sorting is specified by passing a list of sort
841                                          * objects, the table is sorted according to the initial sorting order.
842                                          * Passing an empty array will reset sorting (basically just reset the headers
843                                          * making the table appear unsorted).
844                                          *
845                                          * @param sortList {Array} (optional) List of sort objects.
846                                          */
847                                         $table.data( 'tablesorter' ).sort = function( sortList ) {
849                                                 if ( firstTime ) {
850                                                         setupForFirstSort();
851                                                 }
853                                                 if ( sortList === undefined ) {
854                                                         sortList = config.sortList;
855                                                 } else if ( sortList.length > 0 ) {
856                                                         sortList = convertSortList( sortList );
857                                                 }
859                                                 // Set each column's sort count to be able to determine the correct sort
860                                                 // order when clicking on a header cell the next time
861                                                 setHeadersOrder( $headers, sortList, table.headerToColumns );
863                                                 // re-build the cache for the tbody cells
864                                                 cache = buildCache( table );
866                                                 // set css for headers
867                                                 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, table.columnToHeader );
869                                                 // sort the table and append it to the dom
870                                                 appendToTable( table, multisort( table, sortList, cache ) );
871                                         };
873                                         // sort initially
874                                         if ( config.sortList.length > 0 ) {
875                                                 setupForFirstSort();
876                                                 config.sortList = convertSortList( config.sortList );
877                                                 $table.data( 'tablesorter' ).sort();
878                                         }
880                                 } );
881                         },
883                         addParser: function ( parser ) {
884                                 var l = parsers.length,
885                                         a = true;
886                                 for ( var i = 0; i < l; i++ ) {
887                                         if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
888                                                 a = false;
889                                         }
890                                 }
891                                 if ( a ) {
892                                         parsers.push( parser );
893                                 }
894                         },
896                         formatDigit: function ( s ) {
897                                 var out, c, p, i;
898                                 if ( ts.transformTable !== false ) {
899                                         out = '';
900                                         for ( p = 0; p < s.length; p++ ) {
901                                                 c = s.charAt(p);
902                                                 if ( c in ts.transformTable ) {
903                                                         out += ts.transformTable[c];
904                                                 } else {
905                                                         out += c;
906                                                 }
907                                         }
908                                         s = out;
909                                 }
910                                 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
911                                 return isNaN( i ) ? 0 : i;
912                         },
914                         formatFloat: function ( s ) {
915                                 var i = parseFloat(s);
916                                 return isNaN( i ) ? 0 : i;
917                         },
919                         formatInt: function ( s ) {
920                                 var i = parseInt( s, 10 );
921                                 return isNaN( i ) ? 0 : i;
922                         },
924                         clearTableBody: function ( table ) {
925                                 $( table.tBodies[0] ).empty();
926                         }
927                 };
929         // Shortcut
930         ts = $.tablesorter;
932         // Register as jQuery prototype method
933         $.fn.tablesorter = function ( settings ) {
934                 return ts.construct( this, settings );
935         };
937         // Add default parsers
938         ts.addParser( {
939                 id: 'text',
940                 is: function () {
941                         return true;
942                 },
943                 format: function ( s ) {
944                         s = $.trim( s.toLowerCase() );
945                         if ( ts.collationRegex ) {
946                                 var tsc = ts.collationTable;
947                                 s = s.replace( ts.collationRegex, function ( match ) {
948                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
949                                         return r.toLowerCase();
950                                 } );
951                         }
952                         return s;
953                 },
954                 type: 'text'
955         } );
957         ts.addParser( {
958                 id: 'IPAddress',
959                 is: function ( s ) {
960                         return ts.rgx.IPAddress[0].test(s);
961                 },
962                 format: function ( s ) {
963                         var a = s.split( '.' ),
964                                 r = '',
965                                 l = a.length;
966                         for ( var i = 0; i < l; i++ ) {
967                                 var item = a[i];
968                                 if ( item.length === 1 ) {
969                                         r += '00' + item;
970                                 } else if ( item.length === 2 ) {
971                                         r += '0' + item;
972                                 } else {
973                                         r += item;
974                                 }
975                         }
976                         return $.tablesorter.formatFloat(r);
977                 },
978                 type: 'numeric'
979         } );
981         ts.addParser( {
982                 id: 'currency',
983                 is: function ( s ) {
984                         return ts.rgx.currency[0].test(s);
985                 },
986                 format: function ( s ) {
987                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
988                 },
989                 type: 'numeric'
990         } );
992         ts.addParser( {
993                 id: 'url',
994                 is: function ( s ) {
995                         return ts.rgx.url[0].test(s);
996                 },
997                 format: function ( s ) {
998                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
999                 },
1000                 type: 'text'
1001         } );
1003         ts.addParser( {
1004                 id: 'isoDate',
1005                 is: function ( s ) {
1006                         return ts.rgx.isoDate[0].test(s);
1007                 },
1008                 format: function ( s ) {
1009                         return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
1010                         new RegExp( /-/g), '/')).getTime() : '0' );
1011                 },
1012                 type: 'numeric'
1013         } );
1015         ts.addParser( {
1016                 id: 'usLongDate',
1017                 is: function ( s ) {
1018                         return ts.rgx.usLongDate[0].test(s);
1019                 },
1020                 format: function ( s ) {
1021                         return $.tablesorter.formatFloat( new Date(s).getTime() );
1022                 },
1023                 type: 'numeric'
1024         } );
1026         ts.addParser( {
1027                 id: 'date',
1028                 is: function ( s ) {
1029                         return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
1030                 },
1031                 format: function ( s ) {
1032                         var match;
1033                         s = $.trim( s.toLowerCase() );
1035                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1036                                 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1037                                         s = [ match[3], match[1], match[2] ];
1038                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1039                                         s = [ match[3], match[2], match[1] ];
1040                                 } else {
1041                                         // If we get here, we don't know which order the dd-dd-dddd
1042                                         // date is in. So return something not entirely invalid.
1043                                         return '99999999';
1044                                 }
1045                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1046                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1047                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1048                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1049                         } else {
1050                                 // Should never get here
1051                                 return '99999999';
1052                         }
1054                         // Pad Month and Day
1055                         if ( s[1].length === 1 ) {
1056                                 s[1] = '0' + s[1];
1057                         }
1058                         if ( s[2].length === 1 ) {
1059                                 s[2] = '0' + s[2];
1060                         }
1062                         var y;
1063                         if ( ( y = parseInt( s[0], 10) ) < 100 ) {
1064                                 // Guestimate years without centuries
1065                                 if ( y < 30 ) {
1066                                         s[0] = 2000 + y;
1067                                 } else {
1068                                         s[0] = 1900 + y;
1069                                 }
1070                         }
1071                         while ( s[0].length < 4 ) {
1072                                 s[0] = '0' + s[0];
1073                         }
1074                         return parseInt( s.join( '' ), 10 );
1075                 },
1076                 type: 'numeric'
1077         } );
1079         ts.addParser( {
1080                 id: 'time',
1081                 is: function ( s ) {
1082                         return ts.rgx.time[0].test(s);
1083                 },
1084                 format: function ( s ) {
1085                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1086                 },
1087                 type: 'numeric'
1088         } );
1090         ts.addParser( {
1091                 id: 'number',
1092                 is: function ( s ) {
1093                         return $.tablesorter.numberRegex.test( $.trim( s ));
1094                 },
1095                 format: function ( s ) {
1096                         return $.tablesorter.formatDigit(s);
1097                 },
1098                 type: 'numeric'
1099         } );
1101 }( jQuery, mediaWiki ) );