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