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