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