merged master
[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 * @option String cssHeader ( optional ) A string of the class name to be appended
23 * to sortable tr elements in the thead of the table. Default value:
24 * "header"
25 *
26 * @option String cssAsc ( optional ) A string of the class name to be appended to
27 * sortable tr elements in the thead on a ascending sort. Default value:
28 * "headerSortUp"
29 *
30 * @option String cssDesc ( optional ) A string of the class name to be appended
31 * to sortable tr elements in the thead on a descending sort. Default
32 * value: "headerSortDown"
33 *
34 * @option String sortInitialOrder ( optional ) A string of the inital sorting
35 * order can be asc or desc. Default value: "asc"
36 *
37 * @option String sortMultisortKey ( optional ) A string of the multi-column sort
38 * key. Default value: "shiftKey"
39 *
40 * @option Boolean sortLocaleCompare ( optional ) Boolean flag indicating whatever
41 * to use String.localeCampare method or not. Set to false.
42 *
43 * @option Boolean cancelSelection ( optional ) Boolean flag indicating if
44 * tablesorter should cancel selection of the table headers text.
45 * Default value: true
46 *
47 * @option Boolean debug ( optional ) Boolean flag indicating if tablesorter
48 * should display debuging information usefull for development.
49 *
50 * @type jQuery
51 *
52 * @name tablesorter
53 *
54 * @cat Plugins/Tablesorter
55 *
56 * @author Christian Bach/christian.bach@polyester.se
57 */
58
59 ( function ( $, mw ) {
60
61 /* Local scope */
62
63 var ts,
64 parsers = [];
65
66 /* Parser utility functions */
67
68 function getParserById( name ) {
69 var len = parsers.length;
70 for ( var i = 0; i < len; i++ ) {
71 if ( parsers[i].id.toLowerCase() === name.toLowerCase() ) {
72 return parsers[i];
73 }
74 }
75 return false;
76 }
77
78 function getElementText( node ) {
79 var $node = $( node ),
80 // Use data-sort-value attribute.
81 // Use data() instead of attr() so that live value changes
82 // are processed as well (bug 38152).
83 data = $node.data( 'sortValue' );
84
85 if ( data !== null && data !== undefined ) {
86 // Cast any numbers or other stuff to a string, methods
87 // like charAt, toLowerCase and split are expected.
88 return String( data );
89 } else {
90 return $node.text();
91 }
92 }
93
94 function getTextFromRowAndCellIndex( rows, rowIndex, cellIndex ) {
95 if ( rows[rowIndex] && rows[rowIndex].cells[cellIndex] ) {
96 return $.trim( getElementText( rows[rowIndex].cells[cellIndex] ) );
97 } else {
98 return '';
99 }
100 }
101
102 function detectParserForColumn( table, rows, cellIndex ) {
103 var l = parsers.length,
104 nodeValue,
105 // Start with 1 because 0 is the fallback parser
106 i = 1,
107 rowIndex = 0,
108 concurrent = 0,
109 needed = ( rows.length > 4 ) ? 5 : rows.length;
110
111 while( i < l ) {
112 nodeValue = getTextFromRowAndCellIndex( rows, rowIndex, cellIndex );
113 if ( nodeValue !== '') {
114 if ( parsers[i].is( nodeValue, table ) ) {
115 concurrent++;
116 rowIndex++;
117 if ( concurrent >= needed ) {
118 // Confirmed the parser for multiple cells, let's return it
119 return parsers[i];
120 }
121 } else {
122 // Check next parser, reset rows
123 i++;
124 rowIndex = 0;
125 concurrent = 0;
126 }
127 } else {
128 // Empty cell
129 rowIndex++;
130 if ( rowIndex > rows.length ) {
131 rowIndex = 0;
132 i++;
133 }
134 }
135 }
136
137 // 0 is always the generic parser (text)
138 return parsers[0];
139 }
140
141 function buildParserCache( table, $headers ) {
142 var rows = table.tBodies[0].rows,
143 sortType,
144 parsers = [];
145
146 if ( rows[0] ) {
147
148 var cells = rows[0].cells,
149 len = cells.length,
150 i, parser;
151
152 for ( i = 0; i < len; i++ ) {
153 parser = false;
154 sortType = $headers.eq( i ).data( 'sort-type' );
155 if ( sortType !== undefined ) {
156 parser = getParserById( sortType );
157 }
158
159 if ( parser === false ) {
160 parser = detectParserForColumn( table, rows, i );
161 }
162
163 parsers.push( parser );
164 }
165 }
166 return parsers;
167 }
168
169 /* Other utility functions */
170
171 function buildCache( table ) {
172 var totalRows = ( table.tBodies[0] && table.tBodies[0].rows.length ) || 0,
173 totalCells = ( table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length ) || 0,
174 parsers = table.config.parsers,
175 cache = {
176 row: [],
177 normalized: []
178 };
179
180 for ( var i = 0; i < totalRows; ++i ) {
181
182 // Add the table data to main data array
183 var $row = $( table.tBodies[0].rows[i] ),
184 cols = [];
185
186 // if this is a child row, add it to the last row's children and
187 // continue to the next row
188 if ( $row.hasClass( table.config.cssChildRow ) ) {
189 cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add( $row );
190 // go to the next for loop
191 continue;
192 }
193
194 cache.row.push( $row );
195
196 for ( var j = 0; j < totalCells; ++j ) {
197 cols.push( parsers[j].format( getElementText( $row[0].cells[j] ), table, $row[0].cells[j] ) );
198 }
199
200 cols.push( cache.normalized.length ); // add position for rowCache
201 cache.normalized.push( cols );
202 cols = null;
203 }
204
205 return cache;
206 }
207
208 function appendToTable( table, cache ) {
209 var row = cache.row,
210 normalized = cache.normalized,
211 totalRows = normalized.length,
212 checkCell = ( normalized[0].length - 1 ),
213 fragment = document.createDocumentFragment();
214
215 for ( var i = 0; i < totalRows; i++ ) {
216 var pos = normalized[i][checkCell];
217
218 var l = row[pos].length;
219
220 for ( var j = 0; j < l; j++ ) {
221 fragment.appendChild( row[pos][j] );
222 }
223
224 }
225 table.tBodies[0].appendChild( fragment );
226 }
227
228 /**
229 * Find all header rows in a thead-less table and put them in a <thead> tag.
230 * This only treats a row as a header row if it contains only <th>s (no <td>s)
231 * and if it is preceded entirely by header rows. The algorithm stops when
232 * it encounters the first non-header row.
233 *
234 * After this, it will look at all rows at the bottom for footer rows
235 * And place these in a tfoot using similar rules.
236 * @param $table jQuery object for a <table>
237 */
238 function emulateTHeadAndFoot( $table ) {
239 var $rows = $table.find( '> tbody > tr' );
240 if( !$table.get(0).tHead ) {
241 var $thead = $( '<thead>' );
242 $rows.each( function () {
243 if ( $(this).children( 'td' ).length > 0 ) {
244 // This row contains a <td>, so it's not a header row
245 // Stop here
246 return false;
247 }
248 $thead.append( this );
249 } );
250 $table.find(' > tbody:first').before( $thead );
251 }
252 if( !$table.get(0).tFoot ) {
253 var $tfoot = $( '<tfoot>' );
254 var len = $rows.length;
255 for ( var i = len-1; i >= 0; i-- ) {
256 if( $( $rows[i] ).children( 'td' ).length > 0 ){
257 break;
258 }
259 $tfoot.prepend( $( $rows[i] ));
260 }
261 $table.append( $tfoot );
262 }
263 }
264
265 function buildHeaders( table, msg ) {
266 var maxSeen = 0,
267 longest,
268 realCellIndex = 0,
269 $tableHeaders = $( 'thead:eq(0) > tr', table );
270 if ( $tableHeaders.length > 1 ) {
271 $tableHeaders.each( function () {
272 if ( this.cells.length > maxSeen ) {
273 maxSeen = this.cells.length;
274 longest = this;
275 }
276 });
277 $tableHeaders = $( longest );
278 }
279 $tableHeaders = $tableHeaders.children( 'th' ).each( function ( index ) {
280 this.column = realCellIndex;
281
282 var colspan = this.colspan;
283 colspan = colspan ? parseInt( colspan, 10 ) : 1;
284 realCellIndex += colspan;
285
286 this.order = 0;
287 this.count = 0;
288
289 if ( $( this ).is( '.unsortable' ) ) {
290 this.sortDisabled = true;
291 }
292
293 if ( !this.sortDisabled ) {
294 var $th = $( this ).addClass( table.config.cssHeader ).attr( 'title', msg[1] );
295 }
296
297 // add cell to headerList
298 table.config.headerList[index] = this;
299 } );
300
301 return $tableHeaders;
302
303 }
304
305 function isValueInArray( v, a ) {
306 var l = a.length;
307 for ( var i = 0; i < l; i++ ) {
308 if ( a[i][0] === v ) {
309 return true;
310 }
311 }
312 return false;
313 }
314
315 function setHeadersCss( table, $headers, list, css, msg ) {
316 // Remove all header information
317 $headers.removeClass( css[0] ).removeClass( css[1] );
318
319 var h = [];
320 $headers.each( function ( offset ) {
321 if ( !this.sortDisabled ) {
322 h[this.column] = $( this );
323 }
324 } );
325
326 var l = list.length;
327 for ( var i = 0; i < l; i++ ) {
328 h[ list[i][0] ].addClass( css[ list[i][1] ] ).attr( 'title', msg[ list[i][1] ] );
329 }
330 }
331
332 function sortText( a, b ) {
333 return ( (a < b) ? false : ((a > b) ? true : 0) );
334 }
335
336 function sortTextDesc( a, b ) {
337 return ( (b < a) ? false : ((b > a) ? true : 0) );
338 }
339
340 function checkSorting( array1, array2, sortList ) {
341 var col, fn, ret;
342 for ( var i = 0, len = sortList.length; i < len; i++ ) {
343 col = sortList[i][0];
344 fn = ( sortList[i][1] ) ? sortTextDesc : sortText;
345 ret = fn.call( this, array1[col], array2[col] );
346 if ( ret !== 0 ) {
347 return ret;
348 }
349 }
350 return ret;
351 }
352
353 // Merge sort algorithm
354 // Based on http://en.literateprograms.org/Merge_sort_(JavaScript)
355 function mergeSortHelper( array, begin, beginRight, end, sortList ) {
356 for ( ; begin < beginRight; ++begin ) {
357 if ( checkSorting( array[begin], array[beginRight], sortList ) ) {
358 var v = array[begin];
359 array[begin] = array[beginRight];
360 var begin2 = beginRight;
361 while ( begin2 + 1 < end && checkSorting( v, array[begin2 + 1], sortList ) ) {
362 var tmp = array[begin2];
363 array[begin2] = array[begin2 + 1];
364 array[begin2 + 1] = tmp;
365 ++begin2;
366 }
367 array[begin2] = v;
368 }
369 }
370 }
371
372 function mergeSort(array, begin, end, sortList) {
373 var size = end - begin;
374 if ( size < 2 ) {
375 return;
376 }
377
378 var beginRight = begin + Math.floor(size / 2);
379
380 mergeSort( array, begin, beginRight, sortList );
381 mergeSort( array, beginRight, end, sortList );
382 mergeSortHelper( array, begin, beginRight, end, sortList );
383 }
384
385 function multisort( table, sortList, cache ) {
386 var i = sortList.length;
387 mergeSort( cache.normalized, 0, cache.normalized.length, sortList );
388
389 return cache;
390 }
391
392 function buildTransformTable() {
393 var digits = '0123456789,.'.split( '' );
394 var separatorTransformTable = mw.config.get( 'wgSeparatorTransformTable' );
395 var digitTransformTable = mw.config.get( 'wgDigitTransformTable' );
396 if ( separatorTransformTable === null || ( separatorTransformTable[0] === '' && digitTransformTable[2] === '' ) ) {
397 ts.transformTable = false;
398 } else {
399 ts.transformTable = {};
400
401 // Unpack the transform table
402 var ascii = separatorTransformTable[0].split( "\t" ).concat( digitTransformTable[0].split( "\t" ) );
403 var localised = separatorTransformTable[1].split( "\t" ).concat( digitTransformTable[1].split( "\t" ) );
404
405 // Construct regex for number identification
406 for ( var i = 0; i < ascii.length; i++ ) {
407 ts.transformTable[localised[i]] = ascii[i];
408 digits.push( $.escapeRE( localised[i] ) );
409 }
410 }
411 var digitClass = '[' + digits.join( '', digits ) + ']';
412
413 // We allow a trailing percent sign, which we just strip. This works fine
414 // if percents and regular numbers aren't being mixed.
415 ts.numberRegex = new RegExp("^(" + "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
416 "|" + "[-+\u2212]?" + digitClass + "+[\\s\\xa0]*%?" + // Generic localised
417 ")$", "i");
418 }
419
420 function buildDateTable() {
421 var regex = [];
422 ts.monthNames = {};
423
424 for ( var i = 1; i < 13; i++ ) {
425 var name = mw.config.get( 'wgMonthNames' )[i].toLowerCase();
426 ts.monthNames[name] = i;
427 regex.push( $.escapeRE( name ) );
428 name = mw.config.get( 'wgMonthNamesShort' )[i].toLowerCase().replace( '.', '' );
429 ts.monthNames[name] = i;
430 regex.push( $.escapeRE( name ) );
431 }
432
433 // Build piped string
434 regex = regex.join( '|' );
435
436 // Build RegEx
437 // Any date formated with . , ' - or /
438 ts.dateRegex[0] = new RegExp( /^\s*(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{1,2})[\,\.\-\/'\s]{1,2}(\d{2,4})\s*?/i);
439
440 // Written Month name, dmy
441 ts.dateRegex[1] = new RegExp( '^\\s*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
442
443 // Written Month name, mdy
444 ts.dateRegex[2] = new RegExp( '^\\s*(' + regex + ')' + '[\\,\\.\\-\\/\'\\s]*(\\d{1,2})[\\,\\.\\-\\/\'\\s]*(\\d{2,4})\\s*$', 'i' );
445
446 }
447
448 function explodeRowspans( $table ) {
449 // Split multi row cells into multiple cells with the same content
450 $table.find( '> tbody > tr > [rowspan]' ).each(function () {
451 var rowSpan = this.rowSpan;
452 this.rowSpan = 1;
453 var cell = $( this );
454 var next = cell.parent().nextAll();
455 for ( var i = 0; i < rowSpan - 1; i++ ) {
456 var td = next.eq( i ).children( 'td' );
457 if ( !td.length ) {
458 next.eq( i ).append( cell.clone() );
459 } else if ( this.cellIndex === 0 ) {
460 td.eq( this.cellIndex ).before( cell.clone() );
461 } else {
462 td.eq( this.cellIndex - 1 ).after( cell.clone() );
463 }
464 }
465 });
466 }
467
468 function buildCollationTable() {
469 ts.collationTable = mw.config.get( 'tableSorterCollation' );
470 ts.collationRegex = null;
471 if ( ts.collationTable ) {
472 var keys = [];
473
474 // Build array of key names
475 for ( var key in ts.collationTable ) {
476 if ( ts.collationTable.hasOwnProperty(key) ) { //to be safe
477 keys.push(key);
478 }
479 }
480 if (keys.length) {
481 ts.collationRegex = new RegExp( '[' + keys.join( '' ) + ']', 'ig' );
482 }
483 }
484 }
485
486 function cacheRegexs() {
487 if ( ts.rgx ) {
488 return;
489 }
490 ts.rgx = {
491 IPAddress: [
492 new RegExp( /^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/)
493 ],
494 currency: [
495 new RegExp( /^[£$€?.]/),
496 new RegExp( /[£$€]/g)
497 ],
498 url: [
499 new RegExp( /^(https?|ftp|file):\/\/$/),
500 new RegExp( /(https?|ftp|file):\/\//)
501 ],
502 isoDate: [
503 new RegExp( /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/)
504 ],
505 usLongDate: [
506 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)))$/)
507 ],
508 time: [
509 new RegExp( /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/)
510 ]
511 };
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 // 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 );
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 // Apply event handling to headers
593 // this is too big, perhaps break it out?
594 $headers.click( function ( e ) {
595 if ( e.target.nodeName.toLowerCase() === 'a' ) {
596 // The user clicked on a link inside a table header
597 // Do nothing and let the default link click action continue
598 return true;
599 }
600
601 if ( firstTime ) {
602 firstTime = false;
603
604 // Legacy fix of .sortbottoms
605 // Wrap them inside inside a tfoot (because that's what they actually want to be) &
606 // and put the <tfoot> at the end of the <table>
607 var $sortbottoms = $table.find( '> tbody > tr.sortbottom' );
608 if ( $sortbottoms.length ) {
609 var $tfoot = $table.children( 'tfoot' );
610 if ( $tfoot.length ) {
611 $tfoot.eq(0).prepend( $sortbottoms );
612 } else {
613 $table.append( $( '<tfoot>' ).append( $sortbottoms ) );
614 }
615 }
616
617 explodeRowspans( $table );
618 // try to auto detect column type, and store in tables config
619 table.config.parsers = buildParserCache( table, $headers );
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
692 addParser: function ( parser ) {
693 var l = parsers.length,
694 a = true;
695 for ( var i = 0; i < l; i++ ) {
696 if ( parsers[i].id.toLowerCase() === parser.id.toLowerCase() ) {
697 a = false;
698 }
699 }
700 if ( a ) {
701 parsers.push( parser );
702 }
703 },
704
705 formatDigit: function ( s ) {
706 if ( ts.transformTable !== false ) {
707 var out = '',
708 c;
709 for ( var p = 0; p < s.length; p++ ) {
710 c = s.charAt(p);
711 if ( c in ts.transformTable ) {
712 out += ts.transformTable[c];
713 } else {
714 out += c;
715 }
716 }
717 s = out;
718 }
719 var i = parseFloat( s.replace( /[, ]/g, '' ).replace( "\u2212", '-' ) );
720 return ( isNaN(i)) ? 0 : i;
721 },
722
723 formatFloat: function ( s ) {
724 var i = parseFloat(s);
725 return ( isNaN(i)) ? 0 : i;
726 },
727
728 formatInt: function ( s ) {
729 var i = parseInt( s, 10 );
730 return ( isNaN(i)) ? 0 : i;
731 },
732
733 clearTableBody: function ( table ) {
734 if ( $.browser.msie ) {
735 var empty = function ( el ) {
736 while ( el.firstChild ) {
737 el.removeChild( el.firstChild );
738 }
739 };
740 empty( table.tBodies[0] );
741 } else {
742 table.tBodies[0].innerHTML = '';
743 }
744 }
745 };
746
747 // Shortcut
748 ts = $.tablesorter;
749
750 // Register as jQuery prototype method
751 $.fn.tablesorter = function ( settings ) {
752 return ts.construct( this, settings );
753 };
754
755 // Add default parsers
756 ts.addParser( {
757 id: 'text',
758 is: function ( s ) {
759 return true;
760 },
761 format: function ( s ) {
762 s = $.trim( s.toLowerCase() );
763 if ( ts.collationRegex ) {
764 var tsc = ts.collationTable;
765 s = s.replace( ts.collationRegex, function ( match ) {
766 var r = tsc[match] ? tsc[match] : tsc[match.toUpperCase()];
767 return r.toLowerCase();
768 } );
769 }
770 return s;
771 },
772 type: 'text'
773 } );
774
775 ts.addParser( {
776 id: 'IPAddress',
777 is: function ( s ) {
778 return ts.rgx.IPAddress[0].test(s);
779 },
780 format: function ( s ) {
781 var a = s.split( '.' ),
782 r = '',
783 l = a.length;
784 for ( var i = 0; i < l; i++ ) {
785 var item = a[i];
786 if ( item.length === 1 ) {
787 r += '00' + item;
788 } else if ( item.length === 2 ) {
789 r += '0' + item;
790 } else {
791 r += item;
792 }
793 }
794 return $.tablesorter.formatFloat(r);
795 },
796 type: 'numeric'
797 } );
798
799 ts.addParser( {
800 id: 'currency',
801 is: function ( s ) {
802 return ts.rgx.currency[0].test(s);
803 },
804 format: function ( s ) {
805 return $.tablesorter.formatDigit( s.replace( ts.rgx.currency[1], '' ) );
806 },
807 type: 'numeric'
808 } );
809
810 ts.addParser( {
811 id: 'url',
812 is: function ( s ) {
813 return ts.rgx.url[0].test(s);
814 },
815 format: function ( s ) {
816 return $.trim( s.replace( ts.rgx.url[1], '' ) );
817 },
818 type: 'text'
819 } );
820
821 ts.addParser( {
822 id: 'isoDate',
823 is: function ( s ) {
824 return ts.rgx.isoDate[0].test(s);
825 },
826 format: function ( s ) {
827 return $.tablesorter.formatFloat((s !== '') ? new Date(s.replace(
828 new RegExp( /-/g), '/')).getTime() : '0' );
829 },
830 type: 'numeric'
831 } );
832
833 ts.addParser( {
834 id: 'usLongDate',
835 is: function ( s ) {
836 return ts.rgx.usLongDate[0].test(s);
837 },
838 format: function ( s ) {
839 return $.tablesorter.formatFloat( new Date(s).getTime() );
840 },
841 type: 'numeric'
842 } );
843
844 ts.addParser( {
845 id: 'date',
846 is: function ( s ) {
847 return ( ts.dateRegex[0].test(s) || ts.dateRegex[1].test(s) || ts.dateRegex[2].test(s ));
848 },
849 format: function ( s, table ) {
850 var match;
851 s = $.trim( s.toLowerCase() );
852
853 if ( ( match = s.match( ts.dateRegex[0] ) ) !== null ) {
854 if ( mw.config.get( 'wgDefaultDateFormat' ) === 'mdy' || mw.config.get( 'wgContentLanguage' ) === 'en' ) {
855 s = [ match[3], match[1], match[2] ];
856 } else if ( mw.config.get( 'wgDefaultDateFormat' ) === 'dmy' ) {
857 s = [ match[3], match[2], match[1] ];
858 }
859 } else if ( ( match = s.match( ts.dateRegex[1] ) ) !== null ) {
860 s = [ match[3], '' + ts.monthNames[match[2]], match[1] ];
861 } else if ( ( match = s.match( ts.dateRegex[2] ) ) !== null ) {
862 s = [ match[3], '' + ts.monthNames[match[1]], match[2] ];
863 } else {
864 // Should never get here
865 return '99999999';
866 }
867
868 // Pad Month and Day
869 if ( s[1].length === 1 ) {
870 s[1] = '0' + s[1];
871 }
872 if ( s[2].length === 1 ) {
873 s[2] = '0' + s[2];
874 }
875
876 var y;
877 if ( ( y = parseInt( s[0], 10) ) < 100 ) {
878 // Guestimate years without centuries
879 if ( y < 30 ) {
880 s[0] = 2000 + y;
881 } else {
882 s[0] = 1900 + y;
883 }
884 }
885 while ( s[0].length < 4 ) {
886 s[0] = '0' + s[0];
887 }
888 return parseInt( s.join( '' ), 10 );
889 },
890 type: 'numeric'
891 } );
892
893 ts.addParser( {
894 id: 'time',
895 is: function ( s ) {
896 return ts.rgx.time[0].test(s);
897 },
898 format: function ( s ) {
899 return $.tablesorter.formatFloat( new Date( '2000/01/01 ' + s ).getTime() );
900 },
901 type: 'numeric'
902 } );
903
904 ts.addParser( {
905 id: 'number',
906 is: function ( s, table ) {
907 return $.tablesorter.numberRegex.test( $.trim( s ));
908 },
909 format: function ( s ) {
910 return $.tablesorter.formatDigit(s);
911 },
912 type: 'numeric'
913 } );
914
915 }( jQuery, mediaWiki ) );