Merge "(bug 37158) display personal menu on top of page tabs on Vector"
[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 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 // Cache jQuery object
640 var $cell = $( this );
641
642 // Get current column index
643 var i = this.column;
644
645 // Get current column sort order
646 this.order = this.count % 2;
647 this.count++;
648
649 // User only wants to sort on one column
650 if ( !e[config.sortMultiSortKey] ) {
651 // Flush the sort list
652 config.sortList = [];
653 // Add column to sort list
654 config.sortList.push( [i, this.order] );
655
656 // Multi column sorting
657 } else {
658 // The user has clicked on an already sorted column.
659 if ( isValueInArray( i, config.sortList ) ) {
660 // Reverse the sorting direction for all tables.
661 for ( var j = 0; j < config.sortList.length; j++ ) {
662 var s = config.sortList[j],
663 o = config.headerList[s[0]];
664 if ( s[0] === i ) {
665 o.count = s[1];
666 o.count++;
667 s[1] = o.count % 2;
668 }
669 }
670 } else {
671 // Add column to sort list array
672 config.sortList.push( [i, this.order] );
673 }
674 }
675
676 // Set CSS for headers
677 setHeadersCss( $table[0], $headers, config.sortList, sortCSS, sortMsg );
678 appendToTable(
679 $table[0], multisort( $table[0], config.sortList, cache )
680 );
681
682 // Stop normal event by returning false
683 return false;
684 }
685
686 // Cancel selection
687 } ).mousedown( function () {
688 if ( config.cancelSelection ) {
689 this.onselectstart = function () {
690 return false;
691 };
692 return false;
693 }
694 } );
695
696 /**
697 * Sorts the table. If no sorting is specified by passing a list of sort
698 * objects, the table is sorted according to the initial sorting order.
699 * Passing an empty array will reset sorting (basically just reset the headers
700 * making the table appear unsorted).
701 *
702 * @param sortList {Array} (optional) List of sort objects.
703 */
704 $table.data( 'tablesorter' ).sort = function( sortList ) {
705
706 if ( firstTime ) {
707 setupForFirstSort();
708 }
709
710 if ( sortList === undefined ) {
711 sortList = config.sortList;
712 } else if ( sortList.length > 0 ) {
713 sortList = convertSortList( sortList );
714 }
715
716 // re-build the cache for the tbody cells
717 cache = buildCache( table );
718
719 // set css for headers
720 setHeadersCss( table, $headers, sortList, sortCSS, sortMsg );
721
722 // sort the table and append it to the dom
723 appendToTable( table, multisort( table, sortList, cache ) );
724 };
725
726 // sort initially
727 if ( config.sortList.length > 0 ) {
728 setupForFirstSort();
729 config.sortList = convertSortList( config.sortList );
730 $table.data( 'tablesorter' ).sort();
731 }
732
733 } );
734 },
735
736 addParser: function ( parser ) {
737 var l = parsers.length,
738 a = true;
739 for ( var i = 0; i < l; i++ ) {
740 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
741 a = false;
742 }
743 }
744 if ( a ) {
745 parsers.push( parser );
746 }
747 },
748
749 formatDigit: function ( s ) {
750 if ( ts.transformTable !== false ) {
751 var out = '',
752 c;
753 for ( var p = 0; p < s.length; p++ ) {
754 c = s.charAt(p);
755 if ( c in ts.transformTable ) {
756 out += ts.transformTable[c];
757 } else {
758 out += c;
759 }
760 }
761 s = out;
762 }
763 var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
764 return ( isNaN(i)) ? 0 : i;
765 },
766
767 formatFloat: function ( s ) {
768 var i = parseFloat(s);
769 return ( isNaN(i)) ? 0 : i;
770 },
771
772 formatInt: function ( s ) {
773 var i = parseInt( s, 10 );
774 return ( isNaN(i)) ? 0 : i;
775 },
776
777 clearTableBody: function ( table ) {
778 if ( $.browser.msie ) {
779 var empty = function ( el ) {
780 while ( el.firstChild ) {
781 el.removeChild( el.firstChild );
782 }
783 };
784 empty( table.tBodies[0] );
785 } else {
786 table.tBodies[0].innerHTML = '';
787 }
788 }
789 };
790
791 // Shortcut
792 ts = $.tablesorter;
793
794 // Register as jQuery prototype method
795 $.fn.tablesorter = function ( settings ) {
796 return ts.construct( this, settings );
797 };
798
799 // Add default parsers
800 ts.addParser( {
801 id: 'text',
802 is: function ( s ) {
803 return true;
804 },
805 format: function ( s ) {
806 s = $.trim( s.toLowerCase() );
807 if ( ts.collationRegex ) {
808 var tsc = ts.collationTable;
809 s = s.replace( ts.collationRegex, function ( match ) {
810 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
811 return r.toLowerCase();
812 } );
813 }
814 return s;
815 },
816 type: 'text'
817 } );
818
819 ts.addParser( {
820 id: 'IPAddress',
821 is: function ( s ) {
822 return ts.rgx.IPAddress[0].test(s);
823 },
824 format: function ( s ) {
825 var a = s.split( '.' ),
826 r = '',
827 l = a.length;
828 for ( var i = 0; i < l; i++ ) {
829 var item = a[i];
830 if ( item.length === 1 ) {
831 r += '00' + item;
832 } else if ( item.length === 2 ) {
833 r += '0' + item;
834 } else {
835 r += item;
836 }
837 }
838 return $.tablesorter.formatFloat(r);
839 },
840 type: 'numeric'
841 } );
842
843 ts.addParser( {
844 id: 'currency',
845 is: function ( s ) {
846 return ts.rgx.currency[0].test(s);
847 },
848 format: function ( s ) {
849 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
850 },
851 type: 'numeric'
852 } );
853
854 ts.addParser( {
855 id: 'url',
856 is: function ( s ) {
857 return ts.rgx.url[0].test(s);
858 },
859 format: function ( s ) {
860 return $.trim( s.replace( ts.rgx.url[1], '' ) );
861 },
862 type: 'text'
863 } );
864
865 ts.addParser( {
866 id: 'isoDate',
867 is: function ( s ) {
868 return ts.rgx.isoDate[0].test(s);
869 },
870 format: function ( s ) {
871 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
872 new RegExp( /-/g), '/')).getTime() : '0' );
873 },
874 type: 'numeric'
875 } );
876
877 ts.addParser( {
878 id: 'usLongDate',
879 is: function ( s ) {
880 return ts.rgx.usLongDate[0].test(s);
881 },
882 format: function ( s ) {
883 return $.tablesorter.formatFloat( new Date(s).getTime() );
884 },
885 type: 'numeric'
886 } );
887
888 ts.addParser( {
889 id: 'date',
890 is: function ( s ) {
891 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
892 },
893 format: function ( s, table ) {
894 var match;
895 s = $.trim( s.toLowerCase() );
896
897 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
898 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
899 s = [ match[3], match[1], match[2] ];
900 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
901 s = [ match[3], match[2], match[1] ];
902 } else {
903 // If we get here, we don't know which order the dd-dd-dddd
904 // date is in. So return something not entirely invalid.
905 return '99999999';
906 }
907 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
908 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
909 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
910 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
911 } else {
912 // Should never get here
913 return '99999999';
914 }
915
916 // Pad Month and Day
917 if ( s[1].length === 1 ) {
918 s[1] = '0' + s[1];
919 }
920 if ( s[2].length === 1 ) {
921 s[2] = '0' + s[2];
922 }
923
924 var y;
925 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
926 // Guestimate years without centuries
927 if ( y < 30 ) {
928 s[0] = 2000 + y;
929 } else {
930 s[0] = 1900 + y;
931 }
932 }
933 while ( s[0].length < 4 ) {
934 s[0] = '0' + s[0];
935 }
936 return parseInt( s.join( '' ), 10 );
937 },
938 type: 'numeric'
939 } );
940
941 ts.addParser( {
942 id: 'time',
943 is: function ( s ) {
944 return ts.rgx.time[0].test(s);
945 },
946 format: function ( s ) {
947 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
948 },
949 type: 'numeric'
950 } );
951
952 ts.addParser( {
953 id: 'number',
954 is: function ( s, table ) {
955 return $.tablesorter.numberRegex.test( $.trim( s ));
956 },
957 format: function ( s ) {
958 return $.tablesorter.formatDigit(s);
959 },
960 type: 'numeric'
961 } );
962
963 }( jQuery, mediaWiki ) );