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