Typofix, ping r112427
[mediawiki.git] / skins / common / wikibits.js
blob8f47499c484eae5e5c743732acf4a99a32f07f07
1 /**
2  * MediaWiki legacy wikibits
3  */
4 (function(){
6 window.clientPC = navigator.userAgent.toLowerCase(); // Get client info
7 window.is_gecko = /gecko/.test( clientPC ) &&
8         !/khtml|spoofer|netscape\/7\.0/.test(clientPC);
10 window.is_safari = window.is_safari_win = window.webkit_version =
11         window.is_chrome = window.is_chrome_mac = false;
12 window.webkit_match = clientPC.match(/applewebkit\/(\d+)/);
13 if (webkit_match) {
14         window.is_safari = clientPC.indexOf('applewebkit') != -1 &&
15                 clientPC.indexOf('spoofer') == -1;
16         window.is_safari_win = is_safari && clientPC.indexOf('windows') != -1;
17         window.webkit_version = parseInt(webkit_match[1]);
18         // Tests for chrome here, to avoid breaking old scripts safari left alone
19         // This is here for accesskeys
20         window.is_chrome = clientPC.indexOf('chrome') !== -1 &&
21                 clientPC.indexOf('spoofer') === -1;
22         window.is_chrome_mac = is_chrome && clientPC.indexOf('mac') !== -1
25 // For accesskeys; note that FF3+ is included here!
26 window.is_ff2 = /firefox\/[2-9]|minefield\/3/.test( clientPC );
27 window.ff2_bugs = /firefox\/2/.test( clientPC );
28 // These aren't used here, but some custom scripts rely on them
29 window.is_ff2_win = is_ff2 && clientPC.indexOf('windows') != -1;
30 window.is_ff2_x11 = is_ff2 && clientPC.indexOf('x11') != -1;
32 window.is_opera = window.is_opera_preseven = window.is_opera_95 =
33         window.opera6_bugs = window.opera7_bugs = window.opera95_bugs = false;
34 if (clientPC.indexOf('opera') != -1) {
35         window.is_opera = true;
36         window.is_opera_preseven = window.opera && !document.childNodes;
37         window.is_opera_seven = window.opera && document.childNodes;
38         window.is_opera_95 = /opera\/(9\.[5-9]|[1-9][0-9])/.test( clientPC );
39         window.opera6_bugs = is_opera_preseven;
40         window.opera7_bugs = is_opera_seven && !is_opera_95;
41         window.opera95_bugs = /opera\/(9\.5)/.test( clientPC );
43 // As recommended by <http://msdn.microsoft.com/en-us/library/ms537509.aspx>,
44 // avoiding false positives from moronic extensions that append to the IE UA
45 // string (bug 23171)
46 window.ie6_bugs = false;
47 if ( /msie ([0-9]{1,}[\.0-9]{0,})/.exec( clientPC ) != null
48 && parseFloat( RegExp.$1 ) <= 6.0 ) {
49         ie6_bugs = true;
52 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
53 window.doneOnloadHook = undefined;
55 if (!window.onloadFuncts) {
56         window.onloadFuncts = [];
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         }
68 window.importScript = function( page ) {
69         var uri = mw.config.get( 'wgScript' ) + '?title=' +
70                 mw.util.wikiUrlencode( page ) +
71                 '&action=raw&ctype=text/javascript';
72         return importScriptURI( uri );
75 window.loadedScripts = {}; // included-scripts tracker
76 window.importScriptURI = function( url ) {
77         if ( loadedScripts[url] ) {
78                 return null;
79         }
80         loadedScripts[url] = true;
81         var s = document.createElement( 'script' );
82         s.setAttribute( 'src', url );
83         s.setAttribute( 'type', 'text/javascript' );
84         document.getElementsByTagName('head')[0].appendChild( s );
85         return s;
88 window.importStylesheet = function( page ) {
89         return importStylesheetURI( mw.config.get( 'wgScript' ) + '?action=raw&ctype=text/css&title=' + mw.util.wikiUrlencode( page ) );
92 window.importStylesheetURI = function( url, media ) {
93         var l = document.createElement( 'link' );
94         l.type = 'text/css';
95         l.rel = 'stylesheet';
96         l.href = url;
97         if( media ) {
98                 l.media = media;
99         }
100         document.getElementsByTagName('head')[0].appendChild( l );
101         return l;
104 window.appendCSS = function( text ) {
105         var s = document.createElement( 'style' );
106         s.type = 'text/css';
107         s.rel = 'stylesheet';
108         if ( s.styleSheet ) {
109                 s.styleSheet.cssText = text; // IE
110         } else {
111                 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
112         }
113         document.getElementsByTagName('head')[0].appendChild( s );
114         return s;
117 // Special stylesheet links for Monobook only (see bug 14717)
118 var skinpath = mw.config.get( 'stylepath' ) + '/' + mw.config.get( 'skin' );
119 if ( mw.config.get( 'skin' ) === 'monobook' ) {
120         if ( opera6_bugs ) {
121                 importStylesheetURI( skinpath + '/Opera6Fixes.css' );
122         } else if ( opera7_bugs ) {
123                 importStylesheetURI( skinpath + '/Opera7Fixes.css' );
124         } else if ( opera95_bugs ) {
125                 importStylesheetURI( skinpath + '/Opera9Fixes.css' );
126         } else if ( ff2_bugs ) {
127                 importStylesheetURI( skinpath + '/FF2Fixes.css' );
128         }
131 if ( mw.config.get( 'wgBreakFrames' ) ) {
132         // Un-trap us from framesets
133         if ( window.top != window ) {
134                 window.top.location = window.location;
135         }
138 window.changeText = function( el, newText ) {
139         // Safari work around
140         if ( el.innerText ) {
141                 el.innerText = newText;
142         } else if ( el.firstChild && el.firstChild.nodeValue ) {
143                 el.firstChild.nodeValue = newText;
144         }
147 window.killEvt = function( evt ) {
148         evt = evt || window.event || window.Event; // W3C, IE, Netscape
149         if ( typeof ( evt.preventDefault ) != 'undefined' ) {
150                 evt.preventDefault(); // Don't follow the link
151                 evt.stopPropagation();
152         } else {
153                 evt.cancelBubble = true; // IE
154         }
155         return false; // Don't follow the link (IE)
158 window.mwEditButtons = [];
159 window.mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
161 window.escapeQuotes = function( text ) {
162         var re = new RegExp( "'", "g" );
163         text = text.replace( re, "\\'" );
164         re = new RegExp( "\\n", "g" );
165         text = text.replace( re, "\\n" );
166         return escapeQuotesHTML( text );
169 window.escapeQuotesHTML = function( text ) {
170         var re = new RegExp( '&', "g" );
171         text = text.replace( re, "&amp;" );
172         re = new RegExp( '"', "g" );
173         text = text.replace( re, "&quot;" );
174         re = new RegExp( '<', "g" );
175         text = text.replace( re, "&lt;" );
176         re = new RegExp( '>', "g" );
177         text = text.replace( re, "&gt;" );
178         return text;
182  * Set the accesskey prefix based on browser detection.
183  */
184 window.tooltipAccessKeyPrefix = 'alt-';
185 if ( is_opera ) {
186         tooltipAccessKeyPrefix = 'shift-esc-';
187 } else if ( is_chrome ) {
188         tooltipAccessKeyPrefix = is_chrome_mac ? 'ctrl-option-' : 'alt-';
189 } else if ( !is_safari_win && is_safari && webkit_version > 526 ) {
190         tooltipAccessKeyPrefix = 'ctrl-alt-';
191 } else if ( !is_safari_win && ( is_safari
192                 || clientPC.indexOf('mac') != -1
193                 || clientPC.indexOf('konqueror') != -1 ) ) {
194         tooltipAccessKeyPrefix = 'ctrl-';
195 } else if ( is_ff2 ) {
196         tooltipAccessKeyPrefix = 'alt-shift-';
198 window.tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/;
201  * Add the appropriate prefix to the accesskey shown in the tooltip.
202  * If the nodeList parameter is given, only those nodes are updated;
203  * otherwise, all the nodes that will probably have accesskeys by
204  * default are updated.
206  * @param nodeList Array list of elements to update
207  */
208 window.updateTooltipAccessKeys = function( nodeList ) {
209         if ( !nodeList ) {
210                 // Rather than scan all links on the whole page, we can just scan these
211                 // containers which contain the relevant links. This is really just an
212                 // optimization technique.
213                 var linkContainers = [
214                         'column-one', // Monobook and Modern
215                         'mw-head', 'mw-panel', 'p-logo' // Vector
216                 ];
217                 for ( var i in linkContainers ) {
218                         var linkContainer = document.getElementById( linkContainers[i] );
219                         if ( linkContainer ) {
220                                 updateTooltipAccessKeys( linkContainer.getElementsByTagName( 'a' ) );
221                         }
222                 }
223                 // these are rare enough that no such optimization is needed
224                 updateTooltipAccessKeys( document.getElementsByTagName( 'input' ) );
225                 updateTooltipAccessKeys( document.getElementsByTagName( 'label' ) );
226                 return;
227         }
229         for ( var i = 0; i < nodeList.length; i++ ) {
230                 var element = nodeList[i];
231                 var tip = element.getAttribute( 'title' );
232                 if ( tip && tooltipAccessKeyRegexp.exec( tip ) ) {
233                         tip = tip.replace(tooltipAccessKeyRegexp,
234                                           '[' + tooltipAccessKeyPrefix + "$5]");
235                         element.setAttribute( 'title', tip );
236                 }
237         }
241  * Add a link to one of the portlet menus on the page, including:
243  * p-cactions: Content actions (shown as tabs above the main content in Monobook)
244  * p-personal: Personal tools (shown at the top right of the page in Monobook)
245  * p-navigation: Navigation
246  * p-tb: Toolbox
248  * This function exists for the convenience of custom JS authors.  All
249  * but the first three parameters are optional, though providing at
250  * least an id and a tooltip is recommended.
252  * By default the new link will be added to the end of the list.  To
253  * add the link before a given existing item, pass the DOM node of
254  * that item (easily obtained with document.getElementById()) as the
255  * nextnode parameter; to add the link _after_ an existing item, pass
256  * the node's nextSibling instead.
258  * @param portlet String id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
259  * @param href String link URL
260  * @param text String link text (will be automatically lowercased by CSS for p-cactions in Monobook)
261  * @param id String id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
262  * @param tooltip String text to show when hovering over the link, without accesskey suffix
263  * @param accesskey String accesskey to activate this link (one character, try to avoid conflicts)
264  * @param nextnode Node the DOM node before which the new item should be added, should be another item in the same list
266  * @return Node -- the DOM node of the new item (an LI element) or null
267  */
268 window.addPortletLink = function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
269         var root = document.getElementById( portlet );
270         if ( !root ) {
271                 return null;
272         }
273         var uls = root.getElementsByTagName( 'ul' );
274         var node;
275         if ( uls.length > 0 ) {
276                 node = uls[0];
277         } else {
278                 node = document.createElement( 'ul' );
279                 var lastElementChild = null;
280                 for ( var i = 0; i < root.childNodes.length; ++i ) { /* get root.lastElementChild */
281                         if ( root.childNodes[i].nodeType == 1 ) {
282                                 lastElementChild = root.childNodes[i];
283                         }
284                 }
285                 if ( lastElementChild && lastElementChild.nodeName.match( /div/i ) ) {
286                         /* Insert into the menu divs */
287                         lastElementChild.appendChild( node );
288                 } else {
289                         root.appendChild( node );
290                 }
291         }
292         if ( !node ) {
293                 return null;
294         }
296         // unhide portlet if it was hidden before
297         root.className = root.className.replace( /(^| )emptyPortlet( |$)/, "$2" );
299         var link = document.createElement( 'a' );
300         link.appendChild( document.createTextNode( text ) );
301         link.href = href;
303         // Wrap in a span - make it work with vector tabs and has no effect on any other portlets
304         var span = document.createElement( 'span' );
305         span.appendChild( link );
307         var item = document.createElement( 'li' );
308         item.appendChild( span );
309         if ( id ) {
310                 item.id = id;
311         }
313         if ( accesskey ) {
314                 link.setAttribute( 'accesskey', accesskey );
315                 tooltip += ' [' + accesskey + ']';
316         }
317         if ( tooltip ) {
318                 link.setAttribute( 'title', tooltip );
319         }
320         if ( accesskey && tooltip ) {
321                 updateTooltipAccessKeys( [link] );
322         }
324         if ( nextnode && nextnode.parentNode == node ) {
325                 node.insertBefore( item, nextnode );
326         } else {
327                 node.appendChild( item );  // IE compatibility (?)
328         }
330         return item;
333 window.getInnerText = function( el ) {
334         if ( typeof el == 'string' ) {
335                 return el;
336         }
337         if ( typeof el == 'undefined' ) {
338                 return el;
339         }
340         // Custom sort value through 'data-sort-value' attribute
341         // (no need to prepend hidden text to change sort value)
342         if ( el.nodeType && el.getAttribute( 'data-sort-value' ) !== null ) {
343                 // Make sure it's a valid DOM element (.nodeType) and that the attribute is set (!null)
344                 return el.getAttribute( 'data-sort-value' );
345         }
346         if ( el.textContent ) {
347                 return el.textContent; // not needed but it is faster
348         }
349         if ( el.innerText ) {
350                 return el.innerText; // IE doesn't have textContent
351         }
352         var str = '';
354         var cs = el.childNodes;
355         var l = cs.length;
356         for ( var i = 0; i < l; i++ ) {
357                 switch ( cs[i].nodeType ) {
358                         case 1: // ELEMENT_NODE
359                                 str += getInnerText( cs[i] );
360                                 break;
361                         case 3: // TEXT_NODE
362                                 str += cs[i].nodeValue;
363                                 break;
364                 }
365         }
366         return str;
369 window.checkboxes = undefined;
370 window.lastCheckbox = undefined;
372 window.setupCheckboxShiftClick = function() {
373         checkboxes = [];
374         lastCheckbox = null;
375         var inputs = document.getElementsByTagName( 'input' );
376         addCheckboxClickHandlers( inputs );
379 window.addCheckboxClickHandlers = function( inputs, start ) {
380         if ( !start ) {
381                 start = 0;
382         }
384         var finish = start + 250;
385         if ( finish > inputs.length ) {
386                 finish = inputs.length;
387         }
389         for ( var i = start; i < finish; i++ ) {
390                 var cb = inputs[i];
391                 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' || ( ' ' + cb.className + ' ' ).indexOf( ' noshiftselect ' )  != -1 ) {
392                         continue;
393                 }
394                 var end = checkboxes.length;
395                 checkboxes[end] = cb;
396                 cb.index = end;
397                 addClickHandler( cb, checkboxClickHandler );
398         }
400         if ( finish < inputs.length ) {
401                 setTimeout( function() {
402                         addCheckboxClickHandlers( inputs, finish );
403                 }, 200 );
404         }
407 window.checkboxClickHandler = function( e ) {
408         if ( typeof e == 'undefined' ) {
409                 e = window.event;
410         }
411         if ( !e.shiftKey || lastCheckbox === null ) {
412                 lastCheckbox = this.index;
413                 return true;
414         }
415         var endState = this.checked;
416         var start, finish;
417         if ( this.index < lastCheckbox ) {
418                 start = this.index + 1;
419                 finish = lastCheckbox;
420         } else {
421                 start = lastCheckbox;
422                 finish = this.index - 1;
423         }
424         for ( var i = start; i <= finish; ++i ) {
425                 checkboxes[i].checked = endState;
426                 if( i > start && typeof checkboxes[i].onchange == 'function' ) {
427                         checkboxes[i].onchange(); // fire triggers
428                 }
429         }
430         lastCheckbox = this.index;
431         return true;
436         Written by Jonathan Snook, http://www.snook.ca/jonathan
437         Add-ons by Robert Nyman, http://www.robertnyman.com
438         Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
439         From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
441 window.getElementsByClassName = function( oElm, strTagName, oClassNames ) {
442         var arrReturnElements = [];
443         if ( typeof( oElm.getElementsByClassName ) == 'function' ) {
444                 /* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
445                 var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
446                 if ( strTagName == '*' ) {
447                         return arrNativeReturn;
448                 }
449                 for ( var h = 0; h < arrNativeReturn.length; h++ ) {
450                         if( arrNativeReturn[h].tagName.toLowerCase() == strTagName.toLowerCase() ) {
451                                 arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
452                         }
453                 }
454                 return arrReturnElements;
455         }
456         var arrElements = ( strTagName == '*' && oElm.all ) ? oElm.all : oElm.getElementsByTagName( strTagName );
457         var arrRegExpClassNames = [];
458         if( typeof oClassNames == 'object' ) {
459                 for( var i = 0; i < oClassNames.length; i++ ) {
460                         arrRegExpClassNames[arrRegExpClassNames.length] =
461                                 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
462                 }
463         } else {
464                 arrRegExpClassNames[arrRegExpClassNames.length] =
465                         new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
466         }
467         var oElement;
468         var bMatchesAll;
469         for( var j = 0; j < arrElements.length; j++ ) {
470                 oElement = arrElements[j];
471                 bMatchesAll = true;
472                 for( var k = 0; k < arrRegExpClassNames.length; k++ ) {
473                         if( !arrRegExpClassNames[k].test( oElement.className ) ) {
474                                 bMatchesAll = false;
475                                 break;
476                         }
477                 }
478                 if( bMatchesAll ) {
479                         arrReturnElements[arrReturnElements.length] = oElement;
480                 }
481         }
482         return ( arrReturnElements );
485 window.redirectToFragment = function( fragment ) {
486         var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
487         if ( match ) {
488                 var webKitVersion = parseInt( match[1] );
489                 if ( webKitVersion < 420 ) {
490                         // Released Safari w/ WebKit 418.9.1 messes up horribly
491                         // Nightlies of 420+ are ok
492                         return;
493                 }
494         }
495         if ( window.location.hash == '' ) {
496                 window.location.hash = fragment;
498                 // Mozilla needs to wait until after load, otherwise the window doesn't
499                 // scroll.  See <https://bugzilla.mozilla.org/show_bug.cgi?id=516293>.
500                 // There's no obvious way to detect this programmatically, so we use
501                 // version-testing.  If Firefox fixes the bug, they'll jump twice, but
502                 // better twice than not at all, so make the fix hit future versions as
503                 // well.
504                 if ( is_gecko ) {
505                         addOnloadHook(function() {
506                                 if ( window.location.hash == fragment ) {
507                                         window.location.hash = fragment;
508                                 }
509                         });
510                 }
511         }
515  * Add a cute little box at the top of the screen to inform the user of
516  * something, replacing any preexisting message.
518  * @param message String -or- Dom Object  HTML to be put inside the right div
519  * @param className String   Used in adding a class; should be different for each
520  *   call to allow CSS/JS to hide different boxes.  null = no class used.
521  * @return Boolean       True on success, false on failure
522  */
523 window.jsMsg = function( message, className ) {
524         if ( !document.getElementById ) {
525                 return false;
526         }
527         // We special-case skin structures provided by the software.  Skins that
528         // choose to abandon or significantly modify our formatting can just define
529         // an mw-js-message div to start with.
530         var messageDiv = document.getElementById( 'mw-js-message' );
531         if ( !messageDiv ) {
532                 messageDiv = document.createElement( 'div' );
533                 if ( document.getElementById( 'column-content' )
534                 && document.getElementById( 'content' ) ) {
535                         // MonoBook, presumably
536                         document.getElementById( 'content' ).insertBefore(
537                                 messageDiv,
538                                 document.getElementById( 'content' ).firstChild
539                         );
540                 } else if ( document.getElementById( 'content' )
541                 && document.getElementById( 'article' ) ) {
542                         // Non-Monobook but still recognizable (old-style)
543                         document.getElementById( 'article').insertBefore(
544                                 messageDiv,
545                                 document.getElementById( 'article' ).firstChild
546                         );
547                 } else {
548                         return false;
549                 }
550         }
552         messageDiv.setAttribute( 'id', 'mw-js-message' );
553         messageDiv.style.display = 'block';
554         if( className ) {
555                 messageDiv.setAttribute( 'class', 'mw-js-message-' + className );
556         }
558         if ( typeof message === 'object' ) {
559                 while ( messageDiv.hasChildNodes() ) { // Remove old content
560                         messageDiv.removeChild( messageDiv.firstChild );
561                 }
562                 messageDiv.appendChild( message ); // Append new content
563         } else {
564                 messageDiv.innerHTML = message;
565         }
566         return true;
570  * Inject a cute little progress spinner after the specified element
572  * @param element Element to inject after
573  * @param id Identifier string (for use with removeSpinner(), below)
574  */
575 window.injectSpinner = function( element, id ) {
576         var spinner = document.createElement( 'img' );
577         spinner.id = 'mw-spinner-' + id;
578         spinner.src = mw.config.get( 'stylepath' ) + '/common/images/spinner.gif';
579         spinner.alt = spinner.title = '...';
580         if( element.nextSibling ) {
581                 element.parentNode.insertBefore( spinner, element.nextSibling );
582         } else {
583                 element.parentNode.appendChild( spinner );
584         }
588  * Remove a progress spinner added with injectSpinner()
590  * @param id Identifier string
591  */
592 window.removeSpinner = function( id ) {
593         var spinner = document.getElementById( 'mw-spinner-' + id );
594         if( spinner ) {
595                 spinner.parentNode.removeChild( spinner );
596         }
599 window.runOnloadHook = function() {
600         // don't run anything below this for non-dom browsers
601         if ( doneOnloadHook || !( document.getElementById && document.getElementsByTagName ) ) {
602                 return;
603         }
605         // set this before running any hooks, since any errors below
606         // might cause the function to terminate prematurely
607         doneOnloadHook = true;
609         // Run any added-on functions
610         for ( var i = 0; i < onloadFuncts.length; i++ ) {
611                 onloadFuncts[i]();
612         }
616  * Add an event handler to an element
618  * @param element Element to add handler to
619  * @param attach String Event to attach to
620  * @param handler callable Event handler callback
621  */
622 window.addHandler = function( element, attach, handler ) {
623         if( element.addEventListener ) {
624                 element.addEventListener( attach, handler, false );
625         } else if( element.attachEvent ) {
626                 element.attachEvent( 'on' + attach, handler );
627         }
630 window.hookEvent = function( hookName, hookFunct ) {
631         addHandler( window, hookName, hookFunct );
635  * Add a click event handler to an element
637  * @param element Element to add handler to
638  * @param handler callable Event handler callback
639  */
640 window.addClickHandler = function( element, handler ) {
641         addHandler( element, 'click', handler );
645  * Removes an event handler from an element
647  * @param element Element to remove handler from
648  * @param remove String Event to remove
649  * @param handler callable Event handler callback to remove
650  */
651 window.removeHandler = function( element, remove, handler ) {
652         if( window.removeEventListener ) {
653                 element.removeEventListener( remove, handler, false );
654         } else if( window.detachEvent ) {
655                 element.detachEvent( 'on' + remove, handler );
656         }
658 // note: all skins should call runOnloadHook() at the end of html output,
659 //      so the below should be redundant. It's there just in case.
660 hookEvent( 'load', runOnloadHook );
662 if ( ie6_bugs ) {
663         importScriptURI( mw.config.get( 'stylepath' ) + '/common/IEFixes.js' );
666 })();