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