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