a0bfd63d344a29145d50247df0078c3e493bf3e3
[lhc/web/wiklou.git] / skins / common / wikibits.js
1 // MediaWiki JavaScript support functions
2
3 var clientPC = navigator.userAgent.toLowerCase(); // Get client info
4 var is_gecko = /gecko/.test( clientPC ) &&
5 !/khtml|spoofer|netscape\/7\.0/.test(clientPC);
6 var webkit_match = clientPC.match(/applewebkit\/(\d+)/);
7 if (webkit_match) {
8 var is_safari = clientPC.indexOf('applewebkit') !== -1 &&
9 clientPC.indexOf('spoofer') === -1;
10 var is_safari_win = is_safari && clientPC.indexOf('windows') !== -1;
11 var webkit_version = parseInt(webkit_match[1]);
12 }
13 // For accesskeys; note that FF3+ is included here!
14 var is_ff2 = /firefox\/[2-9]|minefield\/3/.test( clientPC );
15 var ff2_bugs = /firefox\/2/.test( clientPC );
16 // These aren't used here, but some custom scripts rely on them
17 var is_ff2_win = is_ff2 && clientPC.indexOf('windows') !== -1;
18 var is_ff2_x11 = is_ff2 && clientPC.indexOf('x11') !== -1;
19 if (clientPC.indexOf('opera') !== -1) {
20 var is_opera = true;
21 var is_opera_preseven = window.opera && !document.childNodes;
22 var is_opera_seven = window.opera && document.childNodes;
23 var is_opera_95 = /opera\/(9\.[5-9]|[1-9][0-9])/.test( clientPC );
24 var opera6_bugs = is_opera_preseven;
25 var opera7_bugs = is_opera_seven && !is_opera_95;
26 var opera95_bugs = /opera\/(9\.5)/.test( clientPC );
27 }
28 // As recommended by <http://msdn.microsoft.com/en-us/library/ms537509.aspx>,
29 // avoiding false positives from moronic extensions that append to the IE UA
30 // string (bug 23171)
31 var ie6_bugs = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec( clientPC ) && parseFloat( RegExp.$1 ) <= 6.0 );
32
33 // Global external objects used by this script.
34 /*extern ta, stylepath, skin */
35
36 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
37 var doneOnloadHook;
38
39 if (!window.onloadFuncts) {
40 var onloadFuncts = [];
41 }
42
43 function addOnloadHook( hookFunct ) {
44 // Allows add-on scripts to add onload functions
45 if( !doneOnloadHook ) {
46 onloadFuncts[onloadFuncts.length] = hookFunct;
47 } else {
48 hookFunct(); // bug in MSIE script loading
49 }
50 }
51
52 function hookEvent( hookName, hookFunct ) {
53 addHandler( window, hookName, hookFunct );
54 }
55
56 function importScript( page ) {
57 // TODO: might want to introduce a utility function to match wfUrlencode() in PHP
58 var uri = wgScript + '?title=' +
59 encodeURIComponent(page.replace(/ /g,'_')).replace(/%2F/ig,'/').replace(/%3A/ig,':') +
60 '&action=raw&ctype=text/javascript';
61 return importScriptURI( uri );
62 }
63
64 var loadedScripts = {}; // included-scripts tracker
65 function importScriptURI( url ) {
66 if ( loadedScripts[url] ) {
67 return;
68 }
69 loadedScripts[url] = true;
70 var s = document.createElement( 'script' );
71 s.setAttribute( 'src', url );
72 s.setAttribute( 'type', 'text/javascript' );
73 document.getElementsByTagName('head')[0].appendChild( s );
74 return s;
75 }
76
77 function importStylesheet( page ) {
78 return importStylesheetURI( wgScript + '?action=raw&ctype=text/css&title=' + encodeURIComponent( page.replace(/ /g,'_') ) );
79 }
80
81 function importStylesheetURI( url, media ) {
82 var l = document.createElement( 'link' );
83 l.type = 'text/css';
84 l.rel = 'stylesheet';
85 l.href = url;
86 if( media ) {
87 l.media = media;
88 }
89 document.getElementsByTagName('head')[0].appendChild( l );
90 return l;
91 }
92
93 function appendCSS( text ) {
94 var s = document.createElement( 'style' );
95 s.type = 'text/css';
96 s.rel = 'stylesheet';
97 if ( s.styleSheet ) {
98 s.styleSheet.cssText = text; // IE
99 } else {
100 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
101 }
102 document.getElementsByTagName('head')[0].appendChild( s );
103 return s;
104 }
105
106 // Special stylesheet links for Monobook only (see bug 14717)
107 if ( typeof stylepath !== 'undefined' && skin === 'monobook' ) {
108 if ( opera6_bugs ) {
109 importStylesheetURI( stylepath + '/' + skin + '/Opera6Fixes.css' );
110 } else if ( opera7_bugs ) {
111 importStylesheetURI( stylepath + '/' + skin + '/Opera7Fixes.css' );
112 } else if ( opera95_bugs ) {
113 importStylesheetURI( stylepath + '/' + skin + '/Opera9Fixes.css' );
114 } else if ( ff2_bugs ) {
115 importStylesheetURI( stylepath + '/' + skin + '/FF2Fixes.css' );
116 }
117 }
118
119
120 if ( wgBreakFrames ) {
121 // Un-trap us from framesets
122 if ( window.top != window ) {
123 window.top.location = window.location;
124 }
125 }
126
127 function showTocToggle() {
128 if ( document.createTextNode ) {
129 // Uses DOM calls to avoid document.write + XHTML issues
130
131 var linkHolder = document.getElementById( 'toctitle' );
132 var existingLink = document.getElementById( 'togglelink' );
133 if ( !linkHolder || existingLink ) {
134 // Don't add the toggle link twice
135 return;
136 }
137
138 var outerSpan = document.createElement( 'span' );
139 outerSpan.className = 'toctoggle';
140
141 var toggleLink = document.createElement( 'a' );
142 toggleLink.id = 'togglelink';
143 toggleLink.className = 'internal';
144 toggleLink.href = '#';
145 addClickHandler( toggleLink, function( evt ) { toggleToc(); return killEvt( evt ); } );
146
147 toggleLink.appendChild( document.createTextNode( tocHideText ) );
148
149 outerSpan.appendChild( document.createTextNode( '[' ) );
150 outerSpan.appendChild( toggleLink );
151 outerSpan.appendChild( document.createTextNode( ']' ) );
152
153 linkHolder.appendChild( document.createTextNode( ' ' ) );
154 linkHolder.appendChild( outerSpan );
155
156 var cookiePos = document.cookie.indexOf( "hidetoc=" );
157 if ( cookiePos > -1 && document.cookie.charAt( cookiePos + 8 ) === 1 ) {
158 toggleToc();
159 }
160 }
161 }
162
163 function changeText( el, newText ) {
164 // Safari work around
165 if ( el.innerText ) {
166 el.innerText = newText;
167 } else if ( el.firstChild && el.firstChild.nodeValue ) {
168 el.firstChild.nodeValue = newText;
169 }
170 }
171
172 function killEvt( evt ) {
173 evt = evt || window.event || window.Event; // W3C, IE, Netscape
174 if ( typeof ( evt.preventDefault ) !== 'undefined' ) {
175 evt.preventDefault(); // Don't follow the link
176 evt.stopPropagation();
177 } else {
178 evt.cancelBubble = true; // IE
179 }
180 return false; // Don't follow the link (IE)
181 }
182
183 function toggleToc() {
184 var tocmain = document.getElementById( 'toc' );
185 var toc = document.getElementById('toc').getElementsByTagName('ul')[0];
186 var toggleLink = document.getElementById( 'togglelink' );
187
188 if ( toc && toggleLink && toc.style.display === 'none' ) {
189 changeText( toggleLink, tocHideText );
190 toc.style.display = 'block';
191 document.cookie = "hidetoc=0";
192 tocmain.className = 'toc';
193 } else {
194 changeText( toggleLink, tocShowText );
195 toc.style.display = 'none';
196 document.cookie = "hidetoc=1";
197 tocmain.className = 'toc tochidden';
198 }
199 return false;
200 }
201
202 var mwEditButtons = [];
203 var mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
204
205 function escapeQuotes( text ) {
206 var re = new RegExp( "'", "g" );
207 text = text.replace( re, "\\'" );
208 re = new RegExp( "\\n", "g" );
209 text = text.replace( re, "\\n" );
210 return escapeQuotesHTML( text );
211 }
212
213 function escapeQuotesHTML( text ) {
214 var re = new RegExp( '&', "g" );
215 text = text.replace( re, "&amp;" );
216 re = new RegExp( '"', "g" );
217 text = text.replace( re, "&quot;" );
218 re = new RegExp( '<', "g" );
219 text = text.replace( re, "&lt;" );
220 re = new RegExp( '>', "g" );
221 text = text.replace( re, "&gt;" );
222 return text;
223 }
224
225 /**
226 * Set the accesskey prefix based on browser detection.
227 */
228 var tooltipAccessKeyPrefix = 'alt-';
229 if ( is_opera ) {
230 tooltipAccessKeyPrefix = 'shift-esc-';
231 } else if ( !is_safari_win && is_safari && webkit_version > 526 ) {
232 tooltipAccessKeyPrefix = 'ctrl-alt-';
233 } else if ( !is_safari_win && ( is_safari
234 || clientPC.indexOf('mac') !== -1
235 || clientPC.indexOf('konqueror') !== -1 ) ) {
236 tooltipAccessKeyPrefix = 'ctrl-';
237 } else if ( is_ff2 ) {
238 tooltipAccessKeyPrefix = 'alt-shift-';
239 }
240 var tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/;
241
242 /**
243 * Add the appropriate prefix to the accesskey shown in the tooltip.
244 * If the nodeList parameter is given, only those nodes are updated;
245 * otherwise, all the nodes that will probably have accesskeys by
246 * default are updated.
247 *
248 * @param Array nodeList -- list of elements to update
249 */
250 function updateTooltipAccessKeys( nodeList ) {
251 if ( !nodeList ) {
252 // Rather than scan all links on the whole page, we can just scan these
253 // containers which contain the relevant links. This is really just an
254 // optimization technique.
255 var linkContainers = [
256 'column-one', // Monobook and Modern
257 'mw-head', 'mw-panel', 'p-logo' // Vector
258 ];
259 for ( var i in linkContainers ) {
260 var linkContainer = document.getElementById( linkContainers[i] );
261 if ( linkContainer ) {
262 updateTooltipAccessKeys( linkContainer.getElementsByTagName( 'a' ) );
263 }
264 }
265 // these are rare enough that no such optimization is needed
266 updateTooltipAccessKeys( document.getElementsByTagName( 'input' ) );
267 updateTooltipAccessKeys( document.getElementsByTagName( 'label' ) );
268 return;
269 }
270
271 for ( var i = 0; i < nodeList.length; i++ ) {
272 var element = nodeList[i];
273 var tip = element.getAttribute( 'title' );
274 if ( tip && tooltipAccessKeyRegexp.exec( tip ) ) {
275 tip = tip.replace(tooltipAccessKeyRegexp,
276 '[' + tooltipAccessKeyPrefix + "$5]");
277 element.setAttribute( 'title', tip );
278 }
279 }
280 }
281
282 /**
283 * Add a link to one of the portlet menus on the page, including:
284 *
285 * p-cactions: Content actions (shown as tabs above the main content in Monobook)
286 * p-personal: Personal tools (shown at the top right of the page in Monobook)
287 * p-navigation: Navigation
288 * p-tb: Toolbox
289 *
290 * This function exists for the convenience of custom JS authors. All
291 * but the first three parameters are optional, though providing at
292 * least an id and a tooltip is recommended.
293 *
294 * By default the new link will be added to the end of the list. To
295 * add the link before a given existing item, pass the DOM node of
296 * that item (easily obtained with document.getElementById()) as the
297 * nextnode parameter; to add the link _after_ an existing item, pass
298 * the node's nextSibling instead.
299 *
300 * @param String portlet -- id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
301 * @param String href -- link URL
302 * @param String text -- link text (will be automatically lowercased by CSS for p-cactions in Monobook)
303 * @param String id -- id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
304 * @param String tooltip -- text to show when hovering over the link, without accesskey suffix
305 * @param String accesskey -- accesskey to activate this link (one character, try to avoid conflicts)
306 * @param Node nextnode -- the DOM node before which the new item should be added, should be another item in the same list
307 *
308 * @return Node -- the DOM node of the new item (an LI element) or null
309 */
310 function addPortletLink( portlet, href, text, id, tooltip, accesskey, nextnode ) {
311 var root = document.getElementById( portlet );
312 if ( !root ) {
313 return;
314 }
315 var node = root.getElementsByTagName( 'ul' )[0];
316 if ( !node ) {
317 return;
318 }
319
320 // unhide portlet if it was hidden before
321 root.className = root.className.replace( /(^| )emptyPortlet( |$)/, "$2" );
322
323 var span = document.createElement( 'span' );
324 span.appendChild( document.createTextNode( text ) );
325
326 var link = document.createElement( 'a' );
327 link.appendChild( span );
328 link.href = href;
329
330 var item = document.createElement( 'li' );
331 item.appendChild( link );
332 if ( id ) {
333 item.id = id;
334 }
335
336 if ( accesskey ) {
337 link.setAttribute( 'accesskey', accesskey );
338 tooltip += ' [' + accesskey + ']';
339 }
340 if ( tooltip ) {
341 link.setAttribute( 'title', tooltip );
342 }
343 if ( accesskey && tooltip ) {
344 updateTooltipAccessKeys( new Array( link ) );
345 }
346
347 if ( nextnode && nextnode.parentNode === node ) {
348 node.insertBefore( item, nextnode );
349 } else {
350 node.appendChild( item ); // IE compatibility (?)
351 }
352
353 return item;
354 }
355
356 function getInnerText( el ) {
357 if ( typeof el === 'string' ) {
358 return el;
359 }
360 if ( typeof el === 'undefined' ) {
361 return el;
362 }
363 if ( el.textContent ) {
364 return el.textContent; // not needed but it is faster
365 }
366 if ( el.innerText ) {
367 return el.innerText; // IE doesn't have textContent
368 }
369 var str = '';
370
371 var cs = el.childNodes;
372 var l = cs.length;
373 for ( var i = 0; i < l; i++ ) {
374 switch ( cs[i].nodeType ) {
375 case 1: // ELEMENT_NODE
376 str += ts_getInnerText( cs[i] );
377 break;
378 case 3: // TEXT_NODE
379 str += cs[i].nodeValue;
380 break;
381 }
382 }
383 return str;
384 }
385
386 /* Dummy for deprecated function */
387 window.ta = [];
388 function akeytt( doId ) {
389 }
390
391 var checkboxes;
392 var lastCheckbox;
393
394 function setupCheckboxShiftClick() {
395 checkboxes = [];
396 lastCheckbox = undefined;
397 var inputs = document.getElementsByTagName( 'input' );
398 addCheckboxClickHandlers( inputs );
399 }
400
401 function addCheckboxClickHandlers( inputs, start ) {
402 if ( !start ) {
403 start = 0;
404 }
405
406 var finish = start + 250;
407 if ( finish > inputs.length ) {
408 finish = inputs.length;
409 }
410
411 for ( var i = start; i < finish; i++ ) {
412 var cb = inputs[i];
413 if ( !cb.type || cb.type.toLowerCase() !== 'checkbox' ) {
414 continue;
415 }
416 var end = checkboxes.length;
417 checkboxes[end] = cb;
418 cb.index = end;
419 addClickHandler( cb, checkboxClickHandler );
420 }
421
422 if ( finish < inputs.length ) {
423 setTimeout( function() {
424 addCheckboxClickHandlers( inputs, finish );
425 }, 200 );
426 }
427 }
428
429 function checkboxClickHandler( e ) {
430 if ( typeof e === 'undefined' ) {
431 e = window.event;
432 }
433 if ( !e.shiftKey || lastCheckbox === undefined ) {
434 lastCheckbox = this.index;
435 return true;
436 }
437 var endState = this.checked;
438 var start, finish;
439 if ( this.index < lastCheckbox ) {
440 start = this.index + 1;
441 finish = lastCheckbox;
442 } else {
443 start = lastCheckbox;
444 finish = this.index - 1;
445 }
446 for ( var i = start; i <= finish; ++i ) {
447 checkboxes[i].checked = endState;
448 if( i > start && typeof checkboxes[i].onchange === 'function' ) {
449 checkboxes[i].onchange(); // fire triggers
450 }
451 }
452 lastCheckbox = this.index;
453 return true;
454 }
455
456
457 /*
458 Written by Jonathan Snook, http://www.snook.ca/jonathan
459 Add-ons by Robert Nyman, http://www.robertnyman.com
460 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
461 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
462 */
463 function getElementsByClassName( oElm, strTagName, oClassNames ) {
464 var arrReturnElements = new Array();
465 if ( typeof( oElm.getElementsByClassName ) === 'function' ) {
466 /* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
467 var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
468 if ( strTagName === '*' ) {
469 return arrNativeReturn;
470 }
471 for ( var h = 0; h < arrNativeReturn.length; h++ ) {
472 if( arrNativeReturn[h].tagName.toLowerCase() === strTagName.toLowerCase() ) {
473 arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
474 }
475 }
476 return arrReturnElements;
477 }
478 var arrElements = ( strTagName === '*' && oElm.all ) ? oElm.all : oElm.getElementsByTagName( strTagName );
479 var arrRegExpClassNames = new Array();
480 if( typeof oClassNames === 'object' ) {
481 for( var i = 0; i < oClassNames.length; i++ ) {
482 arrRegExpClassNames[arrRegExpClassNames.length] =
483 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
484 }
485 } else {
486 arrRegExpClassNames[arrRegExpClassNames.length] =
487 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
488 }
489 var oElement;
490 var bMatchesAll;
491 for( var j = 0; j < arrElements.length; j++ ) {
492 oElement = arrElements[j];
493 bMatchesAll = true;
494 for( var k = 0; k < arrRegExpClassNames.length; k++ ) {
495 if( !arrRegExpClassNames[k].test( oElement.className ) ) {
496 bMatchesAll = false;
497 break;
498 }
499 }
500 if( bMatchesAll ) {
501 arrReturnElements[arrReturnElements.length] = oElement;
502 }
503 }
504 return ( arrReturnElements );
505 }
506
507 function redirectToFragment( fragment ) {
508 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
509 if ( match ) {
510 var webKitVersion = parseInt( match[1] );
511 if ( webKitVersion < 420 ) {
512 // Released Safari w/ WebKit 418.9.1 messes up horribly
513 // Nightlies of 420+ are ok
514 return;
515 }
516 }
517 if ( window.location.hash === '' ) {
518 window.location.hash = fragment;
519
520 // Mozilla needs to wait until after load, otherwise the window doesn't
521 // scroll. See <https://bugzilla.mozilla.org/show_bug.cgi?id=516293>.
522 // There's no obvious way to detect this programmatically, so we use
523 // version-testing. If Firefox fixes the bug, they'll jump twice, but
524 // better twice than not at all, so make the fix hit future versions as
525 // well.
526 if ( is_gecko ) {
527 addOnloadHook(function() {
528 if ( window.location.hash === fragment ) {
529 window.location.hash = fragment;
530 }
531 });
532 }
533 }
534 }
535
536 /*
537 * Table sorting script based on one (c) 1997-2006 Stuart Langridge and Joost
538 * de Valk:
539 * http://www.joostdevalk.nl/code/sortable-table/
540 * http://www.kryogenix.org/code/browser/sorttable/
541 *
542 * @todo don't break on colspans/rowspans (bug 8028)
543 * @todo language-specific digit grouping/decimals (bug 8063)
544 * @todo support all accepted date formats (bug 8226)
545 */
546
547 var ts_image_path = stylepath + '/common/images/';
548 var ts_image_up = 'sort_up.gif';
549 var ts_image_down = 'sort_down.gif';
550 var ts_image_none = 'sort_none.gif';
551 var ts_europeandate = wgContentLanguage !== 'en'; // The non-American-inclined can change to "true"
552 var ts_alternate_row_colors = false;
553 var ts_number_transform_table;
554 var ts_number_regex;
555
556 function sortables_init() {
557 var idnum = 0;
558 // Find all tables with class sortable and make them sortable
559 var tables = getElementsByClassName( document, 'table', 'sortable' );
560 for ( var ti = 0; ti < tables.length ; ti++ ) {
561 if ( !tables[ti].id ) {
562 tables[ti].setAttribute( 'id', 'sortable_table_id_' + idnum );
563 ++idnum;
564 }
565 ts_makeSortable( tables[ti] );
566 }
567 }
568
569 function ts_makeSortable( table ) {
570 var firstRow;
571 if ( table.rows && table.rows.length > 0 ) {
572 if ( table.tHead && table.tHead.rows.length > 0 ) {
573 firstRow = table.tHead.rows[table.tHead.rows.length-1];
574 } else {
575 firstRow = table.rows[0];
576 }
577 }
578 if ( !firstRow ) {
579 return;
580 }
581
582 // We have a first row: assume it's the header, and make its contents clickable links
583 for ( var i = 0; i < firstRow.cells.length; i++ ) {
584 var cell = firstRow.cells[i];
585 if ( (' ' + cell.className + ' ').indexOf(' unsortable ') === -1 ) {
586 cell.innerHTML += '<a href="#" class="sortheader" '
587 + 'onclick="ts_resortTable(this);return false;">'
588 + '<span class="sortarrow">'
589 + '<img src="'
590 + ts_image_path
591 + ts_image_none
592 + '" alt="&darr;"/></span></a>';
593 }
594 }
595 if ( ts_alternate_row_colors ) {
596 ts_alternate( table );
597 }
598 }
599
600 function ts_getInnerText( el ) {
601 return getInnerText( el );
602 }
603
604 function ts_resortTable( lnk ) {
605 // get the span
606 var span = lnk.getElementsByTagName('span')[0];
607
608 var td = lnk.parentNode;
609 var tr = td.parentNode;
610 var column = td.cellIndex;
611
612 var table = tr.parentNode;
613 while ( table && !( table.tagName && table.tagName.toLowerCase() === 'table' ) ) {
614 table = table.parentNode;
615 }
616 if ( !table ) {
617 return;
618 }
619
620 if ( table.rows.length <= 1 ) {
621 return;
622 }
623
624 // Generate the number transform table if it's not done already
625 if ( ts_number_transform_table === undefined ) {
626 ts_initTransformTable();
627 }
628
629 // Work out a type for the column
630 // Skip the first row if that's where the headings are
631 var rowStart = ( table.tHead && table.tHead.rows.length > 0 ? 0 : 1 );
632 var bodyRows = 0;
633 if (rowStart === 0 && table.tBodies) {
634 for (var i=0; i < table.tBodies.length; i++ ) {
635 bodyRows += table.tBodies[i].rows.length;
636 }
637 if (bodyRows < table.rows.length)
638 rowStart = 1;
639 }
640
641 var itm = '';
642 for ( var i = rowStart; i < table.rows.length; i++ ) {
643 if ( table.rows[i].cells.length > column ) {
644 itm = ts_getInnerText(table.rows[i].cells[column]);
645 itm = itm.replace(/^[\s\xa0]+/, '').replace(/[\s\xa0]+$/, '');
646 if ( itm !== '' ) {
647 break;
648 }
649 }
650 }
651
652 // TODO: bug 8226, localised date formats
653 var sortfn = ts_sort_generic;
654 var preprocessor = ts_toLowerCase;
655 if ( /^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test( itm ) ) {
656 preprocessor = ts_dateToSortKey;
657 } else if ( /^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test( itm ) ) {
658 preprocessor = ts_dateToSortKey;
659 } else if ( /^\d\d[\/.-]\d\d[\/.-]\d\d$/.test( itm ) ) {
660 preprocessor = ts_dateToSortKey;
661 // (minus sign)([pound dollar euro yen currency]|cents)
662 } else if ( /(^([-\u2212] *)?[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test( itm ) ) {
663 preprocessor = ts_currencyToSortKey;
664 } else if ( ts_number_regex.test( itm ) ) {
665 preprocessor = ts_parseFloat;
666 }
667
668 var reverse = ( span.getAttribute( 'sortdir' ) === 'down' );
669
670 var newRows = new Array();
671 var staticRows = new Array();
672 for ( var j = rowStart; j < table.rows.length; j++ ) {
673 var row = table.rows[j];
674 if( (' ' + row.className + ' ').indexOf(' unsortable ') < 0 ) {
675 var keyText = ts_getInnerText( row.cells[column] );
676 if( keyText === undefined ) {
677 keyText = '';
678 }
679 var oldIndex = ( reverse ? -j : j );
680 var preprocessed = preprocessor( keyText.replace(/^[\s\xa0]+/, '').replace(/[\s\xa0]+$/, '') );
681
682 newRows[newRows.length] = new Array( row, preprocessed, oldIndex );
683 } else {
684 staticRows[staticRows.length] = new Array( row, false, j-rowStart );
685 }
686 }
687
688 newRows.sort( sortfn );
689
690 var arrowHTML;
691 if ( reverse ) {
692 arrowHTML = '<img src="' + ts_image_path + ts_image_down + '" alt="&darr;"/>';
693 newRows.reverse();
694 span.setAttribute( 'sortdir', 'up' );
695 } else {
696 arrowHTML = '<img src="' + ts_image_path + ts_image_up + '" alt="&uarr;"/>';
697 span.setAttribute( 'sortdir', 'down' );
698 }
699
700 for ( var i = 0; i < staticRows.length; i++ ) {
701 var row = staticRows[i];
702 newRows.splice( row[2], 0, row );
703 }
704
705 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
706 // don't do sortbottom rows
707 for ( var i = 0; i < newRows.length; i++ ) {
708 if ( ( ' ' + newRows[i][0].className + ' ').indexOf(' sortbottom ') === -1 ) {
709 table.tBodies[0].appendChild( newRows[i][0] );
710 }
711 }
712 // do sortbottom rows only
713 for ( var i = 0; i < newRows.length; i++ ) {
714 if ( ( ' ' + newRows[i][0].className + ' ').indexOf(' sortbottom ') !== -1 ) {
715 table.tBodies[0].appendChild( newRows[i][0] );
716 }
717 }
718
719 // Delete any other arrows there may be showing
720 var spans = getElementsByClassName( tr, 'span', 'sortarrow' );
721 for ( var i = 0; i < spans.length; i++ ) {
722 spans[i].innerHTML = '<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/>';
723 }
724 span.innerHTML = arrowHTML;
725
726 if ( ts_alternate_row_colors ) {
727 ts_alternate( table );
728 }
729 }
730
731 function ts_initTransformTable() {
732 if ( typeof wgSeparatorTransformTable === 'undefined'
733 || ( wgSeparatorTransformTable[0] === '' && wgDigitTransformTable[2] === '' ) )
734 {
735 var digitClass = "[0-9,.]";
736 ts_number_transform_table = false;
737 } else {
738 ts_number_transform_table = {};
739 // Unpack the transform table
740 // Separators
741 var ascii = wgSeparatorTransformTable[0].split("\t");
742 var localised = wgSeparatorTransformTable[1].split("\t");
743 for ( var i = 0; i < ascii.length; i++ ) {
744 ts_number_transform_table[localised[i]] = ascii[i];
745 }
746 // Digits
747 ascii = wgDigitTransformTable[0].split("\t");
748 localised = wgDigitTransformTable[1].split("\t");
749 for ( var i = 0; i < ascii.length; i++ ) {
750 ts_number_transform_table[localised[i]] = ascii[i];
751 }
752
753 // Construct regex for number identification
754 var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\\.'];
755 var maxDigitLength = 1;
756 for ( var digit in ts_number_transform_table ) {
757 // Escape regex metacharacters
758 digits.push(
759 digit.replace( /[\\\\$\*\+\?\.\(\)\|\{\}\[\]\-]/,
760 function( s ) { return '\\' + s; } )
761 );
762 if ( digit.length > maxDigitLength ) {
763 maxDigitLength = digit.length;
764 }
765 }
766 if ( maxDigitLength > 1 ) {
767 var digitClass = '[' + digits.join( '', digits ) + ']';
768 } else {
769 var digitClass = '(' + digits.join( '|', digits ) + ')';
770 }
771 }
772
773 // We allow a trailing percent sign, which we just strip. This works fine
774 // if percents and regular numbers aren't being mixed.
775 ts_number_regex = new RegExp(
776 "^(" +
777 "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
778 "|" +
779 "[-+\u2212]?" + digitClass + "+%?" + // Generic localised
780 ")$", "i"
781 );
782 }
783
784 function ts_toLowerCase( s ) {
785 return s.toLowerCase();
786 }
787
788 function ts_dateToSortKey( date ) {
789 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
790 if ( date.length === 11 ) {
791 switch ( date.substr( 3, 3 ).toLowerCase() ) {
792 case 'jan':
793 var month = '01';
794 break;
795 case 'feb':
796 var month = '02';
797 break;
798 case 'mar':
799 var month = '03';
800 break;
801 case 'apr':
802 var month = '04';
803 break;
804 case 'may':
805 var month = '05';
806 break;
807 case 'jun':
808 var month = '06';
809 break;
810 case 'jul':
811 var month = '07';
812 break;
813 case 'aug':
814 var month = '08';
815 break;
816 case 'sep':
817 var month = '09';
818 break;
819 case 'oct':
820 var month = '10';
821 break;
822 case 'nov':
823 var month = '11';
824 break;
825 case 'dec':
826 var month = '12';
827 break;
828 // default: var month = '00';
829 }
830 return date.substr( 7, 4 ) + month + date.substr( 0, 2 );
831 } else if ( date.length === 10 ) {
832 if ( ts_europeandate === false ) {
833 return date.substr( 6, 4 ) + date.substr( 0, 2 ) + date.substr( 3, 2 );
834 } else {
835 return date.substr( 6, 4 ) + date.substr( 3, 2 ) + date.substr( 0, 2 );
836 }
837 } else if ( date.length === 8 ) {
838 var yr = date.substr( 6, 2 );
839 if ( parseInt( yr ) < 50 ) {
840 yr = '20' + yr;
841 } else {
842 yr = '19' + yr;
843 }
844 if ( ts_europeandate === true ) {
845 return yr + date.substr( 3, 2 ) + date.substr( 0, 2 );
846 } else {
847 return yr + date.substr( 0, 2 ) + date.substr( 3, 2 );
848 }
849 }
850 return '00000000';
851 }
852
853 function ts_parseFloat( s ) {
854 if ( !s ) {
855 return 0;
856 }
857 if ( ts_number_transform_table !== false ) {
858 var newNum = '', c;
859
860 for ( var p = 0; p < s.length; p++ ) {
861 c = s.charAt( p );
862 if ( c in ts_number_transform_table ) {
863 newNum += ts_number_transform_table[c];
864 } else {
865 newNum += c;
866 }
867 }
868 s = newNum;
869 }
870 var num = parseFloat( s.replace(/[, ]/g, '').replace("\u2212", '-') );
871 return ( isNaN( num ) ? -Infinity : num );
872 }
873
874 function ts_currencyToSortKey( s ) {
875 return ts_parseFloat(s.replace(/[^-\u22120-9.,]/g,''));
876 }
877
878 function ts_sort_generic( a, b ) {
879 return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2];
880 }
881
882 function ts_alternate( table ) {
883 // Take object table and get all it's tbodies.
884 var tableBodies = table.getElementsByTagName( 'tbody' );
885 // Loop through these tbodies
886 for ( var i = 0; i < tableBodies.length; i++ ) {
887 // Take the tbody, and get all it's rows
888 var tableRows = tableBodies[i].getElementsByTagName( 'tr' );
889 // Loop through these rows
890 // Start at 1 because we want to leave the heading row untouched
891 for ( var j = 0; j < tableRows.length; j++ ) {
892 // Check if j is even, and apply classes for both possible results
893 var oldClasses = tableRows[j].className.split(' ');
894 var newClassName = '';
895 for ( var k = 0; k < oldClasses.length; k++ ) {
896 if ( oldClasses[k] !== '' && oldClasses[k] !== 'even' && oldClasses[k] !== 'odd' ) {
897 newClassName += oldClasses[k] + ' ';
898 }
899 }
900 tableRows[j].className = newClassName + ( j % 2 === 0 ? 'even' : 'odd' );
901 }
902 }
903 }
904
905 /*
906 * End of table sorting code
907 */
908
909
910 /**
911 * Add a cute little box at the top of the screen to inform the user of
912 * something, replacing any preexisting message.
913 *
914 * @param String -or- Dom Object message HTML to be put inside the right div
915 * @param String className Used in adding a class; should be different for each
916 * call to allow CSS/JS to hide different boxes. null = no class used.
917 * @return Boolean True on success, false on failure
918 */
919 function jsMsg( message, className ) {
920 if ( !document.getElementById ) {
921 return false;
922 }
923 // We special-case skin structures provided by the software. Skins that
924 // choose to abandon or significantly modify our formatting can just define
925 // an mw-js-message div to start with.
926 var messageDiv = document.getElementById( 'mw-js-message' );
927 if ( !messageDiv ) {
928 messageDiv = document.createElement( 'div' );
929 if ( document.getElementById( 'column-content' )
930 && document.getElementById( 'content' ) ) {
931 // MonoBook, presumably
932 document.getElementById( 'content' ).insertBefore(
933 messageDiv,
934 document.getElementById( 'content' ).firstChild
935 );
936 } else if ( document.getElementById( 'content' )
937 && document.getElementById( 'article' ) ) {
938 // Non-Monobook but still recognizable (old-style)
939 document.getElementById( 'article').insertBefore(
940 messageDiv,
941 document.getElementById( 'article' ).firstChild
942 );
943 } else {
944 return false;
945 }
946 }
947
948 messageDiv.setAttribute( 'id', 'mw-js-message' );
949 messageDiv.style.display = 'block';
950 if( className ) {
951 messageDiv.setAttribute( 'class', 'mw-js-message-' + className );
952 }
953
954 if ( typeof message === 'object' ) {
955 while ( messageDiv.hasChildNodes() ) { // Remove old content
956 messageDiv.removeChild( messageDiv.firstChild );
957 }
958 messageDiv.appendChild( message ); // Append new content
959 } else {
960 messageDiv.innerHTML = message;
961 }
962 return true;
963 }
964
965 /**
966 * Inject a cute little progress spinner after the specified element
967 *
968 * @param element Element to inject after
969 * @param id Identifier string (for use with removeSpinner(), below)
970 */
971 function injectSpinner( element, id ) {
972 var spinner = document.createElement( 'img' );
973 spinner.id = 'mw-spinner-' + id;
974 spinner.src = stylepath + '/common/images/spinner.gif';
975 spinner.alt = spinner.title = '...';
976 if( element.nextSibling ) {
977 element.parentNode.insertBefore( spinner, element.nextSibling );
978 } else {
979 element.parentNode.appendChild( spinner );
980 }
981 }
982
983 /**
984 * Remove a progress spinner added with injectSpinner()
985 *
986 * @param id Identifier string
987 */
988 function removeSpinner( id ) {
989 var spinner = document.getElementById( 'mw-spinner-' + id );
990 if( spinner ) {
991 spinner.parentNode.removeChild( spinner );
992 }
993 }
994
995 function runOnloadHook() {
996 // don't run anything below this for non-dom browsers
997 if ( doneOnloadHook || !( document.getElementById && document.getElementsByTagName ) ) {
998 return;
999 }
1000
1001 // set this before running any hooks, since any errors below
1002 // might cause the function to terminate prematurely
1003 doneOnloadHook = true;
1004
1005 updateTooltipAccessKeys( null );
1006 setupCheckboxShiftClick();
1007 sortables_init();
1008
1009 // Run any added-on functions
1010 for ( var i = 0; i < onloadFuncts.length; i++ ) {
1011 onloadFuncts[i]();
1012 }
1013 }
1014
1015 /**
1016 * Add an event handler to an element
1017 *
1018 * @param Element element Element to add handler to
1019 * @param String attach Event to attach to
1020 * @param callable handler Event handler callback
1021 */
1022 function addHandler( element, attach, handler ) {
1023 if( window.addEventListener ) {
1024 element.addEventListener( attach, handler, false );
1025 } else if( window.attachEvent ) {
1026 element.attachEvent( 'on' + attach, handler );
1027 }
1028 }
1029
1030 /**
1031 * Add a click event handler to an element
1032 *
1033 * @param Element element Element to add handler to
1034 * @param callable handler Event handler callback
1035 */
1036 function addClickHandler( element, handler ) {
1037 addHandler( element, 'click', handler );
1038 }
1039
1040 /**
1041 * Removes an event handler from an element
1042 *
1043 * @param Element element Element to remove handler from
1044 * @param String remove Event to remove
1045 * @param callable handler Event handler callback to remove
1046 */
1047 function removeHandler( element, remove, handler ) {
1048 if( window.removeEventListener ) {
1049 element.removeEventListener( remove, handler, false );
1050 } else if( window.detachEvent ) {
1051 element.detachEvent( 'on' + remove, handler );
1052 }
1053 }
1054 // note: all skins should call runOnloadHook() at the end of html output,
1055 // so the below should be redundant. It's there just in case.
1056 hookEvent( 'load', runOnloadHook );
1057
1058 if ( ie6_bugs ) {
1059 importScriptURI( stylepath + '/common/IEFixes.js' );
1060 }
1061
1062 // For future use.
1063 mw = {};
1064
1065