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