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