Merge "Maintain the page ID in WikiPage instead of relying on Title"
[lhc/web/wiklou.git] / resources / jquery / jquery.tablesorter.js
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 */
68
69 ( function ( $, mw ) {
70 /*jshint onevar:false */
71
72 /* Local scope */
73
74 var ts,
75 parsers = [];
76
77 /* Parser utility functions */
78
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 }
88
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' );
95
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.tagName.toLowerCase() === 'img' ) {
102 return $node.attr( 'alt' ) || ''; // handle undefined alt
103 } else {
104 return $.map( $.makeArray( node.childNodes ), function( elem ) {
105 // 1 is for document.ELEMENT_NODE (the constant is undefined on old browsers)
106 if ( elem.nodeType === 1 ) {
107 return getElementSortKey( elem );
108 } else {
109 return $.text( elem );
110 }
111 } ).join( '' );
112 }
113 }
114 }
115
116 function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
117 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
118 return $.trim( getElementSortKey( rows[rowIndex].cells[cellIndex] ) );
119 } else {
120 return '';
121 }
122 }
123
124 function detectParserForColumn( table, rows, cellIndex ) {
125 var l = parsers.length,
126 nodeValue,
127 // Start with 1 because 0 is the fallback parser
128 i = 1,
129 rowIndex = 0,
130 concurrent = 0,
131 needed = ( rows.length > 4 ) ? 5 : rows.length;
132
133 while( i < l ) {
134 nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
135 if ( nodeValue !== '') {
136 if ( parsers[i].is( nodeValue, table ) ) {
137 concurrent++;
138 rowIndex++;
139 if ( concurrent >= needed ) {
140 // Confirmed the parser for multiple cells, let's return it
141 return parsers[i];
142 }
143 } else {
144 // Check next parser, reset rows
145 i++;
146 rowIndex = 0;
147 concurrent = 0;
148 }
149 } else {
150 // Empty cell
151 rowIndex++;
152 if ( rowIndex > rows.length ) {
153 rowIndex = 0;
154 i++;
155 }
156 }
157 }
158
159 // 0 is always the generic parser (text)
160 return parsers[0];
161 }
162
163 function buildParserCache( table, $headers ) {
164 var rows = table.tBodies[0].rows,
165 sortType,
166 parsers = [];
167
168 if ( rows[0] ) {
169
170 var cells = rows[0].cells,
171 len = cells.length,
172 i, parser;
173
174 for ( i = 0; i < len; i++ ) {
175 parser = false;
176 sortType = $headers.eq( i ).data( 'sortType' );
177 if ( sortType !== undefined ) {
178 parser = getParserById( sortType );
179 }
180
181 if ( parser === false ) {
182 parser = detectParserForColumn( table, rows, i );
183 }
184
185 parsers.push( parser );
186 }
187 }
188 return parsers;
189 }
190
191 /* Other utility functions */
192
193 function buildCache( table ) {
194 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
195 totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
196 parsers = table.config.parsers,
197 cache = {
198 row: [],
199 normalized: []
200 };
201
202 for ( var i = 0; i < totalRows; ++i ) {
203
204 // Add the table data to main data array
205 var $row = $( table.tBodies[0].rows[i] ),
206 cols = [];
207
208 // if this is a child row, add it to the last row's children and
209 // continue to the next row
210 if ( $row.hasClass( table.config.cssChildRow ) ) {
211 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
212 // go to the next for loop
213 continue;
214 }
215
216 cache.row.push( $row );
217
218 for ( var j = 0; j < totalCells; ++j ) {
219 cols.push( parsers[j].format( getElementSortKey( $row[0].cells[j] ), table, $row[0].cells[j] ) );
220 }
221
222 cols.push( cache.normalized.length ); // add position for rowCache
223 cache.normalized.push( cols );
224 cols = null;
225 }
226
227 return cache;
228 }
229
230 function appendToTable( table, cache ) {
231 var row = cache.row,
232 normalized = cache.normalized,
233 totalRows = normalized.length,
234 checkCell = ( normalized[0].length - 1 ),
235 fragment = document.createDocumentFragment();
236
237 for ( var i = 0; i < totalRows; i++ ) {
238 var pos = normalized[i][checkCell];
239
240 var l = row[pos].length;
241
242 for ( var j = 0; j < l; j++ ) {
243 fragment.appendChild( row[pos][j] );
244 }
245
246 }
247 table.tBodies[0].appendChild( fragment );
248
249 $( table ).trigger( 'sortEnd.tablesorter' );
250 }
251
252 /**
253 * Find all header rows in a thead-less table and put them in a <thead> tag.
254 * This only treats a row as a header row if it contains only <th>s (no <td>s)
255 * and if it is preceded entirely by header rows. The algorithm stops when
256 * it encounters the first non-header row.
257 *
258 * After this, it will look at all rows at the bottom for footer rows
259 * And place these in a tfoot using similar rules.
260 * @param $table jQuery object for a <table>
261 */
262 function emulateTHeadAndFoot( $table ) {
263 var $rows = $table.find( '> tbody > tr' );
264 if( !$table.get(0).tHead ) {
265 var $thead = $( '<thead>' );
266 $rows.each( function () {
267 if ( $(this).children( 'td' ).length > 0 ) {
268 // This row contains a <td>, so it's not a header row
269 // Stop here
270 return false;
271 }
272 $thead.append( this );
273 } );
274 $table.find(' > tbody:first').before( $thead );
275 }
276 if( !$table.get(0).tFoot ) {
277 var $tfoot = $( '<tfoot>' );
278 var len = $rows.length;
279 for ( var i = len-1; i >= 0; i-- ) {
280 if( $( $rows[i] ).children( 'td' ).length > 0 ){
281 break;
282 }
283 $tfoot.prepend( $( $rows[i] ));
284 }
285 $table.append( $tfoot );
286 }
287 }
288
289 function buildHeaders( table, msg ) {
290 var maxSeen = 0,
291 longest,
292 realCellIndex = 0,
293 $tableHeaders = $( 'thead:eq(0) > tr', table );
294 if ( $tableHeaders.length > 1 ) {
295 $tableHeaders.each( function () {
296 if ( this.cells.length > maxSeen ) {
297 maxSeen = this.cells.length;
298 longest = this;
299 }
300 });
301 $tableHeaders = $( longest );
302 }
303 $tableHeaders = $tableHeaders.children( 'th' ).each( function ( index ) {
304 this.column = realCellIndex;
305
306 var colspan = this.colspan;
307 colspan = colspan ? parseInt( colspan, 10 ) : 1;
308 realCellIndex += colspan;
309
310 this.order = 0;
311 this.count = 0;
312
313 if ( $( this ).is( '.unsortable' ) ) {
314 this.sortDisabled = true;
315 }
316
317 if ( !this.sortDisabled ) {
318 $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
319 }
320
321 // add cell to headerList
322 table.config.headerList[index] = this;
323 } );
324
325 return $tableHeaders;
326
327 }
328
329 function isValueInArray( v, a ) {
330 var l = a.length;
331 for ( var i = 0; i < l; i++ ) {
332 if ( a[i][0] === v ) {
333 return true;
334 }
335 }
336 return false;
337 }
338
339 function setHeadersCss( table, $headers, list, css, msg, columnToHeader ) {
340 // Remove all header information and reset titles to default message
341 $headers.removeClass( css[0] ).removeClass( css[1] ).attr( 'title', msg[1] );
342
343 for ( var i = 0; i < list.length; i++ ) {
344 $headers.eq( columnToHeader[ list[i][0] ] )
345 .addClass( css[ list[i][1] ] )
346 .attr( 'title', msg[ list[i][1] ] );
347 }
348 }
349
350 function sortText( a, b ) {
351 return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
352 }
353
354 function sortTextDesc( a, b ) {
355 return ( (b < a) ? -1 : ((b > a) ? 1 : 0) );
356 }
357
358 function multisort( table, sortList, cache ) {
359 var sortFn = [];
360 var len = sortList.length;
361 for ( var i = 0; i < len; i++ ) {
362 sortFn[i] = ( sortList[i][1] ) ? sortTextDesc : sortText;
363 }
364 cache.normalized.sort( function ( array1, array2 ) {
365 var col, ret;
366 for ( var i = 0; i < len; i++ ) {
367 col = sortList[i][0];
368 ret = sortFn[i].call( this, array1[col], array2[col] );
369 if ( ret !== 0 ) {
370 return ret;
371 }
372 }
373 // Fall back to index number column to ensure stable sort
374 return sortText.call( this, array1[array1.length - 1], array2[array2.length - 1] );
375 } );
376 return cache;
377 }
378
379 function buildTransformTable() {
380 var digits = '0123456789,.'.split( '' );
381 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
382 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
383 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
384 ts.transformTable = false;
385 } else {
386 ts.transformTable = {};
387
388 // Unpack the transform table
389 var ascii = separatorTransformTable[0].split( '\t' ).concat( digitTransformTable[0].split( '\t' ) );
390 var localised = separatorTransformTable[1].split( '\t' ).concat( digitTransformTable[1].split( '\t' ) );
391
392 // Construct regex for number identification
393 for ( var i = 0; i < ascii.length; i++ ) {
394 ts.transformTable[localised[i]] = ascii[i];
395 digits.push( $.escapeRE( localised[i] ) );
396 }
397 }
398 var digitClass = '[' + digits.join( '', digits ) + ']';
399
400 // We allow a trailing percent sign, which we just strip. This works fine
401 // if percents and regular numbers aren't being mixed.
402 ts.numberRegex = new RegExp('^(' + '[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?' + // Fortran-style scientific
403 '|' + '[-+\u2212]?' + digitClass + '+[\\s\\xa0]*%?' + // Generic localised
404 ')$', 'i');
405 }
406
407 function buildDateTable() {
408 var regex = [];
409 ts.monthNames = {};
410
411 for ( var i = 1; i < 13; i++ ) {
412 var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
413 ts.monthNames[name] = i;
414 regex.push( $.escapeRE( name ) );
415 name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
416 ts.monthNames[name] = i;
417 regex.push( $.escapeRE( name ) );
418 }
419
420 // Build piped string
421 regex = regex.join( '|' );
422
423 // Build RegEx
424 // Any date formated with . , ' - or /
425 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
426
427 // Written Month name, dmy
428 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
429
430 // Written Month name, mdy
431 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
432
433 }
434
435 function explodeRowspans( $table ) {
436 // Split multi row cells into multiple cells with the same content
437 $table.find( '> tbody > tr > [rowspan]' ).each(function () {
438 var rowSpan = this.rowSpan;
439 this.rowSpan = 1;
440 var cell = $( this );
441 var next = cell.parent().nextAll();
442 for ( var i = 0; i < rowSpan - 1; i++ ) {
443 var td = next.eq( i ).children( 'td' );
444 if ( !td.length ) {
445 next.eq( i ).append( cell.clone() );
446 } else if ( this.cellIndex === 0 ) {
447 td.eq( this.cellIndex ).before( cell.clone() );
448 } else {
449 td.eq( this.cellIndex - 1 ).after( cell.clone() );
450 }
451 }
452 });
453 }
454
455 function buildCollationTable() {
456 ts.collationTable = mw.config.get( 'tableSorterCollation' );
457 ts.collationRegex = null;
458 if ( ts.collationTable ) {
459 var keys = [];
460
461 // Build array of key names
462 for ( var key in ts.collationTable ) {
463 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
464 keys.push(key);
465 }
466 }
467 if (keys.length) {
468 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
469 }
470 }
471 }
472
473 function cacheRegexs() {
474 if ( ts.rgx ) {
475 return;
476 }
477 ts.rgx = {
478 IPAddress: [
479 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
480 ],
481 currency: [
482 new RegExp( /(^[£$€¥]|[£$€¥]$)/),
483 new RegExp( /[£$€¥]/g)
484 ],
485 url: [
486 new RegExp( /^(https?|ftp|file):\/\/$/),
487 new RegExp( /(https?|ftp|file):\/\//)
488 ],
489 isoDate: [
490 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
491 ],
492 usLongDate: [
493 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)))$/)
494 ],
495 time: [
496 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
497 ]
498 };
499 }
500
501 /**
502 * Converts sort objects [ { Integer: String }, ... ] to the internally used nested array
503 * structure [ [ Integer , Integer ], ... ]
504 *
505 * @param sortObjects {Array} List of sort objects.
506 * @return {Array} List of internal sort definitions.
507 */
508
509 function convertSortList( sortObjects ) {
510 var sortList = [];
511 $.each( sortObjects, function( i, sortObject ) {
512 $.each ( sortObject, function( columnIndex, order ) {
513 var orderIndex = ( order === 'desc' ) ? 1 : 0;
514 sortList.push( [columnIndex, orderIndex] );
515 } );
516 } );
517 return sortList;
518 }
519
520 /* Public scope */
521
522 $.tablesorter = {
523
524 defaultOptions: {
525 cssHeader: 'headerSort',
526 cssAsc: 'headerSortUp',
527 cssDesc: 'headerSortDown',
528 cssChildRow: 'expand-child',
529 sortInitialOrder: 'asc',
530 sortMultiSortKey: 'shiftKey',
531 sortLocaleCompare: false,
532 parsers: {},
533 widgets: [],
534 headers: {},
535 cancelSelection: true,
536 sortList: [],
537 headerList: [],
538 selectorHeaders: 'thead tr:eq(0) th',
539 debug: false
540 },
541
542 dateRegex: [],
543 monthNames: {},
544
545 /**
546 * @param $tables {jQuery}
547 * @param settings {Object} (optional)
548 */
549 construct: function ( $tables, settings ) {
550 return $tables.each( function ( i, table ) {
551 // Declare and cache.
552 var $headers, cache, config,
553 headerToColumns, columnToHeader, colspanOffset,
554 $table = $( table ),
555 firstTime = true;
556
557 // Quit if no tbody
558 if ( !table.tBodies ) {
559 return;
560 }
561 if ( !table.tHead ) {
562 // No thead found. Look for rows with <th>s and
563 // move them into a <thead> tag or a <tfoot> tag
564 emulateTHeadAndFoot( $table );
565
566 // Still no thead? Then quit
567 if ( !table.tHead ) {
568 return;
569 }
570 }
571 $table.addClass( 'jquery-tablesorter' );
572
573 // FIXME config should probably not be stored in the plain table node
574 // New config object.
575 table.config = {};
576
577 // Merge and extend.
578 config = $.extend( table.config, $.tablesorter.defaultOptions, settings );
579
580 // Save the settings where they read
581 $.data( table, 'tablesorter', { config: config } );
582
583 // Get the CSS class names, could be done else where.
584 var sortCSS = [ config.cssDesc, config.cssAsc ];
585 var sortMsg = [ mw.msg( 'sort-descending' ), mw.msg( 'sort-ascending' ) ];
586
587 // Build headers
588 $headers = buildHeaders( table, sortMsg );
589
590 // Grab and process locale settings
591 buildTransformTable();
592 buildDateTable();
593 buildCollationTable();
594
595 // Precaching regexps can bring 10 fold
596 // performance improvements in some browsers.
597 cacheRegexs();
598
599 function setupForFirstSort() {
600 firstTime = false;
601
602 // Legacy fix of .sortbottoms
603 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
604 // and put the <tfoot> at the end of the <table>
605 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
606 if ( $sortbottoms.length ) {
607 var $tfoot = $table.children( 'tfoot' );
608 if ( $tfoot.length ) {
609 $tfoot.eq(0).prepend( $sortbottoms );
610 } else {
611 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
612 }
613 }
614
615 explodeRowspans( $table );
616
617 // try to auto detect column type, and store in tables config
618 table.config.parsers = buildParserCache( table, $headers );
619 }
620
621 // as each header can span over multiple columns (using colspan=N),
622 // we have to bidirectionally map headers to their columns and columns to their headers
623 headerToColumns = [];
624 columnToHeader = [];
625 colspanOffset = 0;
626 $headers.each( function ( headerIndex ) {
627 var columns = [];
628 for ( var i = 0; i < this.colSpan; i++ ) {
629 columnToHeader[ colspanOffset + i ] = headerIndex;
630 columns.push( colspanOffset + i );
631 }
632
633 headerToColumns[ headerIndex ] = columns;
634 colspanOffset += this.colSpan;
635 } );
636
637 // Apply event handling to headers
638 // this is too big, perhaps break it out?
639 $headers.filter( ':not(.unsortable)' ).click( function ( e ) {
640 if ( e.target.nodeName.toLowerCase() === 'a' ) {
641 // The user clicked on a link inside a table header
642 // Do nothing and let the default link click action continue
643 return true;
644 }
645
646 if ( firstTime ) {
647 setupForFirstSort();
648 }
649
650 // Build the cache for the tbody cells
651 // to share between calculations for this sort action.
652 // Re-calculated each time a sort action is performed due to possiblity
653 // that sort values change. Shouldn't be too expensive, but if it becomes
654 // too slow an event based system should be implemented somehow where
655 // cells get event .change() and bubbles up to the <table> here
656 cache = buildCache( table );
657
658 var totalRows = ( $table[0].tBodies[0] && $table[0].tBodies[0].rows.length ) || 0;
659 if ( !table.sortDisabled && totalRows > 0 ) {
660 // Get current column sort order
661 this.order = this.count % 2;
662 this.count++;
663
664 var cell = this;
665 // Get current column index
666 var columns = headerToColumns[this.column];
667 var newSortList = $.map( columns, function (c) {
668 // jQuery "helpfully" flattens the arrays...
669 return [[c, cell.order]];
670 });
671 // Index of first column belonging to this header
672 var i = columns[0];
673
674 if ( !e[config.sortMultiSortKey] ) {
675 // User only wants to sort on one column set
676 // Flush the sort list and add new columns
677 config.sortList = newSortList;
678 } else {
679 // Multi column sorting
680 // It is not possible for one column to belong to multiple headers,
681 // so this is okay - we don't need to check for every value in the columns array
682 if ( isValueInArray( i, config.sortList ) ) {
683 // The user has clicked on an already sorted column.
684 // Reverse the sorting direction for all tables.
685 for ( var j = 0; j < config.sortList.length; j++ ) {
686 var s = config.sortList[j],
687 o = config.headerList[s[0]];
688 if ( isValueInArray( s[0], newSortList ) ) {
689 o.count = s[1];
690 o.count++;
691 s[1] = o.count % 2;
692 }
693 }
694 } else {
695 // Add columns to sort list array
696 config.sortList = config.sortList.concat( newSortList );
697 }
698 }
699
700 // Set CSS for headers
701 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg, columnToHeader );
702 appendToTable(
703 $table[0], multisort( $table[0], config.sortList, cache )
704 );
705
706 // Stop normal event by returning false
707 return false;
708 }
709
710 // Cancel selection
711 } ).mousedown( function () {
712 if ( config.cancelSelection ) {
713 this.onselectstart = function () {
714 return false;
715 };
716 return false;
717 }
718 } );
719
720 /**
721 * Sorts the table. If no sorting is specified by passing a list of sort
722 * objects, the table is sorted according to the initial sorting order.
723 * Passing an empty array will reset sorting (basically just reset the headers
724 * making the table appear unsorted).
725 *
726 * @param sortList {Array} (optional) List of sort objects.
727 */
728 $table.data( 'tablesorter' ).sort = function( sortList ) {
729
730 if ( firstTime ) {
731 setupForFirstSort();
732 }
733
734 if ( sortList === undefined ) {
735 sortList = config.sortList;
736 } else if ( sortList.length > 0 ) {
737 sortList = convertSortList( sortList );
738 }
739
740 // re-build the cache for the tbody cells
741 cache = buildCache( table );
742
743 // set css for headers
744 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg, columnToHeader );
745
746 // sort the table and append it to the dom
747 appendToTable( table, multisort( table, sortList, cache ) );
748 };
749
750 // sort initially
751 if ( config.sortList.length > 0 ) {
752 setupForFirstSort();
753 config.sortList = convertSortList( config.sortList );
754 $table.data( 'tablesorter' ).sort();
755 }
756
757 } );
758 },
759
760 addParser: function ( parser ) {
761 var l = parsers.length,
762 a = true;
763 for ( var i = 0; i < l; i++ ) {
764 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
765 a = false;
766 }
767 }
768 if ( a ) {
769 parsers.push( parser );
770 }
771 },
772
773 formatDigit: function ( s ) {
774 var out, c, p, i;
775 if ( ts.transformTable !== false ) {
776 out = '';
777 for ( p = 0; p < s.length; p++ ) {
778 c = s.charAt(p);
779 if ( c in ts.transformTable ) {
780 out += ts.transformTable[c];
781 } else {
782 out += c;
783 }
784 }
785 s = out;
786 }
787 i = parseFloat( s.replace( /[, ]/g, '' ).replace( '\u2212', '-' ) );
788 return isNaN( i ) ? 0 : i;
789 },
790
791 formatFloat: function ( s ) {
792 var i = parseFloat(s);
793 return isNaN( i ) ? 0 : i;
794 },
795
796 formatInt: function ( s ) {
797 var i = parseInt( s, 10 );
798 return isNaN( i ) ? 0 : i;
799 },
800
801 clearTableBody: function ( table ) {
802 $( table.tBodies[0] ).empty();
803 }
804 };
805
806 // Shortcut
807 ts = $.tablesorter;
808
809 // Register as jQuery prototype method
810 $.fn.tablesorter = function ( settings ) {
811 return ts.construct( this, settings );
812 };
813
814 // Add default parsers
815 ts.addParser( {
816 id: 'text',
817 is: function () {
818 return true;
819 },
820 format: function ( s ) {
821 s = $.trim( s.toLowerCase() );
822 if ( ts.collationRegex ) {
823 var tsc = ts.collationTable;
824 s = s.replace( ts.collationRegex, function ( match ) {
825 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
826 return r.toLowerCase();
827 } );
828 }
829 return s;
830 },
831 type: 'text'
832 } );
833
834 ts.addParser( {
835 id: 'IPAddress',
836 is: function ( s ) {
837 return ts.rgx.IPAddress[0].test(s);
838 },
839 format: function ( s ) {
840 var a = s.split( '.' ),
841 r = '',
842 l = a.length;
843 for ( var i = 0; i < l; i++ ) {
844 var item = a[i];
845 if ( item.length === 1 ) {
846 r += '00' + item;
847 } else if ( item.length === 2 ) {
848 r += '0' + item;
849 } else {
850 r += item;
851 }
852 }
853 return $.tablesorter.formatFloat(r);
854 },
855 type: 'numeric'
856 } );
857
858 ts.addParser( {
859 id: 'currency',
860 is: function ( s ) {
861 return ts.rgx.currency[0].test(s);
862 },
863 format: function ( s ) {
864 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
865 },
866 type: 'numeric'
867 } );
868
869 ts.addParser( {
870 id: 'url',
871 is: function ( s ) {
872 return ts.rgx.url[0].test(s);
873 },
874 format: function ( s ) {
875 return $.trim( s.replace( ts.rgx.url[1], '' ) );
876 },
877 type: 'text'
878 } );
879
880 ts.addParser( {
881 id: 'isoDate',
882 is: function ( s ) {
883 return ts.rgx.isoDate[0].test(s);
884 },
885 format: function ( s ) {
886 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
887 new RegExp( /-/g), '/')).getTime() : '0' );
888 },
889 type: 'numeric'
890 } );
891
892 ts.addParser( {
893 id: 'usLongDate',
894 is: function ( s ) {
895 return ts.rgx.usLongDate[0].test(s);
896 },
897 format: function ( s ) {
898 return $.tablesorter.formatFloat( new Date(s).getTime() );
899 },
900 type: 'numeric'
901 } );
902
903 ts.addParser( {
904 id: 'date',
905 is: function ( s ) {
906 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
907 },
908 format: function ( s ) {
909 var match;
910 s = $.trim( s.toLowerCase() );
911
912 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
913 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
914 s = [ match[3], match[1], match[2] ];
915 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
916 s = [ match[3], match[2], match[1] ];
917 } else {
918 // If we get here, we don't know which order the dd-dd-dddd
919 // date is in. So return something not entirely invalid.
920 return '99999999';
921 }
922 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
923 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
924 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
925 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
926 } else {
927 // Should never get here
928 return '99999999';
929 }
930
931 // Pad Month and Day
932 if ( s[1].length === 1 ) {
933 s[1] = '0' + s[1];
934 }
935 if ( s[2].length === 1 ) {
936 s[2] = '0' + s[2];
937 }
938
939 var y;
940 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
941 // Guestimate years without centuries
942 if ( y < 30 ) {
943 s[0] = 2000 + y;
944 } else {
945 s[0] = 1900 + y;
946 }
947 }
948 while ( s[0].length < 4 ) {
949 s[0] = '0' + s[0];
950 }
951 return parseInt( s.join( '' ), 10 );
952 },
953 type: 'numeric'
954 } );
955
956 ts.addParser( {
957 id: 'time',
958 is: function ( s ) {
959 return ts.rgx.time[0].test(s);
960 },
961 format: function ( s ) {
962 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
963 },
964 type: 'numeric'
965 } );
966
967 ts.addParser( {
968 id: 'number',
969 is: function ( s ) {
970 return $.tablesorter.numberRegex.test( $.trim( s ));
971 },
972 format: function ( s ) {
973 return $.tablesorter.formatDigit(s);
974 },
975 type: 'numeric'
976 } );
977
978 }( jQuery, mediaWiki ) );