Localisation updates from http://translatewiki.net.
[mediawiki.git] / resources / jquery / jquery.tablesorter.js
blob405c600b767ab7944a1810ad5cadba03e70b5826
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 = $( 'thead:eq(0) > tr', table );
293                 if ( $tableHeaders.length > 1 ) {
294                         $tableHeaders.each( function () {
295                                 if ( this.cells.length > maxSeen ) {
296                                         maxSeen = this.cells.length;
297                                         longest = this;
298                                 }
299                         });
300                         $tableHeaders = $( longest );
301                 }
302                 $tableHeaders = $tableHeaders.children( 'th' ).each( function ( index ) {
303                         this.column = realCellIndex;
305                         var colspan = this.colspan;
306                         colspan = colspan ? parseInt( colspan, 10 ) : 1;
307                         realCellIndex += colspan;
309                         this.order = 0;
310                         this.count = 0;
312                         if ( $( this ).is( '.unsortable' ) ) {
313                                 this.sortDisabled = true;
314                         }
316                         if ( !this.sortDisabled ) {
317                                 $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
318                         }
320                         // add cell to headerList
321                         table.config.headerList[index] = this;
322                 } );
324                 return $tableHeaders;
326         }
328         /**
329          * Sets the sort count of the columns that are not affected by the sorting to have them sorted
330          * in default (ascending) order when their header cell is clicked the next time.
331          *
332          * @param {jQuery} $headers
333          * @param {Number[][]} sortList
334          * @param {Number[][]} headerToColumns
335          */
336         function setHeadersOrder( $headers, sortList, headerToColumns ) {
337                 // Loop through all headers to retrieve the indices of the columns the header spans across:
338                 $.each( headerToColumns, function( headerIndex, columns ) {
340                         $.each( columns, function( i, columnIndex ) {
341                                 var header = $headers[headerIndex];
343                                 if ( !isValueInArray( columnIndex, sortList ) ) {
344                                         // Column shall not be sorted: Reset header count and order.
345                                         header.order = 0;
346                                         header.count = 0;
347                                 } else {
348                                         // Column shall be sorted: Apply designated count and order.
349                                         $.each( sortList, function( j, sortColumn ) {
350                                                 if ( sortColumn[0] === i ) {
351                                                         header.order = sortColumn[1];
352                                                         header.count = sortColumn[1] + 1;
353                                                         return false;
354                                                 }
355                                         } );
356                                 }
357                         } );
359                 } );
360         }
362         function isValueInArray( v, a ) {
363                 var l = a.length;
364                 for ( var i = 0; i < l; i++ ) {
365                         if ( a[i][0] === v ) {
366                                 return true;
367                         }
368                 }
369                 return false;
370         }
372         function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
373                 // Remove all header information and reset titles to default message
374                 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
376                 for ( var i = 0; i < list.length; i++ ) {
377                         $headers.eq( columnToHeader[ list[i][0] ] )
378                                 .addClass( css[ list[i][1] ] )
379                                 .attr( 'title', msg[ list[i][1] ] );
380                 }
381         }
383         function sortText( a, b ) {
384                 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
385         }
387         function sortTextDesc( a, b ) {
388                 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
389         }
391         function multisort( table, sortList, cache ) {
392                 var sortFn = [];
393                 var len = sortList.length;
394                 for ( var i = 0; i < len; i++ ) {
395                         sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
396                 }
397                 cache.normalized.sort( function ( array1, array2 ) {
398                         var col, ret;
399                         for ( var i = 0; i < len; i++ ) {
400                                 col = sortList[i][0];
401                                 ret = sortFn[i].call( this, array1[col], array2[col] );
402                                 if ( ret !== 0 ) {
403                                         return ret;
404                                 }
405                         }
406                         // Fall back to index number column to ensure stable sort
407                         return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
408                 } );
409                 return cache;
410         }
412         function buildTransformTable() {
413                 var digits = '0123456789,.'.split( '' );
414                 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
415                 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
416                 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
417                         ts.transformTable = false;
418                 } else {
419                         ts.transformTable = {};
421                         // Unpack the transform table
422                         var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
423                         var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
425                         // Construct regex for number identification
426                         for ( var i = 0; i < ascii.length; i++ ) {
427                                 ts.transformTable[localised[i]] = ascii[i];
428                                 digits.push( $.escapeRE( localised[i] ) );
429                         }
430                 }
431                 var digitClass = '[' + digits.join( '', digits ) + ']';
433                 // We allow a trailing percent sign, which we just strip. This works fine
434                 // if percents and regular numbers aren't being mixed.
435                 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
436                 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
437                 ')$', 'i');
438         }
440         function buildDateTable() {
441                 var regex = [];
442                 ts.monthNames = {};
444                 for ( var i = 1; i < 13; i++ ) {
445                         var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
446                         ts.monthNames[name] = i;
447                         regex.push( $.escapeRE( name ) );
448                         name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
449                         ts.monthNames[name] = i;
450                         regex.push( $.escapeRE( name ) );
451                 }
453                 // Build piped string
454                 regex = regex.join( '|' );
456                 // Build RegEx
457                 // Any date formated with . , ' - or /
458                 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
460                 // Written Month name, dmy
461                 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
463                 // Written Month name, mdy
464                 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]+(\\d{1,2})[\\,\\.\\-\\/\'\\s]+(\\d{2,4})\\s*$', 'i' );
466         }
468         /**
469          * Replace all rowspanned cells in the body with clones in each row, so sorting
470          * need not worry about them.
471          *
472          * @param $table jQuery object for a <table>
473          */
474         function explodeRowspans( $table ) {
475                 var rowspanCells = $table.find( '> tbody > tr > [rowspan]' ).get();
477                 // Short circuit
478                 if ( !rowspanCells.length ) {
479                         return;
480                 }
482                 // First, we need to make a property like cellIndex but taking into
483                 // account colspans. We also cache the rowIndex to avoid having to take
484                 // cell.parentNode.rowIndex in the sorting function below.
485                 $table.find( '> tbody > tr' ).each( function () {
486                         var col = 0;
487                         var l = this.cells.length;
488                         for ( var i = 0; i < l; i++ ) {
489                                 this.cells[i].realCellIndex = col;
490                                 this.cells[i].realRowIndex = this.rowIndex;
491                                 col += this.cells[i].colSpan;
492                         }
493                 } );
495                 // Split multi row cells into multiple cells with the same content.
496                 // Sort by column then row index to avoid problems with odd table structures.
497                 // Re-sort whenever a rowspanned cell's realCellIndex is changed, because it
498                 // might change the sort order.
499                 function resortCells() {
500                         rowspanCells = rowspanCells.sort( function ( a, b ) {
501                                 var ret = a.realCellIndex - b.realCellIndex;
502                                 if ( !ret ) {
503                                         ret = a.realRowIndex - b.realRowIndex;
504                                 }
505                                 return ret;
506                         } );
507                         $.each( rowspanCells, function () {
508                                 this.needResort = false;
509                         } );
510                 }
511                 resortCells();
513                 var spanningRealCellIndex, rowSpan, colSpan;
514                 function filterfunc() {
515                         return this.realCellIndex >= spanningRealCellIndex;
516                 }
518                 function fixTdCellIndex() {
519                         this.realCellIndex += colSpan;
520                         if ( this.rowSpan > 1 ) {
521                                 this.needResort = true;
522                         }
523                 }
525                 while ( rowspanCells.length ) {
526                         if ( rowspanCells[0].needResort ) {
527                                 resortCells();
528                         }
530                         var cell = rowspanCells.shift();
531                         rowSpan = cell.rowSpan;
532                         colSpan = cell.colSpan;
533                         spanningRealCellIndex = cell.realCellIndex;
534                         cell.rowSpan = 1;
535                         var $nextRows = $( cell ).parent().nextAll();
536                         for ( var i = 0; i < rowSpan - 1; i++ ) {
537                                 var $tds = $( $nextRows[i].cells ).filter( filterfunc );
538                                 var $clone = $( cell ).clone();
539                                 $clone[0].realCellIndex = spanningRealCellIndex;
540                                 if ( $tds.length ) {
541                                         $tds.each( fixTdCellIndex );
542                                         $tds.first().before( $clone );
543                                 } else {
544                                         $nextRows.eq( i ).append( $clone );
545                                 }
546                         }
547                 }
548         }
550         function buildCollationTable() {
551                 ts.collationTable = mw.config.get( 'tableSorterCollation' );
552                 ts.collationRegex = null;
553                 if ( ts.collationTable ) {
554                         var keys = [];
556                         // Build array of key names
557                         for ( var key in ts.collationTable ) {
558                                 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
559                                         keys.push(key);
560                                 }
561                         }
562                         if (keys.length) {
563                                 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
564                         }
565                 }
566         }
568         function cacheRegexs() {
569                 if ( ts.rgx ) {
570                         return;
571                 }
572                 ts.rgx = {
573                         IPAddress: [
574                                 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
575                         ],
576                         currency: [
577                                 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
578                                 new RegExp( /[£$€¥]/g)
579                         ],
580                         url: [
581                                 new RegExp( /^(https?|ftp|file):\/\/$/),
582                                 new RegExp( /(https?|ftp|file):\/\//)
583                         ],
584                         isoDate: [
585                                 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
586                         ],
587                         usLongDate: [
588                                 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)))$/)
589                         ],
590                         time: [
591                                 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
592                         ]
593                 };
594         }
596         /**
597          * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
598          * structure [ [ Integer , Integer ], ... ]
599          *
600          * @param sortObjects {Array} List of sort objects.
601          * @return {Array} List of internal sort definitions.
602          */
604         function convertSortList( sortObjects ) {
605                 var sortList = [];
606                 $.each( sortObjects, function( i, sortObject ) {
607                         $.each ( sortObject, function( columnIndex, order ) {
608                                 var orderIndex = ( order === 'desc' ) ? 1 : 0;
609                                 sortList.push( [parseInt( columnIndex, 10 ), orderIndex] );
610                         } );
611                 } );
612                 return sortList;
613         }
615         /* Public scope */
617         $.tablesorter = {
619                         defaultOptions: {
620                                 cssHeader: 'headerSort',
621                                 cssAsc: 'headerSortUp',
622                                 cssDesc: 'headerSortDown',
623                                 cssChildRow: 'expand-child',
624                                 sortInitialOrder: 'asc',
625                                 sortMultiSortKey: 'shiftKey',
626                                 sortLocaleCompare: false,
627                                 parsers: {},
628                                 widgets: [],
629                                 headers: {},
630                                 cancelSelection: true,
631                                 sortList: [],
632                                 headerList: [],
633                                 selectorHeaders: 'thead tr:eq(0) th',
634                                 debug: false
635                         },
637                         dateRegex: [],
638                         monthNames: {},
640                         /**
641                          * @param $tables {jQuery}
642                          * @param settings {Object} (optional)
643                          */
644                         construct: function ( $tables, settings ) {
645                                 return $tables.each( function ( i, table ) {
646                                         // Declare and cache.
647                                         var $headers, cache, config,
648                                                 headerToColumns, columnToHeader, colspanOffset,
649                                                 $table = $( table ),
650                                                 firstTime = true;
652                                         // Quit if no tbody
653                                         if ( !table.tBodies ) {
654                                                 return;
655                                         }
656                                         if ( !table.tHead ) {
657                                                 // No thead found. Look for rows with <th>s and
658                                                 // move them into a <thead> tag or a <tfoot> tag
659                                                 emulateTHeadAndFoot( $table );
661                                                 // Still no thead? Then quit
662                                                 if ( !table.tHead ) {
663                                                         return;
664                                                 }
665                                         }
666                                         $table.addClass( 'jquery-tablesorter' );
668                                         // FIXME config should probably not be stored in the plain table node
669                                         // New config object.
670                                         table.config = {};
672                                         // Merge and extend.
673                                         config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
675                                         // Save the settings where they read
676                                         $.data( table, 'tablesorter', { config: config } );
678                                         // Get the CSS class names, could be done else where.
679                                         var sortCSS = [ config.cssDesc, config.cssAsc ];
680                                         var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
682                                         // Build headers
683                                         $headers = buildHeaders( table, sortMsg );
685                                         // Grab and process locale settings
686                                         buildTransformTable();
687                                         buildDateTable();
688                                         buildCollationTable();
690                                         // Precaching regexps can bring 10 fold
691                                         // performance improvements in some browsers.
692                                         cacheRegexs();
694                                         function setupForFirstSort() {
695                                                 firstTime = false;
697                                                 // Legacy fix of .sortbottoms
698                                                 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
699                                                 // and put the <tfoot> at the end of the <table>
700                                                 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
701                                                 if ( $sortbottoms.length ) {
702                                                         var $tfoot = $table.children( 'tfoot' );
703                                                         if ( $tfoot.length ) {
704                                                                 $tfoot.eq(0).prepend( $sortbottoms );
705                                                         } else {
706                                                                 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
707                                                         }
708                                                 }
710                                                 explodeRowspans( $table );
712                                                 // try to auto detect column type, and store in tables config
713                                                 table.config.parsers = buildParserCache( table, $headers );
714                                         }
716                                         // as each header can span over multiple columns (using colspan=N),
717                                         // we have to bidirectionally map headers to their columns and columns to their headers
718                                         headerToColumns = [];
719                                         columnToHeader = [];
720                                         colspanOffset = 0;
721                                         $headers.each( function ( headerIndex ) {
722                                                 var columns = [];
723                                                 for ( var i = 0; i < this.colSpan; i++ ) {
724                                                         columnToHeader[ colspanOffset + i ] = headerIndex;
725                                                         columns.push( colspanOffset + i );
726                                                 }
728                                                 headerToColumns[ headerIndex ] = columns;
729                                                 colspanOffset += this.colSpan;
730                                         } );
732                                         // Apply event handling to headers
733                                         // this is too big, perhaps break it out?
734                                         $headers.filter( ':not(.unsortable)' ).click( function ( e ) {
735                                                 if ( e.target.nodeName.toLowerCase() === 'a' ) {
736                                                         // The user clicked on a link inside a table header
737                                                         // Do nothing and let the default link click action continue
738                                                         return true;
739                                                 }
741                                                 if ( firstTime ) {
742                                                         setupForFirstSort();
743                                                 }
745                                                 // Build the cache for the tbody cells
746                                                 // to share between calculations for this sort action.
747                                                 // Re-calculated each time a sort action is performed due to possiblity
748                                                 // that sort values change. Shouldn't be too expensive, but if it becomes
749                                                 // too slow an event based system should be implemented somehow where
750                                                 // cells get event .change() and bubbles up to the <table> here
751                                                 cache = buildCache( table );
753                                                 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
754                                                 if ( !table.sortDisabled && totalRows > 0 ) {
755                                                         // Get current column sort order
756                                                         this.order = this.count % 2;
757                                                         this.count++;
759                                                         var cell = this;
760                                                         // Get current column index
761                                                         var columns = headerToColumns[this.column];
762                                                         var newSortList = $.map( columns, function (c) {
763                                                                 // jQuery "helpfully" flattens the arrays...
764                                                                 return [[c, cell.order]];
765                                                         });
766                                                         // Index of first column belonging to this header
767                                                         var i = columns[0];
769                                                         if ( !e[config.sortMultiSortKey] ) {
770                                                                 // User only wants to sort on one column set
771                                                                 // Flush the sort list and add new columns
772                                                                 config.sortList = newSortList;
773                                                         } else {
774                                                                 // Multi column sorting
775                                                                 // It is not possible for one column to belong to multiple headers,
776                                                                 // so this is okay - we don't need to check for every value in the columns array
777                                                                 if ( isValueInArray( i, config.sortList ) ) {
778                                                                         // The user has clicked on an already sorted column.
779                                                                         // Reverse the sorting direction for all tables.
780                                                                         for ( var j = 0; j < config.sortList.length; j++ ) {
781                                                                                 var s = config.sortList[j],
782                                                                                         o = config.headerList[s[0]];
783                                                                                 if ( isValueInArray( s[0], newSortList ) ) {
784                                                                                         o.count = s[1];
785                                                                                         o.count++;
786                                                                                         s[1] = o.count % 2;
787                                                                                 }
788                                                                         }
789                                                                 } else {
790                                                                         // Add columns to sort list array
791                                                                         config.sortList = config.sortList.concat( newSortList );
792                                                                 }
793                                                         }
795                                                         // Reset order/counts of cells not affected by sorting
796                                                         setHeadersOrder( $headers, config.sortList, headerToColumns );
798                                                         // Set CSS for headers
799                                                         setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, columnToHeader );
800                                                         appendToTable(
801                                                                 $table[0], multisort( $table[0], config.sortList, cache )
802                                                         );
804                                                         // Stop normal event by returning false
805                                                         return false;
806                                                 }
808                                         // Cancel selection
809                                         } ).mousedown( function () {
810                                                 if ( config.cancelSelection ) {
811                                                         this.onselectstart = function () {
812                                                                 return false;
813                                                         };
814                                                         return false;
815                                                 }
816                                         } );
818                                         /**
819                                          * Sorts the table. If no sorting is specified by passing a list of sort
820                                          * objects, the table is sorted according to the initial sorting order.
821                                          * Passing an empty array will reset sorting (basically just reset the headers
822                                          * making the table appear unsorted).
823                                          *
824                                          * @param sortList {Array} (optional) List of sort objects.
825                                          */
826                                         $table.data( 'tablesorter' ).sort = function( sortList ) {
828                                                 if ( firstTime ) {
829                                                         setupForFirstSort();
830                                                 }
832                                                 if ( sortList === undefined ) {
833                                                         sortList = config.sortList;
834                                                 } else if ( sortList.length > 0 ) {
835                                                         sortList = convertSortList( sortList );
836                                                 }
838                                                 // Set each column's sort count to be able to determine the correct sort
839                                                 // order when clicking on a header cell the next time
840                                                 setHeadersOrder( $headers, sortList, headerToColumns );
842                                                 // re-build the cache for the tbody cells
843                                                 cache = buildCache( table );
845                                                 // set css for headers
846                                                 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, columnToHeader );
848                                                 // sort the table and append it to the dom
849                                                 appendToTable( table, multisort( table, sortList, cache ) );
850                                         };
852                                         // sort initially
853                                         if ( config.sortList.length > 0 ) {
854                                                 setupForFirstSort();
855                                                 config.sortList = convertSortList( config.sortList );
856                                                 $table.data( 'tablesorter' ).sort();
857                                         }
859                                 } );
860                         },
862                         addParser: function ( parser ) {
863                                 var l = parsers.length,
864                                         a = true;
865                                 for ( var i = 0; i < l; i++ ) {
866                                         if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
867                                                 a = false;
868                                         }
869                                 }
870                                 if ( a ) {
871                                         parsers.push( parser );
872                                 }
873                         },
875                         formatDigit: function ( s ) {
876                                 var out, c, p, i;
877                                 if ( ts.transformTable !== false ) {
878                                         out = '';
879                                         for ( p = 0; p < s.length; p++ ) {
880                                                 c = s.charAt(p);
881                                                 if ( c in ts.transformTable ) {
882                                                         out += ts.transformTable[c];
883                                                 } else {
884                                                         out += c;
885                                                 }
886                                         }
887                                         s = out;
888                                 }
889                                 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
890                                 return isNaN( i ) ? 0 : i;
891                         },
893                         formatFloat: function ( s ) {
894                                 var i = parseFloat(s);
895                                 return isNaN( i ) ? 0 : i;
896                         },
898                         formatInt: function ( s ) {
899                                 var i = parseInt( s, 10 );
900                                 return isNaN( i ) ? 0 : i;
901                         },
903                         clearTableBody: function ( table ) {
904                                 $( table.tBodies[0] ).empty();
905                         }
906                 };
908         // Shortcut
909         ts = $.tablesorter;
911         // Register as jQuery prototype method
912         $.fn.tablesorter = function ( settings ) {
913                 return ts.construct( this, settings );
914         };
916         // Add default parsers
917         ts.addParser( {
918                 id: 'text',
919                 is: function () {
920                         return true;
921                 },
922                 format: function ( s ) {
923                         s = $.trim( s.toLowerCase() );
924                         if ( ts.collationRegex ) {
925                                 var tsc = ts.collationTable;
926                                 s = s.replace( ts.collationRegex, function ( match ) {
927                                         var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
928                                         return r.toLowerCase();
929                                 } );
930                         }
931                         return s;
932                 },
933                 type: 'text'
934         } );
936         ts.addParser( {
937                 id: 'IPAddress',
938                 is: function ( s ) {
939                         return ts.rgx.IPAddress[0].test(s);
940                 },
941                 format: function ( s ) {
942                         var a = s.split( '.' ),
943                                 r = '',
944                                 l = a.length;
945                         for ( var i = 0; i < l; i++ ) {
946                                 var item = a[i];
947                                 if ( item.length === 1 ) {
948                                         r += '00' + item;
949                                 } else if ( item.length === 2 ) {
950                                         r += '0' + item;
951                                 } else {
952                                         r += item;
953                                 }
954                         }
955                         return $.tablesorter.formatFloat(r);
956                 },
957                 type: 'numeric'
958         } );
960         ts.addParser( {
961                 id: 'currency',
962                 is: function ( s ) {
963                         return ts.rgx.currency[0].test(s);
964                 },
965                 format: function ( s ) {
966                         return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
967                 },
968                 type: 'numeric'
969         } );
971         ts.addParser( {
972                 id: 'url',
973                 is: function ( s ) {
974                         return ts.rgx.url[0].test(s);
975                 },
976                 format: function ( s ) {
977                         return $.trim( s.replace( ts.rgx.url[1], '' ) );
978                 },
979                 type: 'text'
980         } );
982         ts.addParser( {
983                 id: 'isoDate',
984                 is: function ( s ) {
985                         return ts.rgx.isoDate[0].test(s);
986                 },
987                 format: function ( s ) {
988                         return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
989                         new RegExp( /-/g), '/')).getTime() : '0' );
990                 },
991                 type: 'numeric'
992         } );
994         ts.addParser( {
995                 id: 'usLongDate',
996                 is: function ( s ) {
997                         return ts.rgx.usLongDate[0].test(s);
998                 },
999                 format: function ( s ) {
1000                         return $.tablesorter.formatFloat( new Date(s).getTime() );
1001                 },
1002                 type: 'numeric'
1003         } );
1005         ts.addParser( {
1006                 id: 'date',
1007                 is: function ( s ) {
1008                         return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
1009                 },
1010                 format: function ( s ) {
1011                         var match;
1012                         s = $.trim( s.toLowerCase() );
1014                         if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
1015                                 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
1016                                         s = [ match[3], match[1], match[2] ];
1017                                 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
1018                                         s = [ match[3], match[2], match[1] ];
1019                                 } else {
1020                                         // If we get here, we don't know which order the dd-dd-dddd
1021                                         // date is in. So return something not entirely invalid.
1022                                         return '99999999';
1023                                 }
1024                         } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
1025                                 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
1026                         } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
1027                                 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
1028                         } else {
1029                                 // Should never get here
1030                                 return '99999999';
1031                         }
1033                         // Pad Month and Day
1034                         if ( s[1].length === 1 ) {
1035                                 s[1] = '0' + s[1];
1036                         }
1037                         if ( s[2].length === 1 ) {
1038                                 s[2] = '0' + s[2];
1039                         }
1041                         var y;
1042                         if ( ( y = parseInt( s[0], 10) ) < 100 ) {
1043                                 // Guestimate years without centuries
1044                                 if ( y < 30 ) {
1045                                         s[0] = 2000 + y;
1046                                 } else {
1047                                         s[0] = 1900 + y;
1048                                 }
1049                         }
1050                         while ( s[0].length < 4 ) {
1051                                 s[0] = '0' + s[0];
1052                         }
1053                         return parseInt( s.join( '' ), 10 );
1054                 },
1055                 type: 'numeric'
1056         } );
1058         ts.addParser( {
1059                 id: 'time',
1060                 is: function ( s ) {
1061                         return ts.rgx.time[0].test(s);
1062                 },
1063                 format: function ( s ) {
1064                         return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
1065                 },
1066                 type: 'numeric'
1067         } );
1069         ts.addParser( {
1070                 id: 'number',
1071                 is: function ( s ) {
1072                         return $.tablesorter.numberRegex.test( $.trim( s ));
1073                 },
1074                 format: function ( s ) {
1075                         return $.tablesorter.formatDigit(s);
1076                 },
1077                 type: 'numeric'
1078         } );
1080 }( jQuery, mediaWiki ) );