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