* API: Allow for query extensions
[mediawiki.git] / skins / common / wikibits.js
blob6299e5fa882b23b314485a1162d4723cdf4e818d
1 // MediaWiki JavaScript support functions
3 var clientPC = navigator.userAgent.toLowerCase(); // Get client info
4 var is_gecko = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
5                 && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
6 var is_safari = ((clientPC.indexOf('applewebkit')!=-1) && (clientPC.indexOf('spoofer')==-1));
7 var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
8 // For accesskeys
9 var is_ff2_win = (clientPC.indexOf('firefox/2')!=-1 || clientPC.indexOf('minefield/3')!=-1) && clientPC.indexOf('windows')!=-1;
10 var is_ff2_x11 = (clientPC.indexOf('firefox/2')!=-1 || clientPC.indexOf('minefield/3')!=-1) && clientPC.indexOf('x11')!=-1;
11 if (clientPC.indexOf('opera') != -1) {
12         var is_opera = true;
13         var is_opera_preseven = (window.opera && !document.childNodes);
14         var is_opera_seven = (window.opera && document.childNodes);
17 // Global external objects used by this script.
18 /*extern ta, stylepath, skin */
20 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
21 var doneOnloadHook;
23 if (!window.onloadFuncts) {
24         var onloadFuncts = [];
27 function addOnloadHook(hookFunct) {
28         // Allows add-on scripts to add onload functions
29         onloadFuncts[onloadFuncts.length] = hookFunct;
32 function hookEvent(hookName, hookFunct) {
33         if (window.addEventListener) {
34                 window.addEventListener(hookName, hookFunct, false);
35         } else if (window.attachEvent) {
36                 window.attachEvent("on" + hookName, hookFunct);
37         }
40 // document.write special stylesheet links
41 if (typeof stylepath != 'undefined' && typeof skin != 'undefined') {
42         if (is_opera_preseven) {
43                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/Opera6Fixes.css">');
44         } else if (is_opera_seven) {
45                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/Opera7Fixes.css">');
46         } else if (is_khtml) {
47                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/KHTMLFixes.css">');
48         }
51 if (wgBreakFrames) {
52         // Un-trap us from framesets
53         if (window.top != window) {
54                 window.top.location = window.location;
55         }
58 // for enhanced RecentChanges
59 function toggleVisibility(_levelId, _otherId, _linkId) {
60         var thisLevel = document.getElementById(_levelId);
61         var otherLevel = document.getElementById(_otherId);
62         var linkLevel = document.getElementById(_linkId);
63         if (thisLevel.style.display == 'none') {
64                 thisLevel.style.display = 'block';
65                 otherLevel.style.display = 'none';
66                 linkLevel.style.display = 'inline';
67         } else {
68                 thisLevel.style.display = 'none';
69                 otherLevel.style.display = 'inline';
70                 linkLevel.style.display = 'none';
71         }
74 function historyRadios(parent) {
75         var inputs = parent.getElementsByTagName('input');
76         var radios = [];
77         for (var i = 0; i < inputs.length; i++) {
78                 if (inputs[i].name == "diff" || inputs[i].name == "oldid") {
79                         radios[radios.length] = inputs[i];
80                 }
81         }
82         return radios;
85 // check selection and tweak visibility/class onclick
86 function diffcheck() {
87         var dli = false; // the li where the diff radio is checked
88         var oli = false; // the li where the oldid radio is checked
89         var hf = document.getElementById('pagehistory');
90         if (!hf) {
91                 return true;
92         }
93         var lis = hf.getElementsByTagName('li');
94         for (var i=0;i<lis.length;i++) {
95                 var inputs = historyRadios(lis[i]);
96                 if (inputs[1] && inputs[0]) {
97                         if (inputs[1].checked || inputs[0].checked) { // this row has a checked radio button
98                                 if (inputs[1].checked && inputs[0].checked && inputs[0].value == inputs[1].value) {
99                                         return false;
100                                 }
101                                 if (oli) { // it's the second checked radio
102                                         if (inputs[1].checked) {
103                                                 oli.className = "selected";
104                                                 return false;
105                                         }
106                                 } else if (inputs[0].checked) {
107                                         return false;
108                                 }
109                                 if (inputs[0].checked) {
110                                         dli = lis[i];
111                                 }
112                                 if (!oli) {
113                                         inputs[0].style.visibility = 'hidden';
114                                 }
115                                 if (dli) {
116                                         inputs[1].style.visibility = 'hidden';
117                                 }
118                                 lis[i].className = "selected";
119                                 oli = lis[i];
120                         }  else { // no radio is checked in this row
121                                 if (!oli) {
122                                         inputs[0].style.visibility = 'hidden';
123                                 } else {
124                                         inputs[0].style.visibility = 'visible';
125                                 }
126                                 if (dli) {
127                                         inputs[1].style.visibility = 'hidden';
128                                 } else {
129                                         inputs[1].style.visibility = 'visible';
130                                 }
131                                 lis[i].className = "";
132                         }
133                 }
134         }
135         return true;
138 // page history stuff
139 // attach event handlers to the input elements on history page
140 function histrowinit() {
141         var hf = document.getElementById('pagehistory');
142         if (!hf) {
143                 return;
144         }
145         var lis = hf.getElementsByTagName('li');
146         for (var i = 0; i < lis.length; i++) {
147                 var inputs = historyRadios(lis[i]);
148                 if (inputs[0] && inputs[1]) {
149                         inputs[0].onclick = diffcheck;
150                         inputs[1].onclick = diffcheck;
151                 }
152         }
153         diffcheck();
156 // generate toc from prefs form, fold sections
157 // XXX: needs testing on IE/Mac and safari
158 // more comments to follow
159 function tabbedprefs() {
160         var prefform = document.getElementById('preferences');
161         if (!prefform || !document.createElement) {
162                 return;
163         }
164         if (prefform.nodeName.toLowerCase() == 'a') {
165                 return; // Occasional IE problem
166         }
167         prefform.className = prefform.className + 'jsprefs';
168         var sections = [];
169         var children = prefform.childNodes;
170         var seci = 0;
171         for (var i = 0; i < children.length; i++) {
172                 if (children[i].nodeName.toLowerCase() == 'fieldset') {
173                         children[i].id = 'prefsection-' + seci;
174                         children[i].className = 'prefsection';
175                         if (is_opera || is_khtml) {
176                                 children[i].className = 'prefsection operaprefsection';
177                         }
178                         var legends = children[i].getElementsByTagName('legend');
179                         sections[seci] = {};
180                         legends[0].className = 'mainLegend';
181                         if (legends[0] && legends[0].firstChild.nodeValue) {
182                                 sections[seci].text = legends[0].firstChild.nodeValue;
183                         } else {
184                                 sections[seci].text = '# ' + seci;
185                         }
186                         sections[seci].secid = children[i].id;
187                         seci++;
188                         if (sections.length != 1) {
189                                 children[i].style.display = 'none';
190                         } else {
191                                 var selectedid = children[i].id;
192                         }
193                 }
194         }
195         var toc = document.createElement('ul');
196         toc.id = 'preftoc';
197         toc.selectedid = selectedid;
198         for (i = 0; i < sections.length; i++) {
199                 var li = document.createElement('li');
200                 if (i === 0) {
201                         li.className = 'selected';
202                 }
203                 var a = document.createElement('a');
204                 a.href = '#' + sections[i].secid;
205                 a.onmousedown = a.onclick = uncoversection;
206                 a.appendChild(document.createTextNode(sections[i].text));
207                 a.secid = sections[i].secid;
208                 li.appendChild(a);
209                 toc.appendChild(li);
210         }
211         prefform.parentNode.insertBefore(toc, prefform.parentNode.childNodes[0]);
212         document.getElementById('prefsubmit').id = 'prefcontrol';
215 function uncoversection() {
216         var oldsecid = this.parentNode.parentNode.selectedid;
217         var newsec = document.getElementById(this.secid);
218         if (oldsecid != this.secid) {
219                 var ul = document.getElementById('preftoc');
220                 document.getElementById(oldsecid).style.display = 'none';
221                 newsec.style.display = 'block';
222                 ul.selectedid = this.secid;
223                 var lis = ul.getElementsByTagName('li');
224                 for (var i = 0; i< lis.length; i++) {
225                         lis[i].className = '';
226                 }
227                 this.parentNode.className = 'selected';
228         }
229         return false;
232 // Timezone stuff
233 // tz in format [+-]HHMM
234 function checkTimezone(tz, msg) {
235         var localclock = new Date();
236         // returns negative offset from GMT in minutes
237         var tzRaw = localclock.getTimezoneOffset();
238         var tzHour = Math.floor( Math.abs(tzRaw) / 60);
239         var tzMin = Math.abs(tzRaw) % 60;
240         var tzString = ((tzRaw >= 0) ? "-" : "+") + ((tzHour < 10) ? "0" : "") + tzHour + ((tzMin < 10) ? "0" : "") + tzMin;
241         if (tz != tzString) {
242                 var junk = msg.split('$1');
243                 document.write(junk[0] + "UTC" + tzString + junk[1]);
244         }
247 function unhidetzbutton() {
248         var tzb = document.getElementById('guesstimezonebutton');
249         if (tzb) {
250                 tzb.style.display = 'inline';
251         }
254 // in [-]HH:MM format...
255 // won't yet work with non-even tzs
256 function fetchTimezone() {
257         // FIXME: work around Safari bug
258         var localclock = new Date();
259         // returns negative offset from GMT in minutes
260         var tzRaw = localclock.getTimezoneOffset();
261         var tzHour = Math.floor( Math.abs(tzRaw) / 60);
262         var tzMin = Math.abs(tzRaw) % 60;
263         var tzString = ((tzRaw >= 0) ? "-" : "") + ((tzHour < 10) ? "0" : "") + tzHour +
264                 ":" + ((tzMin < 10) ? "0" : "") + tzMin;
265         return tzString;
268 function guessTimezone(box) {
269         document.getElementsByName("wpHourDiff")[0].value = fetchTimezone();
272 function showTocToggle() {
273         if (document.createTextNode) {
274                 // Uses DOM calls to avoid document.write + XHTML issues
276                 var linkHolder = document.getElementById('toctitle');
277                 if (!linkHolder) {
278                         return;
279                 }
281                 var outerSpan = document.createElement('span');
282                 outerSpan.className = 'toctoggle';
284                 var toggleLink = document.createElement('a');
285                 toggleLink.id = 'togglelink';
286                 toggleLink.className = 'internal';
287                 toggleLink.href = 'javascript:toggleToc()';
288                 toggleLink.appendChild(document.createTextNode(tocHideText));
290                 outerSpan.appendChild(document.createTextNode('['));
291                 outerSpan.appendChild(toggleLink);
292                 outerSpan.appendChild(document.createTextNode(']'));
294                 linkHolder.appendChild(document.createTextNode(' '));
295                 linkHolder.appendChild(outerSpan);
297                 var cookiePos = document.cookie.indexOf("hidetoc=");
298                 if (cookiePos > -1 && document.cookie.charAt(cookiePos + 8) == 1) {
299                         toggleToc();
300                 }
301         }
304 function changeText(el, newText) {
305         // Safari work around
306         if (el.innerText) {
307                 el.innerText = newText;
308         } else if (el.firstChild && el.firstChild.nodeValue) {
309                 el.firstChild.nodeValue = newText;
310         }
313 function toggleToc() {
314         var toc = document.getElementById('toc').getElementsByTagName('ul')[0];
315         var toggleLink = document.getElementById('togglelink');
317         if (toc && toggleLink && toc.style.display == 'none') {
318                 changeText(toggleLink, tocHideText);
319                 toc.style.display = 'block';
320                 document.cookie = "hidetoc=0";
321         } else {
322                 changeText(toggleLink, tocShowText);
323                 toc.style.display = 'none';
324                 document.cookie = "hidetoc=1";
325         }
328 var mwEditButtons = [];
329 var mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
331 // this function generates the actual toolbar buttons with localized text
332 // we use it to avoid creating the toolbar where javascript is not enabled
333 function addButton(imageFile, speedTip, tagOpen, tagClose, sampleText, imageId) {
334         // Don't generate buttons for browsers which don't fully
335         // support it.
336         mwEditButtons[mwEditButtons.length] =
337                 {"imageId": imageId,
338                  "imageFile": imageFile,
339                  "speedTip": speedTip,
340                  "tagOpen": tagOpen,
341                  "tagClose": tagClose,
342                  "sampleText": sampleText};
345 // this function generates the actual toolbar buttons with localized text
346 // we use it to avoid creating the toolbar where javascript is not enabled
347 function mwInsertEditButton(parent, item) {
348         var image = document.createElement("img");
349         image.width = 23;
350         image.height = 22;
351         image.className = "mw-toolbar-editbutton";
352         if (item.imageId) image.id = item.imageId;
353         image.src = item.imageFile;
354         image.border = 0;
355         image.alt = item.speedTip;
356         image.title = item.speedTip;
357         image.style.cursor = "pointer";
358         image.onclick = function() {
359                 insertTags(item.tagOpen, item.tagClose, item.sampleText);
360                 return false;
361         };
363         parent.appendChild(image);
364         return true;
367 function mwSetupToolbar() {
368         var toolbar = document.getElementById('toolbar');
369         if (!toolbar) { return false; }
371         var textbox = document.getElementById('wpTextbox1');
372         if (!textbox) { return false; }
374         // Don't generate buttons for browsers which don't fully
375         // support it.
376         if (!document.selection && textbox.selectionStart === null) {
377                 return false;
378         }
380         for (var i = 0; i < mwEditButtons.length; i++) {
381                 mwInsertEditButton(toolbar, mwEditButtons[i]);
382         }
383         for (var i = 0; i < mwCustomEditButtons.length; i++) {
384                 mwInsertEditButton(toolbar, mwCustomEditButtons[i]);
385         }
386         return true;
389 function escapeQuotes(text) {
390         var re = new RegExp("'","g");
391         text = text.replace(re,"\\'");
392         re = new RegExp("\\n","g");
393         text = text.replace(re,"\\n");
394         return escapeQuotesHTML(text);
397 function escapeQuotesHTML(text) {
398         var re = new RegExp('&',"g");
399         text = text.replace(re,"&amp;");
400         re = new RegExp('"',"g");
401         text = text.replace(re,"&quot;");
402         re = new RegExp('<',"g");
403         text = text.replace(re,"&lt;");
404         re = new RegExp('>',"g");
405         text = text.replace(re,"&gt;");
406         return text;
409 // apply tagOpen/tagClose to selection in textarea,
410 // use sampleText instead of selection if there is none
411 // copied and adapted from phpBB
412 function insertTags(tagOpen, tagClose, sampleText) {
413         var txtarea;
414         if (document.editform) {
415                 txtarea = document.editform.wpTextbox1;
416         } else {
417                 // some alternate form? take the first one we can find
418                 var areas = document.getElementsByTagName('textarea');
419                 txtarea = areas[0];
420         }
422         // IE
423         if (document.selection  && !is_gecko) {
424                 var theSelection = document.selection.createRange().text;
425                 if (!theSelection) {
426                         theSelection=sampleText;
427                 }
428                 txtarea.focus();
429                 if (theSelection.charAt(theSelection.length - 1) == " ") { // exclude ending space char, if any
430                         theSelection = theSelection.substring(0, theSelection.length - 1);
431                         document.selection.createRange().text = tagOpen + theSelection + tagClose + " ";
432                 } else {
433                         document.selection.createRange().text = tagOpen + theSelection + tagClose;
434                 }
436         // Mozilla
437         } else if(txtarea.selectionStart || txtarea.selectionStart == '0') {
438                 var replaced = false;
439                 var startPos = txtarea.selectionStart;
440                 var endPos = txtarea.selectionEnd;
441                 if (endPos-startPos) {
442                         replaced = true;
443                 }
444                 var scrollTop = txtarea.scrollTop;
445                 var myText = (txtarea.value).substring(startPos, endPos);
446                 if (!myText) {
447                         myText=sampleText;
448                 }
449                 var subst;
450                 if (myText.charAt(myText.length - 1) == " ") { // exclude ending space char, if any
451                         subst = tagOpen + myText.substring(0, (myText.length - 1)) + tagClose + " ";
452                 } else {
453                         subst = tagOpen + myText + tagClose;
454                 }
455                 txtarea.value = txtarea.value.substring(0, startPos) + subst +
456                         txtarea.value.substring(endPos, txtarea.value.length);
457                 txtarea.focus();
458                 //set new selection
459                 if (replaced) {
460                         var cPos = startPos+(tagOpen.length+myText.length+tagClose.length);
461                         txtarea.selectionStart = cPos;
462                         txtarea.selectionEnd = cPos;
463                 } else {
464                         txtarea.selectionStart = startPos+tagOpen.length;
465                         txtarea.selectionEnd = startPos+tagOpen.length+myText.length;
466                 }
467                 txtarea.scrollTop = scrollTop;
469         // All other browsers get no toolbar.
470         // There was previously support for a crippled "help"
471         // bar, but that caused more problems than it solved.
472         }
473         // reposition cursor if possible
474         if (txtarea.createTextRange) {
475                 txtarea.caretPos = document.selection.createRange().duplicate();
476         }
481  * Set the accesskey prefix based on browser detection.
482  */
483 var tooltipAccessKeyPrefix = 'alt-';
484 if (is_opera) {
485         tooltipAccessKeyPrefix = 'shift-esc-';
486 } else if (is_safari
487            || navigator.userAgent.toLowerCase().indexOf('mac') != -1
488            || navigator.userAgent.toLowerCase().indexOf('konqueror') != -1 ) {
489         tooltipAccessKeyPrefix = 'ctrl-';
490 } else if (is_ff2_x11 || is_ff2_win) {
491         tooltipAccessKeyPrefix = 'alt-shift-';
493 var tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?.\]$/;
496  * Add the appropriate prefix to the accesskey shown in the tooltip.
497  * If the nodeList parameter is given, only those nodes are updated;
498  * otherwise, all the nodes that will probably have accesskeys by
499  * default are updated.
501  * @param Array nodeList -- list of elements to update
502  */
503 function updateTooltipAccessKeys( nodeList ) {
504         if ( !nodeList ) {
505                 // skins without a "column-one" element don't seem to have links with accesskeys either
506                 var columnOne = document.getElementById("column-one");
507                 if ( columnOne )
508                         updateTooltipAccessKeys( columnOne.getElementsByTagName("a") );
509                 // these are rare enough that no such optimization is needed
510                 updateTooltipAccessKeys( document.getElementsByTagName("input") );
511                 updateTooltipAccessKeys( document.getElementsByTagName("label") );
512                 return;
513         }
515         for ( var i = 0; i < nodeList.length; i++ ) {
516                 var element = nodeList[i];
517                 var tip = element.getAttribute("title");
518                 var key = element.getAttribute("accesskey");
519                 if ( key && tooltipAccessKeyRegexp.exec(tip) ) {
520                         tip = tip.replace(tooltipAccessKeyRegexp,
521                                           "["+tooltipAccessKeyPrefix+key+"]");
522                         element.setAttribute("title", tip );
523                 }
524         }
528  * Add a link to one of the portlet menus on the page, including:
530  * p-cactions: Content actions (shown as tabs above the main content in Monobook)
531  * p-personal: Personal tools (shown at the top right of the page in Monobook)
532  * p-navigation: Navigation
533  * p-tb: Toolbox
535  * This function exists for the convenience of custom JS authors.  All
536  * but the first three parameters are optional, though providing at
537  * least an id and a tooltip is recommended.
539  * By default the new link will be added to the end of the list.  To
540  * add the link before a given existing item, pass the DOM node of
541  * that item (easily obtained with document.getElementById()) as the
542  * nextnode parameter; to add the link _after_ an existing item, pass
543  * the node's nextSibling instead.
545  * @param String portlet -- id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
546  * @param String href -- link URL
547  * @param String text -- link text (will be automatically lowercased by CSS for p-cactions in Monobook)
548  * @param String id -- id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
549  * @param String tooltip -- text to show when hovering over the link, without accesskey suffix
550  * @param String accesskey -- accesskey to activate this link (one character, try to avoid conflicts)
551  * @param Node nextnode -- the DOM node before which the new item should be added, should be another item in the same list
553  * @return Node -- the DOM node of the new item (an LI element) or null
554  */
555 function addPortletLink(portlet, href, text, id, tooltip, accesskey, nextnode) {
556         var node = document.getElementById(portlet);
557         if ( !node ) return null;
558         node = node.getElementsByTagName( "ul" )[0];
559         if ( !node ) return null;
561         var link = document.createElement( "a" );
562         link.appendChild( document.createTextNode( text ) );
563         link.href = href;
565         var item = document.createElement( "li" );
566         item.appendChild( link );
567         if ( id ) item.id = id;
569         if ( accesskey ) {
570                 link.setAttribute( "accesskey", accesskey );
571                 tooltip += " ["+accesskey+"]";
572         }
573         if ( tooltip ) {
574                 link.setAttribute( "title", tooltip );
575         }
576         if ( accesskey && tooltip ) {
577                 updateTooltipAccessKeys( new Array( link ) );
578         }
580         if ( nextnode && nextnode.parentNode == node )
581                 node.insertBefore( item, nextnode );
582         else
583                 node.appendChild( item );  // IE compatibility (?)
585         return item;
590  * Set up accesskeys/tooltips from the deprecated ta array.  If doId
591  * is specified, only set up for that id.  Note that this function is
592  * deprecated and will not be supported indefinitely -- use
593  * updateTooltipAccessKey() instead.
595  * @param mixed doId string or null
596  */
597 function akeytt( doId ) {
598         // A lot of user scripts (and some of the code below) break if
599         // ta isn't defined, so we make sure it is.  Explictly using
600         // window.ta avoids a "ta is not defined" error.
601         if (!window.ta) window.ta = new Array;
603         // Make a local, possibly restricted, copy to avoid clobbering
604         // the original.
605         var ta;
606         if ( doId ) {
607                 ta = new Array;
608                 ta[doId] = window.ta[doId];
609         } else {
610                 ta = window.ta;
611         }
613         // Now deal with evil deprecated ta
614         var watchCheckboxExists = document.getElementById( 'wpWatchthis' ) ? true : false;
615         for (var id in ta) {
616                 var n = document.getElementById(id);
617                 if (n) {
618                         var a = null;
619                         var ak = '';
620                         // Are we putting accesskey in it
621                         if (ta[id][0].length > 0) {
622                                 // Is this object a object? If not assume it's the next child.
624                                 if (n.nodeName.toLowerCase() == "a") {
625                                         a = n;
626                                 } else {
627                                         a = n.childNodes[0];
628                                 }
629                                 // Don't add an accesskey for the watch tab if the watch
630                                 // checkbox is also available.
631                                 if (a && ((id != 'ca-watch' && id != 'ca-unwatch') || !watchCheckboxExists)) {
632                                         a.accessKey = ta[id][0];
633                                         ak = ' ['+tooltipAccessKeyPrefix+ta[id][0]+']';
634                                 }
635                         } else {
636                                 // We don't care what type the object is when assigning tooltip
637                                 a = n;
638                                 ak = '';
639                         }
641                         if (a) {
642                                 a.title = ta[id][1]+ak;
643                         }
644                 }
645         }
648 function setupRightClickEdit() {
649         if (document.getElementsByTagName) {
650                 var spans = document.getElementsByTagName('span');
651                 for (var i = 0; i < spans.length; i++) {
652                         var el = spans[i];
653                         if(el.className == 'editsection') {
654                                 addRightClickEditHandler(el);
655                         }
656                 }
657         }
660 function addRightClickEditHandler(el) {
661         for (var i = 0; i < el.childNodes.length; i++) {
662                 var link = el.childNodes[i];
663                 if (link.nodeType == 1 && link.nodeName.toLowerCase() == 'a') {
664                         var editHref = link.getAttribute('href');
665                         // find the enclosing (parent) header
666                         var prev = el.parentNode;
667                         if (prev && prev.nodeType == 1 &&
668                         prev.nodeName.match(/^[Hh][1-6]$/)) {
669                                 prev.oncontextmenu = function(e) {
670                                         if (!e) { e = window.event; }
671                                         // e is now the event in all browsers
672                                         var targ;
673                                         if (e.target) { targ = e.target; }
674                                         else if (e.srcElement) { targ = e.srcElement; }
675                                         if (targ.nodeType == 3) { // defeat Safari bug
676                                                 targ = targ.parentNode;
677                                         }
678                                         // targ is now the target element
680                                         // We don't want to deprive the noble reader of a context menu
681                                         // for the section edit link, do we?  (Might want to extend this
682                                         // to all <a>'s?)
683                                         if (targ.nodeName.toLowerCase() != 'a'
684                                         || targ.parentNode.className != 'editsection') {
685                                                 document.location = editHref;
686                                                 return false;
687                                         }
688                                         return true;
689                                 };
690                         }
691                 }
692         }
695 var checkboxes;
696 var lastCheckbox;
698 function setupCheckboxShiftClick() {
699         checkboxes = [];
700         lastCheckbox = null;
701         var inputs = document.getElementsByTagName('input');
702         addCheckboxClickHandlers(inputs);
705 function addCheckboxClickHandlers(inputs, start) {
706         if ( !start) start = 0;
708         var finish = start + 250;
709         if ( finish > inputs.length )
710                 finish = inputs.length;
712         for ( var i = start; i < finish; i++ ) {
713                 var cb = inputs[i];
714                 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' )
715                         continue;
716                 cb.index = checkboxes.push(cb) - 1;
717                 cb.onmouseup = checkboxMouseupHandler;
718         }
720         if ( finish < inputs.length ) {
721                 setTimeout( function () {
722                         addCheckboxClickHandlers(inputs, finish);
723                 }, 200 );
724         }
727 function checkboxMouseupHandler(e) {
728         if (typeof e == 'undefined') {
729                 e = window.event;
730         }
731         if ( !e.shiftKey || lastCheckbox === null ) {
732                 lastCheckbox = this.index;
733                 return true;
734         }
735         var endState = !this.checked;
736         if ( is_opera ) { // opera has already toggled the checkbox by this point
737                 endState = !endState;
738         }
739         var start, finish;
740         if ( this.index < lastCheckbox ) {
741                 start = this.index + 1;
742                 finish = lastCheckbox;
743         } else {
744                 start = lastCheckbox;
745                 finish = this.index - 1;
746         }
747         for (var i = start; i <= finish; ++i ) {
748                 checkboxes[i].checked = endState;
749         }
750         lastCheckbox = this.index;
751         return true;
754 function toggle_element_activation(ida,idb) {
755         if (!document.getElementById) {
756                 return;
757         }
758         document.getElementById(ida).disabled=true;
759         document.getElementById(idb).disabled=false;
762 function toggle_element_check(ida,idb) {
763         if (!document.getElementById) {
764                 return;
765         }
766         document.getElementById(ida).checked=true;
767         document.getElementById(idb).checked=false;
770 function fillDestFilename(id) {
771         if (!document.getElementById) {
772                 return;
773         }
774         var path = document.getElementById(id).value;
775         // Find trailing part
776         var slash = path.lastIndexOf('/');
777         var backslash = path.lastIndexOf('\\');
778         var fname;
779         if (slash == -1 && backslash == -1) {
780                 fname = path;
781         } else if (slash > backslash) {
782                 fname = path.substring(slash+1, 10000);
783         } else {
784                 fname = path.substring(backslash+1, 10000);
785         }
787         // Capitalise first letter and replace spaces by underscores
788         fname = fname.charAt(0).toUpperCase().concat(fname.substring(1,10000)).replace(/ /g, '_');
790         // Output result
791         var destFile = document.getElementById('wpDestFile');
792         if (destFile) {
793                 destFile.value = fname;
794         }
797 function scrollEditBox() {
798         var editBoxEl = document.getElementById("wpTextbox1");
799         var scrollTopEl = document.getElementById("wpScrolltop");
800         var editFormEl = document.getElementById("editform");
802         if (editBoxEl && scrollTopEl) {
803                 if (scrollTopEl.value) { editBoxEl.scrollTop = scrollTopEl.value; }
804                 editFormEl.onsubmit = function() {
805                         document.getElementById("wpScrolltop").value = document.getElementById("wpTextbox1").scrollTop;
806                 };
807         }
810 hookEvent("load", scrollEditBox);
812 var allmessages_nodelist = false;
813 var allmessages_modified = false;
814 var allmessages_timeout = false;
815 var allmessages_running = false;
817 function allmessagesmodified() {
818         allmessages_modified = !allmessages_modified;
819         allmessagesfilter();
822 function allmessagesfilter() {
823         if ( allmessages_timeout )
824                 window.clearTimeout( allmessages_timeout );
826         if ( !allmessages_running )
827                 allmessages_timeout = window.setTimeout( 'allmessagesfilter_do();', 500 );
830 function allmessagesfilter_do() {
831         if ( !allmessages_nodelist )
832                 return;
834         var text = document.getElementById('allmessagesinput').value;
835         var nodef = allmessages_modified;
837         allmessages_running = true;
839         for ( var name in allmessages_nodelist ) {
840                 var nodes = allmessages_nodelist[name];
841                 var display = ( name.indexOf( text ) == -1 ? 'none' : '' );
843                 for ( var i = 0; i < nodes.length; i++)
844                         nodes[i].style.display =
845                                 ( nodes[i].className == "def" && nodef
846                                   ? 'none' : display );
847         }
849         if ( text != document.getElementById('allmessagesinput').value ||
850              nodef != allmessages_modified )
851                 allmessagesfilter_do();  // repeat
853         allmessages_running = false;
856 function allmessagesfilter_init() {
857         if ( allmessages_nodelist )
858                 return;
860         var nodelist = new Array();
861         var templist = new Array();
863         var table = document.getElementById('allmessagestable');
864         if ( !table ) return;
866         var rows = document.getElementsByTagName('tr');
867         for ( var i = 0; i < rows.length; i++ ) {
868                 var id = rows[i].getAttribute('id')
869                 if ( id && id.substring(0,16) != 'sp-allmessages-r' ) continue;
870                 templist[ id ] = rows[i];
871         }
873         var spans = table.getElementsByTagName('span');
874         for ( var i = 0; i < spans.length; i++ ) {
875                 var id = spans[i].getAttribute('id')
876                 if ( id && id.substring(0,17) != 'sp-allmessages-i-' ) continue;
877                 if ( !spans[i].firstChild || spans[i].firstChild.nodeType != 3 ) continue;
879                 var nodes = new Array();
880                 var row1 = templist[ id.replace('i', 'r1') ];
881                 var row2 = templist[ id.replace('i', 'r2') ];
883                 if ( row1 ) nodes[nodes.length] = row1;
884                 if ( row2 ) nodes[nodes.length] = row2;
885                 nodelist[ spans[i].firstChild.nodeValue ] = nodes;
886         }
888         var k = document.getElementById('allmessagesfilter');
889         if (k) { k.style.display = ''; }
891         allmessages_nodelist = nodelist;
894 hookEvent( "load", allmessagesfilter_init );
897         Written by Jonathan Snook, http://www.snook.ca/jonathan
898         Add-ons by Robert Nyman, http://www.robertnyman.com
899         Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
900         From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
902 function getElementsByClassName(oElm, strTagName, oClassNames){
903         var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
904         var arrReturnElements = new Array();
905         var arrRegExpClassNames = new Array();
906         if(typeof oClassNames == "object"){
907                 for(var i=0; i<oClassNames.length; i++){
908                         arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
909                 }
910         }
911         else{
912                 arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
913         }
914         var oElement;
915         var bMatchesAll;
916         for(var j=0; j<arrElements.length; j++){
917                 oElement = arrElements[j];
918                 bMatchesAll = true;
919                 for(var k=0; k<arrRegExpClassNames.length; k++){
920                         if(!arrRegExpClassNames[k].test(oElement.className)){
921                                 bMatchesAll = false;
922                                 break;
923                         }
924                 }
925                 if(bMatchesAll){
926                         arrReturnElements.push(oElement);
927                 }
928         }
929         return (arrReturnElements)
932 function redirectToFragment(fragment) {
933         var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
934         if (match) {
935                 var webKitVersion = parseInt(match[1]);
936                 if (webKitVersion < 420) {
937                         // Released Safari w/ WebKit 418.9.1 messes up horribly
938                         // Nightlies of 420+ are ok
939                         return;
940                 }
941         }
942         if (is_gecko) {
943                 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
944                 addOnloadHook(function () {
945                         if (window.location.hash == "")
946                                 window.location.hash = fragment;
947                 });
948         } else {
949                 if (window.location.hash == "")
950                         window.location.hash = fragment;
951         }
955  * Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
956  * Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
957  * Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .
959  * Copyright (c) 1997-2006 Stuart Langridge, Joost de Valk.
961  * @todo don't break on colspans/rowspans (bug 8028)
962  * @todo language-specific digit grouping/decimals (bug 8063)
963  * @todo support all accepted date formats (bug 8226)
964  */
966 var ts_image_path = stylepath+"/common/images/";
967 var ts_image_up = "sort_up.gif";
968 var ts_image_down = "sort_down.gif";
969 var ts_image_none = "sort_none.gif";
970 var ts_europeandate = wgContentLanguage != "en"; // The non-American-inclined can change to "true"
971 var ts_alternate_row_colors = true;
972 var SORT_COLUMN_INDEX;
974 function sortables_init() {
975         var idnum = 0;
976         // Find all tables with class sortable and make them sortable
977         var tables = getElementsByClassName(document, "table", "sortable");
978         for (var ti = 0; ti < tables.length ; ti++) {
979                 if (!tables[ti].id) {
980                         tables[ti].setAttribute('id','sortable_table_id_'+idnum);
981                         ++idnum;
982                 }
983                 ts_makeSortable(tables[ti]);
984         }
987 function ts_makeSortable(table) {
988         var firstRow;
989         if (table.rows && table.rows.length > 0) {
990                 if (table.tHead && table.tHead.rows.length > 0) {
991                         firstRow = table.tHead.rows[table.tHead.rows.length-1];
992                 } else {
993                         firstRow = table.rows[0];
994                 }
995         }
996         if (!firstRow) return;
998         // We have a first row: assume it's the header, and make its contents clickable links
999         for (var i = 0; i < firstRow.cells.length; i++) {
1000                 var cell = firstRow.cells[i];
1001                 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
1002                         cell.innerHTML += '&nbsp;&nbsp;<a href="#" class="sortheader" onclick="ts_resortTable(this);return false;"><span class="sortarrow"><img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/></span></a>';
1003                 }
1004         }
1005         if (ts_alternate_row_colors) {
1006                 ts_alternate(table);
1007         }
1010 function ts_getInnerText(el) {
1011         if (typeof el == "string") return el;
1012         if (typeof el == "undefined") { return el };
1013         if (el.innerText) return el.innerText;  // Not needed but it is faster
1014         var str = "";
1016         var cs = el.childNodes;
1017         var l = cs.length;
1018         for (var i = 0; i < l; i++) {
1019                 switch (cs[i].nodeType) {
1020                         case 1: //ELEMENT_NODE
1021                                 str += ts_getInnerText(cs[i]);
1022                                 break;
1023                         case 3: //TEXT_NODE
1024                                 str += cs[i].nodeValue;
1025                                 break;
1026                 }
1027         }
1028         return str;
1031 function ts_resortTable(lnk) {
1032         // get the span
1033         var span = lnk.getElementsByTagName('span')[0];
1035         var td = lnk.parentNode;
1036         var tr = td.parentNode;
1037         var column = td.cellIndex;
1039         var table = tr.parentNode;
1040         while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
1041                 table = table.parentNode;
1042         if (!table) return;
1044         // Work out a type for the column
1045         if (table.rows.length <= 1) return;
1047         // Skip the first row if that's where the headings are
1048         var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
1050         var itm = "";
1051         for (var i = rowStart; i < table.rows.length; i++) {
1052                 if (table.rows[i].cells.length > column) {
1053                         itm = ts_getInnerText(table.rows[i].cells[column]);
1054                         itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
1055                         if (itm != "") break;
1056                 }
1057         }
1059         sortfn = ts_sort_caseinsensitive;
1060         if (itm.match(/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/))
1061                 sortfn = ts_sort_date;
1062         if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/))
1063                 sortfn = ts_sort_date;
1064         if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d$/))
1065                 sortfn = ts_sort_date;
1066         if (itm.match(/^[\u00a3$\u20ac]/)) // pound dollar euro
1067                 sortfn = ts_sort_currency;
1068         if (itm.match(/^[\d.,]+\%?$/))
1069                 sortfn = ts_sort_numeric;
1071         var reverse = (span.getAttribute("sortdir") == 'down');
1073         var newRows = new Array();
1074         for (var j = rowStart; j < table.rows.length; j++) {
1075                 var row = table.rows[j];
1076                 var keyText = ts_getInnerText(row.cells[column]);
1077                 var oldIndex = (reverse ? -j : j);
1079                 newRows[newRows.length] = new Array(row, keyText, oldIndex);
1080         }
1082         newRows.sort(sortfn);
1084         var arrowHTML;
1085         if (reverse) {
1086                         arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
1087                         newRows.reverse();
1088                         span.setAttribute('sortdir','up');
1089         } else {
1090                         arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
1091                         span.setAttribute('sortdir','down');
1092         }
1094         // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
1095         // don't do sortbottom rows
1096         for (var i = 0; i < newRows.length; i++) {
1097                 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
1098                         table.tBodies[0].appendChild(newRows[i][0]);
1099         }
1100         // do sortbottom rows only
1101         for (var i = 0; i < newRows.length; i++) {
1102                 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
1103                         table.tBodies[0].appendChild(newRows[i][0]);
1104         }
1106         // Delete any other arrows there may be showing
1107         var spans = getElementsByClassName(tr, "span", "sortarrow");
1108         for (var i = 0; i < spans.length; i++) {
1109                 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
1110         }
1111         span.innerHTML = arrowHTML;
1113         ts_alternate(table);            
1116 function ts_dateToSortKey(date) {       
1117         // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
1118         if (date.length == 11) {
1119                 switch (date.substr(3,3).toLowerCase()) {
1120                         case "jan": var month = "01"; break;
1121                         case "feb": var month = "02"; break;
1122                         case "mar": var month = "03"; break;
1123                         case "apr": var month = "04"; break;
1124                         case "may": var month = "05"; break;
1125                         case "jun": var month = "06"; break;
1126                         case "jul": var month = "07"; break;
1127                         case "aug": var month = "08"; break;
1128                         case "sep": var month = "09"; break;
1129                         case "oct": var month = "10"; break;
1130                         case "nov": var month = "11"; break;
1131                         case "dec": var month = "12"; break;
1132                         // default: var month = "00";
1133                 }
1134                 return date.substr(7,4)+month+date.substr(0,2);
1135         } else if (date.length == 10) {
1136                 if (ts_europeandate == false) {
1137                         return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
1138                 } else {
1139                         return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
1140                 }
1141         } else if (date.length == 8) {
1142                 yr = date.substr(6,2);
1143                 if (parseInt(yr) < 50) { 
1144                         yr = '20'+yr; 
1145                 } else { 
1146                         yr = '19'+yr; 
1147                 }
1148                 if (ts_europeandate == true) {
1149                         return yr+date.substr(3,2)+date.substr(0,2);
1150                 } else {
1151                         return yr+date.substr(0,2)+date.substr(3,2);
1152                 }
1153         }
1154         return "00000000";
1157 function ts_parseFloat(num) {
1158         if (!num) return 0;
1159         num = parseFloat(num.replace(/,/, ""));
1160         return (isNaN(num) ? 0 : num);
1163 function ts_sort_date(a,b) {
1164         var aa = ts_dateToSortKey(a[1]);
1165         var bb = ts_dateToSortKey(b[1]);
1166         return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1169 function ts_sort_currency(a,b) {
1170         var aa = ts_parseFloat(a[1].replace(/[^0-9.]/g,''));
1171         var bb = ts_parseFloat(b[1].replace(/[^0-9.]/g,''));
1172         return (aa != bb ? aa - bb : a[2] - b[2]);
1175 function ts_sort_numeric(a,b) {
1176         var aa = ts_parseFloat(a[1]);
1177         var bb = ts_parseFloat(b[1]);
1178         return (aa != bb ? aa - bb : a[2] - b[2]);
1181 function ts_sort_caseinsensitive(a,b) {
1182         var aa = a[1].toLowerCase();
1183         var bb = b[1].toLowerCase();
1184         return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1187 function ts_sort_default(a,b) {
1188         return (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2]);
1191 function ts_alternate(table) {
1192         // Take object table and get all it's tbodies.
1193         var tableBodies = table.getElementsByTagName("tbody");
1194         // Loop through these tbodies
1195         for (var i = 0; i < tableBodies.length; i++) {
1196                 // Take the tbody, and get all it's rows
1197                 var tableRows = tableBodies[i].getElementsByTagName("tr");
1198                 // Loop through these rows
1199                 // Start at 1 because we want to leave the heading row untouched
1200                 for (var j = 0; j < tableRows.length; j++) {
1201                         // Check if j is even, and apply classes for both possible results
1202                         var oldClasses = tableRows[j].className.split(" ");
1203                         var newClassName = "";
1204                         for (var k = 0; k < oldClasses.length; k++) {
1205                                 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
1206                                         newClassName += oldClasses[k] + " ";
1207                         }
1208                         tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
1209                 }
1210         }
1214  * End of table sorting code
1215  */
1217 function runOnloadHook() {
1218         // don't run anything below this for non-dom browsers
1219         if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
1220                 return;
1221         }
1223         // set this before running any hooks, since any errors below
1224         // might cause the function to terminate prematurely
1225         doneOnloadHook = true;
1227         histrowinit();
1228         unhidetzbutton();
1229         tabbedprefs();
1230         updateTooltipAccessKeys( null );
1231         akeytt( null );
1232         scrollEditBox();
1233         setupCheckboxShiftClick();
1234         sortables_init();
1236         // Run any added-on functions
1237         for (var i = 0; i < onloadFuncts.length; i++) {
1238                 onloadFuncts[i]();
1239         }
1242 //note: all skins should call runOnloadHook() at the end of html output,
1243 //      so the below should be redundant. It's there just in case.
1244 hookEvent("load", runOnloadHook);
1246 hookEvent("load", mwSetupToolbar);