PrefixSearch: Avoid notice when no subpage exists
[mediawiki.git] / resources / src / jquery / jquery.tablesorter.js
blob5b1e2a7f305d48ea7e73cdc178590de46624847e
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 sortInitialOrder ( optional ) A string of the inital sorting
39  *         order can be asc or desc. Default value: "asc"
40  *
41  * @option String sortMultisortKey ( optional ) A string of the multi-column sort
42  *         key. Default value: "shiftKey"
43  *
44  * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
45  *         to use String.localeCampare method or not. Set to false.
46  *
47  * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
48  *         tablesorter should cancel selection of the table headers text.
49  *         Default value: true
50  *
51  * @option Array sortList ( optional ) An array containing objects specifying sorting.
52  *         By passing more than one object, multi-sorting will be applied. Object structure:
53  *         { <Integer column index>: <String 'asc' or 'desc'> }
54  *         Default value: []
55  *
56  * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
57  *         should display debuging information usefull for development.
58  *
59  * @event sortEnd.tablesorter: Triggered as soon as any sorting has been applied.
60  *
61  * @type jQuery
62  *
63  * @name tablesorter
64  *
65  * @cat Plugins/Tablesorter
66  *
67  * @author Christian Bach/christian.bach@polyester.se
68  */
70 ( function ( $, mw ) {
71         /* Local scope */
73         var ts,
74                 parsers = [];
76         /* Parser utility functions */
78         function getParserById( name ) {
79                 var i,
80                         len = parsers.length;
81                 for ( 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 sortType, cells, len, i, parser,
164                         rows = table.tBodies[0].rows,
165                         parsers = [];
167                 if ( rows[0] ) {
169                         cells = rows[0].cells;
170                         len = cells.length;
172                         for ( i = 0; i < len; i++ ) {
173                                 parser = false;
174                                 sortType = $headers.eq( i ).data( 'sortType' );
175                                 if ( sortType !== undefined ) {
176                                         parser = getParserById( sortType );
177                                 }
179                                 if ( parser === false ) {
180                                         parser = detectParserForColumn( table, rows, i );
181                                 }
183                                 parsers.push( parser );
184                         }
185                 }
186                 return parsers;
187         }
189         /* Other utility functions */
191         function buildCache( table ) {
192                 var i, j, $row, cols,
193                         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 ( i = 0; i < totalRows; ++i ) {
203                         // Add the table data to main data array
204                         $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 ( 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 i, pos, l, j,
231                         row = cache.row,
232                         normalized = cache.normalized,
233                         totalRows = normalized.length,
234                         checkCell = ( normalized[0].length - 1 ),
235                         fragment = document.createDocumentFragment();
237                 for ( i = 0; i < totalRows; i++ ) {
238                         pos = normalized[i][checkCell];
240                         l = row[pos].length;
242                         for ( j = 0; j < l; j++ ) {
243                                 fragment.appendChild( row[pos][j] );
244                         }
246                 }
247                 table.tBodies[0].appendChild( fragment );
249                 $( table ).trigger( 'sortEnd.tablesorter' );
250         }
252         /**
253          * Find all header rows in a thead-less table and put them in a <thead> tag.
254          * This only treats a row as a header row if it contains only <th>s (no <td>s)
255          * and if it is preceded entirely by header rows. The algorithm stops when
256          * it encounters the first non-header row.
257          *
258          * After this, it will look at all rows at the bottom for footer rows
259          * And place these in a tfoot using similar rules.
260          * @param $table jQuery object for a <table>
261          */
262         function emulateTHeadAndFoot( $table ) {
263                 var $thead, $tfoot, i, len,
264                         $rows = $table.find( '> tbody > tr' );
265                 if ( !$table.get( 0 ).tHead ) {
266                         $thead = $( '<thead>' );
267                         $rows.each( function () {
268                                 if ( $( this ).children( 'td' ).length ) {
269                                         // This row contains a <td>, so it's not a header row
270                                         // Stop here
271                                         return false;
272                                 }
273                                 $thead.append( this );
274                         } );
275                         $table.find( ' > tbody:first' ).before( $thead );
276                 }
277                 if ( !$table.get( 0 ).tFoot ) {
278                         $tfoot = $( '<tfoot>' );
279                         len = $rows.length;
280                         for ( i = len - 1; i >= 0; i-- ) {
281                                 if ( $( $rows[i] ).children( 'td' ).length ) {
282                                         break;
283                                 }
284                                 $tfoot.prepend( $( $rows[i] ) );
285                         }
286                         $table.append( $tfoot );
287                 }
288         }
290         function buildHeaders( table, msg ) {
291                 var maxSeen = 0,
292                         colspanOffset = 0,
293                         columns,
294                         i,
295                         rowspan,
296                         colspan,
297                         headerCount,
298                         longestTR,
299                         matrixRowIndex,
300                         matrixColumnIndex,
301                         exploded,
302                         $tableHeaders = $( [] ),
303                         $tableRows = $( 'thead:eq(0) > tr', table );
304                 if ( $tableRows.length <= 1 ) {
305                         $tableHeaders = $tableRows.children( 'th' );
306                 } else {
307                         exploded = [];
309                         // Loop through all the dom cells of the thead
310                         $tableRows.each( function ( rowIndex, row ) {
311                                 $.each( row.cells, function ( columnIndex, cell ) {
312                                         rowspan = Number( cell.rowSpan );
313                                         colspan = Number( cell.colSpan );
315                                         // Skip the spots in the exploded matrix that are already filled
316                                         while ( exploded[rowIndex] && exploded[rowIndex][columnIndex] !== undefined ) {
317                                                 ++columnIndex;
318                                         }
320                                         // Find the actual dimensions of the thead, by placing each cell
321                                         // in the exploded matrix rowspan times colspan times, with the proper offsets
322                                         for ( matrixColumnIndex = columnIndex; matrixColumnIndex < columnIndex + colspan; ++matrixColumnIndex ) {
323                                                 for ( matrixRowIndex = rowIndex; matrixRowIndex < rowIndex + rowspan; ++matrixRowIndex ) {
324                                                         if ( !exploded[matrixRowIndex] ) {
325                                                                 exploded[matrixRowIndex] = [];
326                                                         }
327                                                         exploded[matrixRowIndex][matrixColumnIndex] = cell;
328                                                 }
329                                         }
330                                 } );
331                         } );
332                         // We want to find the row that has the most columns (ignoring colspan)
333                         $.each( exploded, function ( index, cellArray ) {
334                                 headerCount = $.unique( $( cellArray ) ).length;
335                                 if ( headerCount >= maxSeen ) {
336                                         maxSeen = headerCount;
337                                         longestTR = index;
338                                 }
339                         } );
340                         // We cannot use $.unique() here because it sorts into dom order, which is undesirable
341                         $tableHeaders = $( uniqueElements( exploded[longestTR] ) );
342                 }
344                 // as each header can span over multiple columns (using colspan=N),
345                 // we have to bidirectionally map headers to their columns and columns to their headers
346                 table.headerToColumns = [];
347                 table.columnToHeader = [];
349                 $tableHeaders.each( function ( headerIndex ) {
350                         columns = [];
351                         for ( i = 0; i < this.colSpan; i++ ) {
352                                 table.columnToHeader[ colspanOffset + i ] = headerIndex;
353                                 columns.push( colspanOffset + i );
354                         }
356                         table.headerToColumns[ headerIndex ] = columns;
357                         colspanOffset += this.colSpan;
359                         this.headerIndex = headerIndex;
360                         this.order = 0;
361                         this.count = 0;
363                         if ( $( this ).hasClass( table.config.unsortableClass ) ) {
364                                 this.sortDisabled = true;
365                         }
367                         if ( !this.sortDisabled ) {
368                                 $( this )
369                                         .addClass( table.config.cssHeader )
370                                         .prop( 'tabIndex', 0 )
371                                         .attr( {
372                                                 role: 'columnheader button',
373                                                 title: msg[1]
374                                         } );
375                         }
377                         // add cell to headerList
378                         table.config.headerList[headerIndex] = this;
379                 } );
381                 return $tableHeaders;
383         }
385         /**
386          * Sets the sort count of the columns that are not affected by the sorting to have them sorted
387          * in default (ascending) order when their header cell is clicked the next time.
388          *
389          * @param {jQuery} $headers
390          * @param {Number[][]} sortList
391          * @param {Number[][]} headerToColumns
392          */
393         function setHeadersOrder( $headers, sortList, headerToColumns ) {
394                 // Loop through all headers to retrieve the indices of the columns the header spans across:
395                 $.each( headerToColumns, function ( headerIndex, columns ) {
397                         $.each( columns, function ( i, columnIndex ) {
398                                 var header = $headers[headerIndex];
400                                 if ( !isValueInArray( columnIndex, sortList ) ) {
401                                         // Column shall not be sorted: Reset header count and order.
402                                         header.order = 0;
403                                         header.count = 0;
404                                 } else {
405                                         // Column shall be sorted: Apply designated count and order.
406                                         $.each( sortList, function ( j, sortColumn ) {
407                                                 if ( sortColumn[0] === i ) {
408                                                         header.order = sortColumn[1];
409                                                         header.count = sortColumn[1] + 1;
410                                                         return false;
411                                                 }
412                                         } );
413                                 }
414                         } );
416                 } );
417         }
419         function isValueInArray( v, a ) {
420                 var i,
421                         len = a.length;
422                 for ( i = 0; i < len; i++ ) {
423                         if ( a[i][0] === v ) {
424                                 return true;
425                         }
426                 }
427                 return false;
428         }
430         function uniqueElements( array ) {
431                 var uniques = [];
432                 $.each( array, function ( index, elem ) {
433                         if ( elem !== undefined && $.inArray( elem, uniques ) === -1 ) {
434                                 uniques.push( elem );
435                         }
436                 } );
437                 return uniques;
438         }
440         function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
441                 // Remove all header information and reset titles to default message
442                 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
444                 for ( var i = 0; i < list.length; i++ ) {
445                         $headers.eq( columnToHeader[ list[i][0] ] )
446                                 .addClass( css[ list[i][1] ] )
447                                 .attr( 'title', msg[ list[i][1] ] );
448                 }
449         }
451         function sortText( a, b ) {
452                 return ( ( a < b ) ? -1 : ( ( a > b ) ? 1 : 0 ) );
453         }
455         function sortTextDesc( a, b ) {
456                 return ( ( b < a ) ? -1 : ( ( b > a ) ? 1 : 0 ) );
457         }
459         function multisort( table, sortList, cache ) {
460                 var i,
461                         sortFn = [],
462                         len = sortList.length;
463                 for ( i = 0; i < len; i++ ) {
464                         sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
465                 }
466                 cache.normalized.sort( function ( array1, array2 ) {
467                         var i, col, ret;
468                         for ( i = 0; i < len; i++ ) {
469                                 col = sortList[i][0];
470                                 ret = sortFn[i].call( this, array1[col], array2[col] );
471                                 if ( ret !== 0 ) {
472                                         return ret;
473                                 }
474                         }
475                         // Fall back to index number column to ensure stable sort
476                         return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
477                 } );
478                 return cache;
479         }
481         function buildTransformTable() {
482                 var ascii, localised, i, digitClass,
483                         digits = '0123456789,.'.split( '' ),
484                         separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' ),
485                         digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
487                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
488                         ts.transformTable = false;
489                 } else {
490                         ts.transformTable = {};
492                         // Unpack the transform table
493                         ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
494                         localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
496                         // Construct regex for number identification
497                         for ( i = 0; i < ascii.length; i++ ) {
498                                 ts.transformTable[localised[i]] = ascii[i];
499                                 digits.push( $.escapeRE( localised[i] ) );
500                         }
501                 }
502                 digitClass = '[' + digits.join( '', digits ) + ']';
504                 // We allow a trailing percent sign, which we just strip. This works fine
505                 // if percents and regular numbers aren't being mixed.
506                 ts.numberRegex = new RegExp( '^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
507                 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
508                 ')$', 'i' );
509         }
511         function buildDateTable() {
512                 var i, name,
513                         regex = [];
515                 ts.monthNames = {};
517                 for ( i = 0; i < 12; i++ ) {
518                         name = mw.language.months.names[i].toLowerCase();
519                         ts.monthNames[name] = i + 1;
520                         regex.push( $.escapeRE( name ) );
521                         name = mw.language.months.genitive[i].toLowerCase();
522                         ts.monthNames[name] = i + 1;
523                         regex.push( $.escapeRE( name ) );
524                         name = mw.language.months.abbrev[i].toLowerCase().replace( '.', '' );
525                         ts.monthNames[name] = i + 1;
526                         regex.push( $.escapeRE( name ) );
527                 }
529                 // Build piped string
530                 regex = regex.join( '|' );
532                 // Build RegEx
533                 // Any date formated with . , ' - or /
534                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i );
536                 // Written Month name, dmy
537                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
539                 // Written Month name, mdy
540                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
542         }
544         /**
545          * Replace all rowspanned cells in the body with clones in each row, so sorting
546          * need not worry about them.
547          *
548          * @param $table jQuery object for a <table>
549          */
550         function explodeRowspans( $table ) {
551                 var spanningRealCellIndex, rowSpan, colSpan,
552                         cell, i, $tds, $clone, $nextRows,
553                         rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
555                 // Short circuit
556                 if ( !rowspanCells.length ) {
557                         return;
558                 }
560                 // First, we need to make a property like cellIndex but taking into
561                 // account colspans. We also cache the rowIndex to avoid having to take
562                 // cell.parentNode.rowIndex in the sorting function below.
563                 $table.find( '> tbody > tr' ).each( function () {
564                         var i,
565                                 col = 0,
566                                 l = this.cells.length;
567                         for ( i = 0; i < l; i++ ) {
568                                 this.cells[i].realCellIndex = col;
569                                 this.cells[i].realRowIndex = this.rowIndex;
570                                 col += this.cells[i].colSpan;
571                         }
572                 } );
574                 // Split multi row cells into multiple cells with the same content.
575                 // Sort by column then row index to avoid problems with odd table structures.
576                 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
577                 // might change the sort order.
578                 function resortCells() {
579                         rowspanCells = rowspanCells.sort( function ( a, b ) {
580                                 var ret = a.realCellIndex - b.realCellIndex;
581                                 if ( !ret ) {
582                                         ret = a.realRowIndex - b.realRowIndex;
583                                 }
584                                 return ret;
585                         } );
586                         $.each( rowspanCells, function () {
587                                 this.needResort = false;
588                         } );
589                 }
590                 resortCells();
592                 function filterfunc() {
593                         return this.realCellIndex >= spanningRealCellIndex;
594                 }
596                 function fixTdCellIndex() {
597                         this.realCellIndex += colSpan;
598                         if ( this.rowSpan > 1 ) {
599                                 this.needResort = true;
600                         }
601                 }
603                 while ( rowspanCells.length ) {
604                         if ( rowspanCells[0].needResort ) {
605                                 resortCells();
606                         }
608                         cell = rowspanCells.shift();
609                         rowSpan = cell.rowSpan;
610                         colSpan = cell.colSpan;
611                         spanningRealCellIndex = cell.realCellIndex;
612                         cell.rowSpan = 1;
613                         $nextRows = $( cell ).parent().nextAll();
614                         for ( i = 0; i < rowSpan - 1; i++ ) {
615                                 $tds = $( $nextRows[i].cells ).filter( filterfunc );
616                                 $clone = $( cell ).clone();
617                                 $clone[0].realCellIndex = spanningRealCellIndex;
618                                 if ( $tds.length ) {
619                                         $tds.each( fixTdCellIndex );
620                                         $tds.first().before( $clone );
621                                 } else {
622                                         $nextRows.eq( i ).append( $clone );
623                                 }
624                         }
625                 }
626         }
628         function buildCollationTable() {
629                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
630                 ts.collationRegex = null;
631                 if ( ts.collationTable ) {
632                         var key,
633                                 keys = [];
635                         // Build array of key names
636                         for ( key in ts.collationTable ) {
637                                 // Check hasOwn to be safe
638                                 if ( ts.collationTable.hasOwnProperty( key ) ) {
639                                         keys.push( key );
640                                 }
641                         }
642                         if ( keys.length ) {
643                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
644                         }
645                 }
646         }
648         function cacheRegexs() {
649                 if ( ts.rgx ) {
650                         return;
651                 }
652                 ts.rgx = {
653                         IPAddress: [
654                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/ )
655                         ],
656                         currency: [
657                                 new RegExp( /(^[£$€¥]|[£$€¥]$)/ ),
658                                 new RegExp( /[£$€¥]/g )
659                         ],
660                         url: [
661                                 new RegExp( /^(https?|ftp|file):\/\/$/ ),
662                                 new RegExp( /(https?|ftp|file):\/\// )
663                         ],
664                         isoDate: [
665                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/ )
666                         ],
667                         usLongDate: [
668                                 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)))$/ )
669                         ],
670                         time: [
671                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/ )
672                         ]
673                 };
674         }
676         /**
677          * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
678          * structure [ [ Integer , Integer ], ... ]
679          *
680          * @param sortObjects {Array} List of sort objects.
681          * @return {Array} List of internal sort definitions.
682          */
684         function convertSortList( sortObjects ) {
685                 var sortList = [];
686                 $.each( sortObjects, function ( i, sortObject ) {
687                         $.each( sortObject, function ( columnIndex, order ) {
688                                 var orderIndex = ( order === 'desc' ) ? 1 : 0;
689                                 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
690                         } );
691                 } );
692                 return sortList;
693         }
695         /* Public scope */
697         $.tablesorter = {
699                         defaultOptions: {
700                                 cssHeader: 'headerSort',
701                                 cssAsc: 'headerSortUp',
702                                 cssDesc: 'headerSortDown',
703                                 cssChildRow: 'expand-child',
704                                 sortInitialOrder: 'asc',
705                                 sortMultiSortKey: 'shiftKey',
706                                 sortLocaleCompare: false,
707                                 unsortableClass: 'unsortable',
708                                 parsers: {},
709                                 widgets: [],
710                                 headers: {},
711                                 cancelSelection: true,
712                                 sortList: [],
713                                 headerList: [],
714                                 selectorHeaders: 'thead tr:eq(0) th',
715                                 debug: false
716                         },
718                         dateRegex: [],
719                         monthNames: {},
721                         /**
722                          * @param $tables {jQuery}
723                          * @param settings {Object} (optional)
724                          */
725                         construct: function ( $tables, settings ) {
726                                 return $tables.each( function ( i, table ) {
727                                         // Declare and cache.
728                                         var $headers, cache, config, sortCSS, sortMsg,
729                                                 $table = $( table ),
730                                                 firstTime = true;
732                                         // Quit if no tbody
733                                         if ( !table.tBodies ) {
734                                                 return;
735                                         }
736                                         if ( !table.tHead ) {
737                                                 // No thead found. Look for rows with <th>s and
738                                                 // move them into a <thead> tag or a <tfoot> tag
739                                                 emulateTHeadAndFoot( $table );
741                                                 // Still no thead? Then quit
742                                                 if ( !table.tHead ) {
743                                                         return;
744                                                 }
745                                         }
746                                         $table.addClass( 'jquery-tablesorter' );
748                                         // FIXME config should probably not be stored in the plain table node
749                                         // New config object.
750                                         table.config = {};
752                                         // Merge and extend.
753                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
755                                         // Save the settings where they read
756                                         $.data( table, 'tablesorter', { config: config } );
758                                         // Get the CSS class names, could be done else where.
759                                         sortCSS = [ config.cssDesc, config.cssAsc ];
760                                         sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
762                                         // Build headers
763                                         $headers = buildHeaders( table, sortMsg );
765                                         // Grab and process locale settings.
766                                         buildTransformTable();
767                                         buildDateTable();
769                                         // Precaching regexps can bring 10 fold
770                                         // performance improvements in some browsers.
771                                         cacheRegexs();
773                                         function setupForFirstSort() {
774                                                 firstTime = false;
776                                                 // Defer buildCollationTable to first sort. As user and site scripts
777                                                 // may customize tableSorterCollation but load after $.ready(), other
778                                                 // scripts may call .tablesorter() before they have done the
779                                                 // tableSorterCollation customizations.
780                                                 buildCollationTable();
782                                                 // Legacy fix of .sortbottoms
783                                                 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
784                                                 // and put the <tfoot> at the end of the <table>
785                                                 var $tfoot,
786                                                         $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
787                                                 if ( $sortbottoms.length ) {
788                                                         $tfoot = $table.children( 'tfoot' );
789                                                         if ( $tfoot.length ) {
790                                                                 $tfoot.eq( 0 ).prepend( $sortbottoms );
791                                                         } else {
792                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
793                                                         }
794                                                 }
796                                                 explodeRowspans( $table );
798                                                 // try to auto detect column type, and store in tables config
799                                                 table.config.parsers = buildParserCache( table, $headers );
800                                         }
802                                         // Apply event handling to headers
803                                         // this is too big, perhaps break it out?
804                                         $headers.not( '.' + table.config.unsortableClass ).on( 'keypress click', function ( e ) {
805                                                 var cell, columns, newSortList, i,
806                                                         totalRows,
807                                                         j, s, o;
809                                                 if ( e.type === 'click' && e.target.nodeName.toLowerCase() === 'a' ) {
810                                                         // The user clicked on a link inside a table header.
811                                                         // Do nothing and let the default link click action continue.
812                                                         return true;
813                                                 }
815                                                 if ( e.type === 'keypress' && e.which !== 13 ) {
816                                                         // Only handle keypresses on the "Enter" key.
817                                                         return true;
818                                                 }
820                                                 if ( firstTime ) {
821                                                         setupForFirstSort();
822                                                 }
824                                                 // Build the cache for the tbody cells
825                                                 // to share between calculations for this sort action.
826                                                 // Re-calculated each time a sort action is performed due to possiblity
827                                                 // that sort values change. Shouldn't be too expensive, but if it becomes
828                                                 // too slow an event based system should be implemented somehow where
829                                                 // cells get event .change() and bubbles up to the <table> here
830                                                 cache = buildCache( table );
832                                                 totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
833                                                 if ( !table.sortDisabled && totalRows > 0 ) {
834                                                         // Get current column sort order
835                                                         this.order = this.count % 2;
836                                                         this.count++;
838                                                         cell = this;
839                                                         // Get current column index
840                                                         columns = table.headerToColumns[ this.headerIndex ];
841                                                         newSortList = $.map( columns, function ( c ) {
842                                                                 // jQuery "helpfully" flattens the arrays...
843                                                                 return [[c, cell.order]];
844                                                         } );
845                                                         // Index of first column belonging to this header
846                                                         i = columns[0];
848                                                         if ( !e[config.sortMultiSortKey] ) {
849                                                                 // User only wants to sort on one column set
850                                                                 // Flush the sort list and add new columns
851                                                                 config.sortList = newSortList;
852                                                         } else {
853                                                                 // Multi column sorting
854                                                                 // It is not possible for one column to belong to multiple headers,
855                                                                 // so this is okay - we don't need to check for every value in the columns array
856                                                                 if ( isValueInArray( i, config.sortList ) ) {
857                                                                         // The user has clicked on an already sorted column.
858                                                                         // Reverse the sorting direction for all tables.
859                                                                         for ( j = 0; j < config.sortList.length; j++ ) {
860                                                                                 s = config.sortList[j];
861                                                                                 o = config.headerList[s[0]];
862                                                                                 if ( isValueInArray( s[0], newSortList ) ) {
863                                                                                         o.count = s[1];
864                                                                                         o.count++;
865                                                                                         s[1] = o.count % 2;
866                                                                                 }
867                                                                         }
868                                                                 } else {
869                                                                         // Add columns to sort list array
870                                                                         config.sortList = config.sortList.concat( newSortList );
871                                                                 }
872                                                         }
874                                                         // Reset order/counts of cells not affected by sorting
875                                                         setHeadersOrder( $headers, config.sortList, table.headerToColumns );
877                                                         // Set CSS for headers
878                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, table.columnToHeader );
879                                                         appendToTable(
880                                                                 $table[0], multisort( $table[0], config.sortList, cache )
881                                                         );
883                                                         // Stop normal event by returning false
884                                                         return false;
885                                                 }
887                                         // Cancel selection
888                                         } ).mousedown( function () {
889                                                 if ( config.cancelSelection ) {
890                                                         this.onselectstart = function () {
891                                                                 return false;
892                                                         };
893                                                         return false;
894                                                 }
895                                         } );
897                                         /**
898                                          * Sorts the table. If no sorting is specified by passing a list of sort
899                                          * objects, the table is sorted according to the initial sorting order.
900                                          * Passing an empty array will reset sorting (basically just reset the headers
901                                          * making the table appear unsorted).
902                                          *
903                                          * @param sortList {Array} (optional) List of sort objects.
904                                          */
905                                         $table.data( 'tablesorter' ).sort = function ( sortList ) {
907                                                 if ( firstTime ) {
908                                                         setupForFirstSort();
909                                                 }
911                                                 if ( sortList === undefined ) {
912                                                         sortList = config.sortList;
913                                                 } else if ( sortList.length > 0 ) {
914                                                         sortList = convertSortList( sortList );
915                                                 }
917                                                 // Set each column's sort count to be able to determine the correct sort
918                                                 // order when clicking on a header cell the next time
919                                                 setHeadersOrder( $headers, sortList, table.headerToColumns );
921                                                 // re-build the cache for the tbody cells
922                                                 cache = buildCache( table );
924                                                 // set css for headers
925                                                 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, table.columnToHeader );
927                                                 // sort the table and append it to the dom
928                                                 appendToTable( table, multisort( table, sortList, cache ) );
929                                         };
931                                         // sort initially
932                                         if ( config.sortList.length > 0 ) {
933                                                 setupForFirstSort();
934                                                 config.sortList = convertSortList( config.sortList );
935                                                 $table.data( 'tablesorter' ).sort();
936                                         }
938                                 } );
939                         },
941                         addParser: function ( parser ) {
942                                 var i,
943                                         len = parsers.length,
944                                         a = true;
945                                 for ( i = 0; i < len; i++ ) {
946                                         if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
947                                                 a = false;
948                                         }
949                                 }
950                                 if ( a ) {
951                                         parsers.push( parser );
952                                 }
953                         },
955                         formatDigit: function ( s ) {
956                                 var out, c, p, i;
957                                 if ( ts.transformTable !== false ) {
958                                         out = '';
959                                         for ( p = 0; p < s.length; p++ ) {
960                                                 c = s.charAt( p );
961                                                 if ( c in ts.transformTable ) {
962                                                         out += ts.transformTable[c];
963                                                 } else {
964                                                         out += c;
965                                                 }
966                                         }
967                                         s = out;
968                                 }
969                                 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
970                                 return isNaN( i ) ? 0 : i;
971                         },
973                         formatFloat: function ( s ) {
974                                 var i = parseFloat( s );
975                                 return isNaN( i ) ? 0 : i;
976                         },
978                         formatInt: function ( s ) {
979                                 var i = parseInt( s, 10 );
980                                 return isNaN( i ) ? 0 : i;
981                         },
983                         clearTableBody: function ( table ) {
984                                 $( table.tBodies[0] ).empty();
985                         }
986                 };
988         // Shortcut
989         ts = $.tablesorter;
991         // Register as jQuery prototype method
992         $.fn.tablesorter = function ( settings ) {
993                 return ts.construct( this, settings );
994         };
996         // Add default parsers
997         ts.addParser( {
998                 id: 'text',
999                 is: function () {
1000                         return true;
1001                 },
1002                 format: function ( s ) {
1003                         s = $.trim( s.toLowerCase() );
1004                         if ( ts.collationRegex ) {
1005                                 var tsc = ts.collationTable;
1006                                 s = s.replace( ts.collationRegex, function ( match ) {
1007                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
1008                                         return r.toLowerCase();
1009                                 } );
1010                         }
1011                         return s;
1012                 },
1013                 type: 'text'
1014         } );
1016         ts.addParser( {
1017                 id: 'IPAddress',
1018                 is: function ( s ) {
1019                         return ts.rgx.IPAddress[0].test( s );
1020                 },
1021                 format: function ( s ) {
1022                         var i, item,
1023                                 a = s.split( '.' ),
1024                                 r = '',
1025                                 len = a.length;
1026                         for ( i = 0; i < len; i++ ) {
1027                                 item = a[i];
1028                                 if ( item.length === 1 ) {
1029                                         r += '00' + item;
1030                                 } else if ( item.length === 2 ) {
1031                                         r += '0' + item;
1032                                 } else {
1033                                         r += item;
1034                                 }
1035                         }
1036                         return $.tablesorter.formatFloat( r );
1037                 },
1038                 type: 'numeric'
1039         } );
1041         ts.addParser( {
1042                 id: 'currency',
1043                 is: function ( s ) {
1044                         return ts.rgx.currency[0].test( s );
1045                 },
1046                 format: function ( s ) {
1047                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
1048                 },
1049                 type: 'numeric'
1050         } );
1052         ts.addParser( {
1053                 id: 'url',
1054                 is: function ( s ) {
1055                         return ts.rgx.url[0].test( s );
1056                 },
1057                 format: function ( s ) {
1058                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
1059                 },
1060                 type: 'text'
1061         } );
1063         ts.addParser( {
1064                 id: 'isoDate',
1065                 is: function ( s ) {
1066                         return ts.rgx.isoDate[0].test( s );
1067                 },
1068                 format: function ( s ) {
1069                         return $.tablesorter.formatFloat( ( s !== '' ) ? new Date( s.replace(
1070                         new RegExp( /-/g ), '/' ) ).getTime() : '0' );
1071                 },
1072                 type: 'numeric'
1073         } );
1075         ts.addParser( {
1076                 id: 'usLongDate',
1077                 is: function ( s ) {
1078                         return ts.rgx.usLongDate[0].test( s );
1079                 },
1080                 format: function ( s ) {
1081                         return $.tablesorter.formatFloat( new Date( s ).getTime() );
1082                 },
1083                 type: 'numeric'
1084         } );
1086         ts.addParser( {
1087                 id: 'date',
1088                 is: function ( s ) {
1089                         return ( ts.dateRegex[0].test( s ) || ts.dateRegex[1].test( s ) || ts.dateRegex[2].test( s ) );
1090                 },
1091                 format: function ( s ) {
1092                         var match, y;
1093                         s = $.trim( s.toLowerCase() );
1095                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1096                                 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1097                                         s = [ match[3], match[1], match[2] ];
1098                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1099                                         s = [ match[3], match[2], match[1] ];
1100                                 } else {
1101                                         // If we get here, we don't know which order the dd-dd-dddd
1102                                         // date is in. So return something not entirely invalid.
1103                                         return '99999999';
1104                                 }
1105                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1106                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1107                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1108                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1109                         } else {
1110                                 // Should never get here
1111                                 return '99999999';
1112                         }
1114                         // Pad Month and Day
1115                         if ( s[1].length === 1 ) {
1116                                 s[1] = '0' + s[1];
1117                         }
1118                         if ( s[2].length === 1 ) {
1119                                 s[2] = '0' + s[2];
1120                         }
1122                         if ( ( y = parseInt( s[0], 10 ) ) < 100 ) {
1123                                 // Guestimate years without centuries
1124                                 if ( y < 30 ) {
1125                                         s[0] = 2000 + y;
1126                                 } else {
1127                                         s[0] = 1900 + y;
1128                                 }
1129                         }
1130                         while ( s[0].length < 4 ) {
1131                                 s[0] = '0' + s[0];
1132                         }
1133                         return parseInt( s.join( '' ), 10 );
1134                 },
1135                 type: 'numeric'
1136         } );
1138         ts.addParser( {
1139                 id: 'time',
1140                 is: function ( s ) {
1141                         return ts.rgx.time[0].test( s );
1142                 },
1143                 format: function ( s ) {
1144                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1145                 },
1146                 type: 'numeric'
1147         } );
1149         ts.addParser( {
1150                 id: 'number',
1151                 is: function ( s ) {
1152                         return $.tablesorter.numberRegex.test( $.trim( s ) );
1153                 },
1154                 format: function ( s ) {
1155                         return $.tablesorter.formatDigit( s );
1156                 },
1157                 type: 'numeric'
1158         } );
1160 }( jQuery, mediaWiki ) );