Implement extension registration from an extension.json file
[mediawiki.git] / resources / src / jquery / jquery.tablesorter.js
blob3918be7499b795ec9ffa594505de796206f5a2dd
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, wgDefaultDateFormat, wgContentLanguage)
12  * and mw.language.months.
13  *
14  * Uses 'tableSorterCollation' in mw.config (if available)
15  */
16 /**
17  *
18  * @description Create a sortable table with multi-column sorting capabilitys
19  *
20  * @example $( 'table' ).tablesorter();
21  * @desc Create a simple tablesorter interface.
22  *
23  * @example $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } );
24  * @desc Create a tablesorter interface initially sorting on the first and second column.
25  *
26  * @option String cssHeader ( optional ) A string of the class name to be appended
27  *         to sortable tr elements in the thead of the table. Default value:
28  *         "header"
29  *
30  * @option String cssAsc ( optional ) A string of the class name to be appended to
31  *         sortable tr elements in the thead on a ascending sort. Default value:
32  *         "headerSortUp"
33  *
34  * @option String cssDesc ( optional ) A string of the class name to be appended
35  *         to sortable tr elements in the thead on a descending sort. Default
36  *         value: "headerSortDown"
37  *
38  * @option String sortMultisortKey ( optional ) A string of the multi-column sort
39  *         key. Default value: "shiftKey"
40  *
41  * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
42  *         tablesorter should cancel selection of the table headers text.
43  *         Default value: true
44  *
45  * @option Array sortList ( optional ) An array containing objects specifying sorting.
46  *         By passing more than one object, multi-sorting will be applied. Object structure:
47  *         { <Integer column index>: <String 'asc' or 'desc'> }
48  *         Default value: []
49  *
50  * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
51  *
52  * @type jQuery
53  *
54  * @name tablesorter
55  *
56  * @cat Plugins/Tablesorter
57  *
58  * @author Christian Bach/christian.bach@polyester.se
59  */
61 ( function ( $, mw ) {
62         /* Local scope */
64         var ts,
65                 parsers = [];
67         /* Parser utility functions */
69         function getParserById( name ) {
70                 var i,
71                         len = parsers.length;
72                 for ( i = 0; i < len; i++ ) {
73                         if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
74                                 return parsers[i];
75                         }
76                 }
77                 return false;
78         }
80         function getElementSortKey( node ) {
81                 var $node = $( node ),
82                         // Use data-sort-value attribute.
83                         // Use data() instead of attr() so that live value changes
84                         // are processed as well (bug 38152).
85                         data = $node.data( 'sortValue' );
87                 if ( data !== null && data !== undefined ) {
88                         // Cast any numbers or other stuff to a string, methods
89                         // like charAt, toLowerCase and split are expected.
90                         return String( data );
91                 } else {
92                         if ( !node ) {
93                                 return $node.text();
94                         } else if ( node.tagName.toLowerCase() === 'img' ) {
95                                 return $node.attr( 'alt' ) || ''; // handle undefined alt
96                         } else {
97                                 return $.map( $.makeArray( node.childNodes ), function ( elem ) {
98                                         // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
99                                         if ( elem.nodeType === 1 ) {
100                                                 return getElementSortKey( elem );
101                                         } else {
102                                                 return $.text( elem );
103                                         }
104                                 } ).join( '' );
105                         }
106                 }
107         }
109         function detectParserForColumn( table, rows, cellIndex ) {
110                 var l = parsers.length,
111                         nodeValue,
112                         // Start with 1 because 0 is the fallback parser
113                         i = 1,
114                         rowIndex = 0,
115                         concurrent = 0,
116                         needed = ( rows.length > 4 ) ? 5 : rows.length;
118                 while ( i < l ) {
119                         if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
120                                 nodeValue = $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
121                         } else {
122                                 nodeValue = '';
123                         }
125                         if ( nodeValue !== '' ) {
126                                 if ( parsers[i].is( nodeValue, table ) ) {
127                                         concurrent++;
128                                         rowIndex++;
129                                         if ( concurrent >= needed ) {
130                                                 // Confirmed the parser for multiple cells, let's return it
131                                                 return parsers[i];
132                                         }
133                                 } else {
134                                         // Check next parser, reset rows
135                                         i++;
136                                         rowIndex = 0;
137                                         concurrent = 0;
138                                 }
139                         } else {
140                                 // Empty cell
141                                 rowIndex++;
142                                 if ( rowIndex > rows.length ) {
143                                         rowIndex = 0;
144                                         i++;
145                                 }
146                         }
147                 }
149                 // 0 is always the generic parser (text)
150                 return parsers[0];
151         }
153         function buildParserCache( table, $headers ) {
154                 var sortType, cells, len, i, parser,
155                         rows = table.tBodies[0].rows,
156                         parsers = [];
158                 if ( rows[0] ) {
160                         cells = rows[0].cells;
161                         len = cells.length;
163                         for ( i = 0; i < len; i++ ) {
164                                 parser = false;
165                                 sortType = $headers.eq( i ).data( 'sortType' );
166                                 if ( sortType !== undefined ) {
167                                         parser = getParserById( sortType );
168                                 }
170                                 if ( parser === false ) {
171                                         parser = detectParserForColumn( table, rows, i );
172                                 }
174                                 parsers.push( parser );
175                         }
176                 }
177                 return parsers;
178         }
180         /* Other utility functions */
182         function buildCache( table ) {
183                 var i, j, $row, cols,
184                         totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
185                         totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
186                         config = $( table ).data( 'tablesorter' ).config,
187                         parsers = config.parsers,
188                         cache = {
189                                 row: [],
190                                 normalized: []
191                         };
193                 for ( i = 0; i < totalRows; ++i ) {
195                         // Add the table data to main data array
196                         $row = $( table.tBodies[0].rows[i] );
197                         cols = [];
199                         // if this is a child row, add it to the last row's children and
200                         // continue to the next row
201                         if ( $row.hasClass( config.cssChildRow ) ) {
202                                 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
203                                 // go to the next for loop
204                                 continue;
205                         }
207                         cache.row.push( $row );
209                         for ( j = 0; j < totalCells; ++j ) {
210                                 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
211                         }
213                         cols.push( cache.normalized.length ); // add position for rowCache
214                         cache.normalized.push( cols );
215                         cols = null;
216                 }
218                 return cache;
219         }
221         function appendToTable( table, cache ) {
222                 var i, pos, l, j,
223                         row = cache.row,
224                         normalized = cache.normalized,
225                         totalRows = normalized.length,
226                         checkCell = ( normalized[0].length - 1 ),
227                         fragment = document.createDocumentFragment();
229                 for ( i = 0; i < totalRows; i++ ) {
230                         pos = normalized[i][checkCell];
232                         l = row[pos].length;
234                         for ( j = 0; j < l; j++ ) {
235                                 fragment.appendChild( row[pos][j] );
236                         }
238                 }
239                 table.tBodies[0].appendChild( fragment );
241                 $( table ).trigger( 'sortEnd.tablesorter' );
242         }
244         /**
245          * Find all header rows in a thead-less table and put them in a <thead> tag.
246          * This only treats a row as a header row if it contains only <th>s (no <td>s)
247          * and if it is preceded entirely by header rows. The algorithm stops when
248          * it encounters the first non-header row.
249          *
250          * After this, it will look at all rows at the bottom for footer rows
251          * And place these in a tfoot using similar rules.
252          * @param $table jQuery object for a <table>
253          */
254         function emulateTHeadAndFoot( $table ) {
255                 var $thead, $tfoot, i, len,
256                         $rows = $table.find( '> tbody > tr' );
257                 if ( !$table.get( 0 ).tHead ) {
258                         $thead = $( '<thead>' );
259                         $rows.each( function () {
260                                 if ( $( this ).children( 'td' ).length ) {
261                                         // This row contains a <td>, so it's not a header row
262                                         // Stop here
263                                         return false;
264                                 }
265                                 $thead.append( this );
266                         } );
267                         $table.find( ' > tbody:first' ).before( $thead );
268                 }
269                 if ( !$table.get( 0 ).tFoot ) {
270                         $tfoot = $( '<tfoot>' );
271                         len = $rows.length;
272                         for ( i = len - 1; i >= 0; i-- ) {
273                                 if ( $( $rows[i] ).children( 'td' ).length ) {
274                                         break;
275                                 }
276                                 $tfoot.prepend( $( $rows[i] ) );
277                         }
278                         $table.append( $tfoot );
279                 }
280         }
282         function buildHeaders( table, msg ) {
283                 var config = $( table ).data( 'tablesorter' ).config,
284                         maxSeen = 0,
285                         colspanOffset = 0,
286                         columns,
287                         i,
288                         $cell,
289                         rowspan,
290                         colspan,
291                         headerCount,
292                         longestTR,
293                         exploded,
294                         $tableHeaders = $( [] ),
295                         $tableRows = $( 'thead:eq(0) > tr', table );
296                 if ( $tableRows.length <= 1 ) {
297                         $tableHeaders = $tableRows.children( 'th' );
298                 } else {
299                         exploded = [];
301                         // Loop through all the dom cells of the thead
302                         $tableRows.each( function ( rowIndex, row ) {
303                                 $.each( row.cells, function ( columnIndex, cell ) {
304                                         var matrixRowIndex,
305                                                 matrixColumnIndex;
307                                         rowspan = Number( cell.rowSpan );
308                                         colspan = Number( cell.colSpan );
310                                         // Skip the spots in the exploded matrix that are already filled
311                                         while ( exploded[rowIndex] && exploded[rowIndex][columnIndex] !== undefined ) {
312                                                 ++columnIndex;
313                                         }
315                                         // Find the actual dimensions of the thead, by placing each cell
316                                         // in the exploded matrix rowspan times colspan times, with the proper offsets
317                                         for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
318                                                 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
319                                                         if ( !exploded[matrixRowIndex] ) {
320                                                                 exploded[matrixRowIndex] = [];
321                                                         }
322                                                         exploded[matrixRowIndex][matrixColumnIndex] = cell;
323                                                 }
324                                         }
325                                 } );
326                         } );
327                         // We want to find the row that has the most columns (ignoring colspan)
328                         $.each( exploded, function ( index, cellArray ) {
329                                 headerCount = $( uniqueElements( cellArray ) ).filter( 'th' ).length;
330                                 if ( headerCount >= maxSeen ) {
331                                         maxSeen = headerCount;
332                                         longestTR = index;
333                                 }
334                         } );
335                         // We cannot use $.unique() here because it sorts into dom order, which is undesirable
336                         $tableHeaders = $( uniqueElements( exploded[longestTR] ) ).filter( 'th' );
337                 }
339                 // as each header can span over multiple columns (using colspan=N),
340                 // we have to bidirectionally map headers to their columns and columns to their headers
341                 $tableHeaders.each( function ( headerIndex ) {
342                         $cell = $( this );
343                         columns = [];
345                         for ( i = 0; i < this.colSpan; i++ ) {
346                                 config.columnToHeader[ colspanOffset + i ] = headerIndex;
347                                 columns.push( colspanOffset + i );
348                         }
350                         config.headerToColumns[ headerIndex ] = columns;
351                         colspanOffset += this.colSpan;
353                         $cell.data( {
354                                 headerIndex: headerIndex,
355                                 order: 0,
356                                 count: 0
357                         } );
359                         if ( $cell.hasClass( config.unsortableClass ) ) {
360                                 $cell.data( 'sortDisabled', true );
361                         }
363                         if ( !$cell.data( 'sortDisabled' ) ) {
364                                 $cell
365                                         .addClass( config.cssHeader )
366                                         .prop( 'tabIndex', 0 )
367                                         .attr( {
368                                                 role: 'columnheader button',
369                                                 title: msg[1]
370                                         } );
371                         }
373                         // add cell to headerList
374                         config.headerList[headerIndex] = this;
375                 } );
377                 return $tableHeaders;
379         }
381         /**
382          * Sets the sort count of the columns that are not affected by the sorting to have them sorted
383          * in default (ascending) order when their header cell is clicked the next time.
384          *
385          * @param {jQuery} $headers
386          * @param {Number[][]} sortList
387          * @param {Number[][]} headerToColumns
388          */
389         function setHeadersOrder( $headers, sortList, headerToColumns ) {
390                 // Loop through all headers to retrieve the indices of the columns the header spans across:
391                 $.each( headerToColumns, function ( headerIndex, columns ) {
393                         $.each( columns, function ( i, columnIndex ) {
394                                 var header = $headers[headerIndex],
395                                         $header = $( header );
397                                 if ( !isValueInArray( columnIndex, sortList ) ) {
398                                         // Column shall not be sorted: Reset header count and order.
399                                         $header.data( {
400                                                 order: 0,
401                                                 count: 0
402                                         } );
403                                 } else {
404                                         // Column shall be sorted: Apply designated count and order.
405                                         $.each( sortList, function ( j, sortColumn ) {
406                                                 if ( sortColumn[0] === i ) {
407                                                         $header.data( {
408                                                                 order: sortColumn[1],
409                                                                 count: sortColumn[1] + 1
410                                                         } );
411                                                         return false;
412                                                 }
413                                         } );
414                                 }
415                         } );
417                 } );
418         }
420         function isValueInArray( v, a ) {
421                 var i,
422                         len = a.length;
423                 for ( i = 0; i < len; i++ ) {
424                         if ( a[i][0] === v ) {
425                                 return true;
426                         }
427                 }
428                 return false;
429         }
431         function uniqueElements( array ) {
432                 var uniques = [];
433                 $.each( array, function ( index, elem ) {
434                         if ( elem !== undefined && $.inArray( elem, uniques ) === -1 ) {
435                                 uniques.push( elem );
436                         }
437                 } );
438                 return uniques;
439         }
441         function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
442                 // Remove all header information and reset titles to default message
443                 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
445                 for ( var i = 0; i < list.length; i++ ) {
446                         $headers.eq( columnToHeader[ list[i][0] ] )
447                                 .addClass( css[ list[i][1] ] )
448                                 .attr( 'title', msg[ list[i][1] ] );
449                 }
450         }
452         function sortText( a, b ) {
453                 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
454         }
456         function sortTextDesc( a, b ) {
457                 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
458         }
460         function multisort( table, sortList, cache ) {
461                 var i,
462                         sortFn = [],
463                         len = sortList.length;
464                 for ( i = 0; i < len; i++ ) {
465                         sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
466                 }
467                 cache.normalized.sort( function ( array1, array2 ) {
468                         var i, col, ret;
469                         for ( i = 0; i < len; i++ ) {
470                                 col = sortList[i][0];
471                                 ret = sortFn[i].call( this, array1[col], array2[col] );
472                                 if ( ret !== 0 ) {
473                                         return ret;
474                                 }
475                         }
476                         // Fall back to index number column to ensure stable sort
477                         return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
478                 } );
479                 return cache;
480         }
482         function buildTransformTable() {
483                 var ascii, localised, i, digitClass,
484                         digits = '0123456789,.'.split( '' ),
485                         separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
486                         digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
488                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
489                         ts.transformTable = false;
490                 } else {
491                         ts.transformTable = {};
493                         // Unpack the transform table
494                         ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
495                         localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
497                         // Construct regex for number identification
498                         for ( i = 0; i < ascii.length; i++ ) {
499                                 ts.transformTable[localised[i]] = ascii[i];
500                                 digits.push( $.escapeRE( localised[i] ) );
501                         }
502                 }
503                 digitClass = '[' + digits.join( '', digits ) + ']';
505                 // We allow a trailing percent sign, which we just strip. This works fine
506                 // if percents and regular numbers aren't being mixed.
507                 ts.numberRegex = new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
508                 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
509                 ')$', 'i' );
510         }
512         function buildDateTable() {
513                 var i, name,
514                         regex = [];
516                 ts.monthNames = {};
518                 for ( i = 0; i < 12; i++ ) {
519                         name = mw.language.months.names[i].toLowerCase();
520                         ts.monthNames[name] = i + 1;
521                         regex.push( $.escapeRE( name ) );
522                         name = mw.language.months.genitive[i].toLowerCase();
523                         ts.monthNames[name] = i + 1;
524                         regex.push( $.escapeRE( name ) );
525                         name = mw.language.months.abbrev[i].toLowerCase().replace( '.', '' );
526                         ts.monthNames[name] = i + 1;
527                         regex.push( $.escapeRE( name ) );
528                 }
530                 // Build piped string
531                 regex = regex.join( '|' );
533                 // Build RegEx
534                 // Any date formated with . , ' - or /
535                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
537                 // Written Month name, dmy
538                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
540                 // Written Month name, mdy
541                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
543         }
545         /**
546          * Replace all rowspanned cells in the body with clones in each row, so sorting
547          * need not worry about them.
548          *
549          * @param $table jQuery object for a <table>
550          */
551         function explodeRowspans( $table ) {
552                 var spanningRealCellIndex, rowSpan, colSpan,
553                         cell, cellData, i, $tds, $clone, $nextRows,
554                         rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
556                 // Short circuit
557                 if ( !rowspanCells.length ) {
558                         return;
559                 }
561                 // First, we need to make a property like cellIndex but taking into
562                 // account colspans. We also cache the rowIndex to avoid having to take
563                 // cell.parentNode.rowIndex in the sorting function below.
564                 $table.find( '> tbody > tr' ).each( function () {
565                         var i,
566                                 col = 0,
567                                 l = this.cells.length;
568                         for ( i = 0; i < l; i++ ) {
569                                 $( this.cells[i] ).data( 'tablesorter', {
570                                         realCellIndex: col,
571                                         realRowIndex: this.rowIndex
572                                 } );
573                                 col += this.cells[i].colSpan;
574                         }
575                 } );
577                 // Split multi row cells into multiple cells with the same content.
578                 // Sort by column then row index to avoid problems with odd table structures.
579                 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
580                 // might change the sort order.
581                 function resortCells() {
582                         var cellAData,
583                                 cellBData,
584                                 ret;
585                         rowspanCells = rowspanCells.sort( function ( a, b ) {
586                                 cellAData = $.data( a, 'tablesorter' );
587                                 cellBData = $.data( b, 'tablesorter' );
588                                 ret = cellAData.realCellIndex - cellBData.realCellIndex;
589                                 if ( !ret ) {
590                                         ret = cellAData.realRowIndex - cellBData.realRowIndex;
591                                 }
592                                 return ret;
593                         } );
594                         $.each( rowspanCells, function () {
595                                 $.data( this, 'tablesorter' ).needResort = false;
596                         } );
597                 }
598                 resortCells();
600                 function filterfunc() {
601                         return $.data( this, 'tablesorter' ).realCellIndex >= spanningRealCellIndex;
602                 }
604                 function fixTdCellIndex() {
605                         $.data( this, 'tablesorter' ).realCellIndex += colSpan;
606                         if ( this.rowSpan > 1 ) {
607                                 $.data( this, 'tablesorter' ).needResort = true;
608                         }
609                 }
611                 while ( rowspanCells.length ) {
612                         if ( $.data( rowspanCells[0], 'tablesorter' ).needResort ) {
613                                 resortCells();
614                         }
616                         cell = rowspanCells.shift();
617                         cellData = $.data( cell, 'tablesorter' );
618                         rowSpan = cell.rowSpan;
619                         colSpan = cell.colSpan;
620                         spanningRealCellIndex = cellData.realCellIndex;
621                         cell.rowSpan = 1;
622                         $nextRows = $( cell ).parent().nextAll();
623                         for ( i = 0; i < rowSpan - 1; i++ ) {
624                                 $tds = $( $nextRows[i].cells ).filter( filterfunc );
625                                 $clone = $( cell ).clone();
626                                 $clone.data( 'tablesorter', {
627                                         realCellIndex: spanningRealCellIndex,
628                                         realRowIndex: cellData.realRowIndex + i,
629                                         needResort: true
630                                 } );
631                                 if ( $tds.length ) {
632                                         $tds.each( fixTdCellIndex );
633                                         $tds.first().before( $clone );
634                                 } else {
635                                         $nextRows.eq( i ).append( $clone );
636                                 }
637                         }
638                 }
639         }
641         function buildCollationTable() {
642                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
643                 ts.collationRegex = null;
644                 if ( ts.collationTable ) {
645                         var key,
646                                 keys = [];
648                         // Build array of key names
649                         for ( key in ts.collationTable ) {
650                                 // Check hasOwn to be safe
651                                 if ( ts.collationTable.hasOwnProperty( key ) ) {
652                                         keys.push( key );
653                                 }
654                         }
655                         if ( keys.length ) {
656                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
657                         }
658                 }
659         }
661         function cacheRegexs() {
662                 if ( ts.rgx ) {
663                         return;
664                 }
665                 ts.rgx = {
666                         IPAddress: [
667                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
668                         ],
669                         currency: [
670                                 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
671                                 new RegExp( /[£$€¥]/g )
672                         ],
673                         url: [
674                                 new RegExp( /^(https?|ftp|file):\/\/$/ ),
675                                 new RegExp( /(https?|ftp|file):\/\// )
676                         ],
677                         isoDate: [
678                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
679                         ],
680                         usLongDate: [
681                                 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)))$/ )
682                         ],
683                         time: [
684                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
685                         ]
686                 };
687         }
689         /**
690          * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
691          * structure [ [ Integer , Integer ], ... ]
692          *
693          * @param sortObjects {Array} List of sort objects.
694          * @return {Array} List of internal sort definitions.
695          */
697         function convertSortList( sortObjects ) {
698                 var sortList = [];
699                 $.each( sortObjects, function ( i, sortObject ) {
700                         $.each( sortObject, function ( columnIndex, order ) {
701                                 var orderIndex = ( order === 'desc' ) ? 1 : 0;
702                                 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
703                         } );
704                 } );
705                 return sortList;
706         }
708         /* Public scope */
710         $.tablesorter = {
712                         defaultOptions: {
713                                 cssHeader: 'headerSort',
714                                 cssAsc: 'headerSortUp',
715                                 cssDesc: 'headerSortDown',
716                                 cssChildRow: 'expand-child',
717                                 sortMultiSortKey: 'shiftKey',
718                                 unsortableClass: 'unsortable',
719                                 parsers: {},
720                                 cancelSelection: true,
721                                 sortList: [],
722                                 headerList: [],
723                                 headerToColumns: [],
724                                 columnToHeader: []
725                         },
727                         dateRegex: [],
728                         monthNames: {},
730                         /**
731                          * @param $tables {jQuery}
732                          * @param settings {Object} (optional)
733                          */
734                         construct: function ( $tables, settings ) {
735                                 return $tables.each( function ( i, table ) {
736                                         // Declare and cache.
737                                         var $headers, cache, config, sortCSS, sortMsg,
738                                                 $table = $( table ),
739                                                 firstTime = true;
741                                         // Quit if no tbody
742                                         if ( !table.tBodies ) {
743                                                 return;
744                                         }
745                                         if ( !table.tHead ) {
746                                                 // No thead found. Look for rows with <th>s and
747                                                 // move them into a <thead> tag or a <tfoot> tag
748                                                 emulateTHeadAndFoot( $table );
750                                                 // Still no thead? Then quit
751                                                 if ( !table.tHead ) {
752                                                         return;
753                                                 }
754                                         }
755                                         $table.addClass( 'jquery-tablesorter' );
757                                         // Merge and extend
758                                         config = $.extend( {}, $.tablesorter.defaultOptions, settings );
760                                         // Save the settings where they read
761                                         $.data( table, 'tablesorter', { config: config } );
763                                         // Get the CSS class names, could be done elsewhere
764                                         sortCSS = [ config.cssDesc, config.cssAsc ];
765                                         sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
767                                         // Build headers
768                                         $headers = buildHeaders( table, sortMsg );
770                                         // Grab and process locale settings.
771                                         buildTransformTable();
772                                         buildDateTable();
774                                         // Precaching regexps can bring 10 fold
775                                         // performance improvements in some browsers.
776                                         cacheRegexs();
778                                         function setupForFirstSort() {
779                                                 firstTime = false;
781                                                 // Defer buildCollationTable to first sort. As user and site scripts
782                                                 // may customize tableSorterCollation but load after $.ready(), other
783                                                 // scripts may call .tablesorter() before they have done the
784                                                 // tableSorterCollation customizations.
785                                                 buildCollationTable();
787                                                 // Legacy fix of .sortbottoms
788                                                 // Wrap them inside a tfoot (because that's what they actually want to be)
789                                                 // and put the <tfoot> at the end of the <table>
790                                                 var $tfoot,
791                                                         $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
792                                                 if ( $sortbottoms.length ) {
793                                                         $tfoot = $table.children( 'tfoot' );
794                                                         if ( $tfoot.length ) {
795                                                                 $tfoot.eq( 0 ).prepend( $sortbottoms );
796                                                         } else {
797                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
798                                                         }
799                                                 }
801                                                 explodeRowspans( $table );
803                                                 // Try to auto detect column type, and store in tables config
804                                                 config.parsers = buildParserCache( table, $headers );
805                                         }
807                                         // Apply event handling to headers
808                                         // this is too big, perhaps break it out?
809                                         $headers.not( '.' + config.unsortableClass ).on( 'keypress click', function ( e ) {
810                                                 var cell, $cell, columns, newSortList, i,
811                                                         totalRows,
812                                                         j, s, o;
814                                                 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
815                                                         // The user clicked on a link inside a table header.
816                                                         // Do nothing and let the default link click action continue.
817                                                         return true;
818                                                 }
820                                                 if ( e.type === 'keypress' && e.which !== 13 ) {
821                                                         // Only handle keypresses on the "Enter" key.
822                                                         return true;
823                                                 }
825                                                 if ( firstTime ) {
826                                                         setupForFirstSort();
827                                                 }
829                                                 // Build the cache for the tbody cells
830                                                 // to share between calculations for this sort action.
831                                                 // Re-calculated each time a sort action is performed due to possiblity
832                                                 // that sort values change. Shouldn't be too expensive, but if it becomes
833                                                 // too slow an event based system should be implemented somehow where
834                                                 // cells get event .change() and bubbles up to the <table> here
835                                                 cache = buildCache( table );
837                                                 totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
838                                                 if ( !table.sortDisabled && totalRows > 0 ) {
839                                                         cell = this;
840                                                         $cell = $( cell );
842                                                         // Get current column sort order
843                                                         $cell.data( {
844                                                                 order: $cell.data( 'count' ) % 2,
845                                                                 count: $cell.data( 'count' ) + 1
846                                                         } );
848                                                         cell = this;
849                                                         // Get current column index
850                                                         columns = config.headerToColumns[ $cell.data( 'headerIndex' ) ];
851                                                         newSortList = $.map( columns, function ( c ) {
852                                                                 // jQuery "helpfully" flattens the arrays...
853                                                                 return [[c, $cell.data( 'order' )]];
854                                                         } );
855                                                         // Index of first column belonging to this header
856                                                         i = columns[0];
858                                                         if ( !e[config.sortMultiSortKey] ) {
859                                                                 // User only wants to sort on one column set
860                                                                 // Flush the sort list and add new columns
861                                                                 config.sortList = newSortList;
862                                                         } else {
863                                                                 // Multi column sorting
864                                                                 // It is not possible for one column to belong to multiple headers,
865                                                                 // so this is okay - we don't need to check for every value in the columns array
866                                                                 if ( isValueInArray( i, config.sortList ) ) {
867                                                                         // The user has clicked on an already sorted column.
868                                                                         // Reverse the sorting direction for all tables.
869                                                                         for ( j = 0; j < config.sortList.length; j++ ) {
870                                                                                 s = config.sortList[j];
871                                                                                 o = config.headerList[s[0]];
872                                                                                 if ( isValueInArray( s[0], newSortList ) ) {
873                                                                                         $( o ).data( 'count', s[1] + 1 );
874                                                                                         s[1] = $( o ).data( 'count' ) % 2;
875                                                                                 }
876                                                                         }
877                                                                 } else {
878                                                                         // Add columns to sort list array
879                                                                         config.sortList = config.sortList.concat( newSortList );
880                                                                 }
881                                                         }
883                                                         // Reset order/counts of cells not affected by sorting
884                                                         setHeadersOrder( $headers, config.sortList, config.headerToColumns );
886                                                         // Set CSS for headers
887                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, config.columnToHeader );
888                                                         appendToTable(
889                                                                 $table[0], multisort( $table[0], config.sortList, cache )
890                                                         );
892                                                         // Stop normal event by returning false
893                                                         return false;
894                                                 }
896                                         // Cancel selection
897                                         } ).mousedown( function () {
898                                                 if ( config.cancelSelection ) {
899                                                         this.onselectstart = function () {
900                                                                 return false;
901                                                         };
902                                                         return false;
903                                                 }
904                                         } );
906                                         /**
907                                          * Sorts the table. If no sorting is specified by passing a list of sort
908                                          * objects, the table is sorted according to the initial sorting order.
909                                          * Passing an empty array will reset sorting (basically just reset the headers
910                                          * making the table appear unsorted).
911                                          *
912                                          * @param sortList {Array} (optional) List of sort objects.
913                                          */
914                                         $table.data( 'tablesorter' ).sort = function ( sortList ) {
916                                                 if ( firstTime ) {
917                                                         setupForFirstSort();
918                                                 }
920                                                 if ( sortList === undefined ) {
921                                                         sortList = config.sortList;
922                                                 } else if ( sortList.length > 0 ) {
923                                                         sortList = convertSortList( sortList );
924                                                 }
926                                                 // Set each column's sort count to be able to determine the correct sort
927                                                 // order when clicking on a header cell the next time
928                                                 setHeadersOrder( $headers, sortList, config.headerToColumns );
930                                                 // re-build the cache for the tbody cells
931                                                 cache = buildCache( table );
933                                                 // set css for headers
934                                                 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, config.columnToHeader );
936                                                 // sort the table and append it to the dom
937                                                 appendToTable( table, multisort( table, sortList, cache ) );
938                                         };
940                                         // sort initially
941                                         if ( config.sortList.length > 0 ) {
942                                                 setupForFirstSort();
943                                                 config.sortList = convertSortList( config.sortList );
944                                                 $table.data( 'tablesorter' ).sort();
945                                         }
947                                 } );
948                         },
950                         addParser: function ( parser ) {
951                                 var i,
952                                         len = parsers.length,
953                                         a = true;
954                                 for ( i = 0; i < len; i++ ) {
955                                         if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
956                                                 a = false;
957                                         }
958                                 }
959                                 if ( a ) {
960                                         parsers.push( parser );
961                                 }
962                         },
964                         formatDigit: function ( s ) {
965                                 var out, c, p, i;
966                                 if ( ts.transformTable !== false ) {
967                                         out = '';
968                                         for ( p = 0; p < s.length; p++ ) {
969                                                 c = s.charAt( p );
970                                                 if ( c in ts.transformTable ) {
971                                                         out += ts.transformTable[c];
972                                                 } else {
973                                                         out += c;
974                                                 }
975                                         }
976                                         s = out;
977                                 }
978                                 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
979                                 return isNaN( i ) ? 0 : i;
980                         },
982                         formatFloat: function ( s ) {
983                                 var i = parseFloat( s );
984                                 return isNaN( i ) ? 0 : i;
985                         },
987                         formatInt: function ( s ) {
988                                 var i = parseInt( s, 10 );
989                                 return isNaN( i ) ? 0 : i;
990                         },
992                         clearTableBody: function ( table ) {
993                                 $( table.tBodies[0] ).empty();
994                         }
995                 };
997         // Shortcut
998         ts = $.tablesorter;
1000         // Register as jQuery prototype method
1001         $.fn.tablesorter = function ( settings ) {
1002                 return ts.construct( this, settings );
1003         };
1005         // Add default parsers
1006         ts.addParser( {
1007                 id: 'text',
1008                 is: function () {
1009                         return true;
1010                 },
1011                 format: function ( s ) {
1012                         s = $.trim( s.toLowerCase() );
1013                         if ( ts.collationRegex ) {
1014                                 var tsc = ts.collationTable;
1015                                 s = s.replace( ts.collationRegex, function ( match ) {
1016                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
1017                                         return r.toLowerCase();
1018                                 } );
1019                         }
1020                         return s;
1021                 },
1022                 type: 'text'
1023         } );
1025         ts.addParser( {
1026                 id: 'IPAddress',
1027                 is: function ( s ) {
1028                         return ts.rgx.IPAddress[0].test( s );
1029                 },
1030                 format: function ( s ) {
1031                         var i, item,
1032                                 a = s.split( '.' ),
1033                                 r = '',
1034                                 len = a.length;
1035                         for ( i = 0; i < len; i++ ) {
1036                                 item = a[i];
1037                                 if ( item.length === 1 ) {
1038                                         r += '00' + item;
1039                                 } else if ( item.length === 2 ) {
1040                                         r += '0' + item;
1041                                 } else {
1042                                         r += item;
1043                                 }
1044                         }
1045                         return $.tablesorter.formatFloat( r );
1046                 },
1047                 type: 'numeric'
1048         } );
1050         ts.addParser( {
1051                 id: 'currency',
1052                 is: function ( s ) {
1053                         return ts.rgx.currency[0].test( s );
1054                 },
1055                 format: function ( s ) {
1056                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
1057                 },
1058                 type: 'numeric'
1059         } );
1061         ts.addParser( {
1062                 id: 'url',
1063                 is: function ( s ) {
1064                         return ts.rgx.url[0].test( s );
1065                 },
1066                 format: function ( s ) {
1067                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
1068                 },
1069                 type: 'text'
1070         } );
1072         ts.addParser( {
1073                 id: 'isoDate',
1074                 is: function ( s ) {
1075                         return ts.rgx.isoDate[0].test( s );
1076                 },
1077                 format: function ( s ) {
1078                         return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
1079                         new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1080                 },
1081                 type: 'numeric'
1082         } );
1084         ts.addParser( {
1085                 id: 'usLongDate',
1086                 is: function ( s ) {
1087                         return ts.rgx.usLongDate[0].test( s );
1088                 },
1089                 format: function ( s ) {
1090                         return $.tablesorter.formatFloat( new Date( s ).getTime() );
1091                 },
1092                 type: 'numeric'
1093         } );
1095         ts.addParser( {
1096                 id: 'date',
1097                 is: function ( s ) {
1098                         return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1099                 },
1100                 format: function ( s ) {
1101                         var match, y;
1102                         s = $.trim( s.toLowerCase() );
1104                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1105                                 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1106                                         s = [ match[3], match[1], match[2] ];
1107                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1108                                         s = [ match[3], match[2], match[1] ];
1109                                 } else {
1110                                         // If we get here, we don't know which order the dd-dd-dddd
1111                                         // date is in. So return something not entirely invalid.
1112                                         return '99999999';
1113                                 }
1114                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1115                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1116                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1117                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1118                         } else {
1119                                 // Should never get here
1120                                 return '99999999';
1121                         }
1123                         // Pad Month and Day
1124                         if ( s[1].length === 1 ) {
1125                                 s[1] = '0' + s[1];
1126                         }
1127                         if ( s[2].length === 1 ) {
1128                                 s[2] = '0' + s[2];
1129                         }
1131                         if ( ( y = parseInt( s[0], 10 ) ) < 100 ) {
1132                                 // Guestimate years without centuries
1133                                 if ( y < 30 ) {
1134                                         s[0] = 2000 + y;
1135                                 } else {
1136                                         s[0] = 1900 + y;
1137                                 }
1138                         }
1139                         while ( s[0].length < 4 ) {
1140                                 s[0] = '0' + s[0];
1141                         }
1142                         return parseInt( s.join( '' ), 10 );
1143                 },
1144                 type: 'numeric'
1145         } );
1147         ts.addParser( {
1148                 id: 'time',
1149                 is: function ( s ) {
1150                         return ts.rgx.time[0].test( s );
1151                 },
1152                 format: function ( s ) {
1153                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1154                 },
1155                 type: 'numeric'
1156         } );
1158         ts.addParser( {
1159                 id: 'number',
1160                 is: function ( s ) {
1161                         return $.tablesorter.numberRegex.test( $.trim( s ) );
1162                 },
1163                 format: function ( s ) {
1164                         return $.tablesorter.formatDigit( s );
1165                 },
1166                 type: 'numeric'
1167         } );
1169 }( jQuery, mediaWiki ) );