Use prefixedText(), rather than IRC clean text for replace call on comment to make...
[mediawiki.git] / skins / common / wikibits.js
blobcdb5c9defc728113fb190f3c5220dadcc113ec6b
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);
15         var is_opera_95 = (clientPC.search(/opera\/(9.[5-9]|[1-9][0-9])/)!=-1);
18 // Global external objects used by this script.
19 /*extern ta, stylepath, skin */
21 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
22 var doneOnloadHook;
24 if (!window.onloadFuncts) {
25         var onloadFuncts = [];
28 function addOnloadHook(hookFunct) {
29         // Allows add-on scripts to add onload functions
30         onloadFuncts[onloadFuncts.length] = hookFunct;
33 function hookEvent(hookName, hookFunct) {
34         if (window.addEventListener) {
35                 window.addEventListener(hookName, hookFunct, false);
36         } else if (window.attachEvent) {
37                 window.attachEvent("on" + hookName, hookFunct);
38         }
41 // document.write special stylesheet links
42 if (typeof stylepath != 'undefined' && typeof skin != 'undefined') {
43         if (is_opera_preseven) {
44                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/Opera6Fixes.css">');
45         } else if (is_opera_seven && !is_opera_95) {
46                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/Opera7Fixes.css">');
47         } else if (is_khtml) {
48                 document.write('<link rel="stylesheet" type="text/css" href="'+stylepath+'/'+skin+'/KHTMLFixes.css">');
49         }
52 if (wgBreakFrames) {
53         // Un-trap us from framesets
54         if (window.top != window) {
55                 window.top.location = window.location;
56         }
59 // for enhanced RecentChanges
60 function toggleVisibility(_levelId, _otherId, _linkId) {
61         var thisLevel = document.getElementById(_levelId);
62         var otherLevel = document.getElementById(_otherId);
63         var linkLevel = document.getElementById(_linkId);
64         if (thisLevel.style.display == 'none') {
65                 thisLevel.style.display = 'block';
66                 otherLevel.style.display = 'none';
67                 linkLevel.style.display = 'inline';
68         } else {
69                 thisLevel.style.display = 'none';
70                 otherLevel.style.display = 'inline';
71                 linkLevel.style.display = 'none';
72         }
75 function historyRadios(parent) {
76         var inputs = parent.getElementsByTagName('input');
77         var radios = [];
78         for (var i = 0; i < inputs.length; i++) {
79                 if (inputs[i].name == "diff" || inputs[i].name == "oldid") {
80                         radios[radios.length] = inputs[i];
81                 }
82         }
83         return radios;
86 // check selection and tweak visibility/class onclick
87 function diffcheck() {
88         var dli = false; // the li where the diff radio is checked
89         var oli = false; // the li where the oldid radio is checked
90         var hf = document.getElementById('pagehistory');
91         if (!hf) {
92                 return true;
93         }
94         var lis = hf.getElementsByTagName('li');
95         for (var i=0;i<lis.length;i++) {
96                 var inputs = historyRadios(lis[i]);
97                 if (inputs[1] && inputs[0]) {
98                         if (inputs[1].checked || inputs[0].checked) { // this row has a checked radio button
99                                 if (inputs[1].checked && inputs[0].checked && inputs[0].value == inputs[1].value) {
100                                         return false;
101                                 }
102                                 if (oli) { // it's the second checked radio
103                                         if (inputs[1].checked) {
104                                                 oli.className = "selected";
105                                                 return false;
106                                         }
107                                 } else if (inputs[0].checked) {
108                                         return false;
109                                 }
110                                 if (inputs[0].checked) {
111                                         dli = lis[i];
112                                 }
113                                 if (!oli) {
114                                         inputs[0].style.visibility = 'hidden';
115                                 }
116                                 if (dli) {
117                                         inputs[1].style.visibility = 'hidden';
118                                 }
119                                 lis[i].className = "selected";
120                                 oli = lis[i];
121                         }  else { // no radio is checked in this row
122                                 if (!oli) {
123                                         inputs[0].style.visibility = 'hidden';
124                                 } else {
125                                         inputs[0].style.visibility = 'visible';
126                                 }
127                                 if (dli) {
128                                         inputs[1].style.visibility = 'hidden';
129                                 } else {
130                                         inputs[1].style.visibility = 'visible';
131                                 }
132                                 lis[i].className = "";
133                         }
134                 }
135         }
136         return true;
139 // page history stuff
140 // attach event handlers to the input elements on history page
141 function histrowinit() {
142         var hf = document.getElementById('pagehistory');
143         if (!hf) {
144                 return;
145         }
146         var lis = hf.getElementsByTagName('li');
147         for (var i = 0; i < lis.length; i++) {
148                 var inputs = historyRadios(lis[i]);
149                 if (inputs[0] && inputs[1]) {
150                         inputs[0].onclick = diffcheck;
151                         inputs[1].onclick = diffcheck;
152                 }
153         }
154         diffcheck();
157 // generate toc from prefs form, fold sections
158 // XXX: needs testing on IE/Mac and safari
159 // more comments to follow
160 function tabbedprefs() {
161         var prefform = document.getElementById('preferences');
162         if (!prefform || !document.createElement) {
163                 return;
164         }
165         if (prefform.nodeName.toLowerCase() == 'a') {
166                 return; // Occasional IE problem
167         }
168         prefform.className = prefform.className + 'jsprefs';
169         var sections = [];
170         var children = prefform.childNodes;
171         var seci = 0;
172         for (var i = 0; i < children.length; i++) {
173                 if (children[i].nodeName.toLowerCase() == 'fieldset') {
174                         children[i].id = 'prefsection-' + seci;
175                         children[i].className = 'prefsection';
176                         if (is_opera || is_khtml) {
177                                 children[i].className = 'prefsection operaprefsection';
178                         }
179                         var legends = children[i].getElementsByTagName('legend');
180                         sections[seci] = {};
181                         legends[0].className = 'mainLegend';
182                         if (legends[0] && legends[0].firstChild.nodeValue) {
183                                 sections[seci].text = legends[0].firstChild.nodeValue;
184                         } else {
185                                 sections[seci].text = '# ' + seci;
186                         }
187                         sections[seci].secid = children[i].id;
188                         seci++;
189                         if (sections.length != 1) {
190                                 children[i].style.display = 'none';
191                         } else {
192                                 var selectedid = children[i].id;
193                         }
194                 }
195         }
196         var toc = document.createElement('ul');
197         toc.id = 'preftoc';
198         toc.selectedid = selectedid;
199         for (i = 0; i < sections.length; i++) {
200                 var li = document.createElement('li');
201                 if (i === 0) {
202                         li.className = 'selected';
203                 }
204                 var a = document.createElement('a');
205                 a.href = '#' + sections[i].secid;
206                 a.onmousedown = a.onclick = uncoversection;
207                 a.appendChild(document.createTextNode(sections[i].text));
208                 a.secid = sections[i].secid;
209                 li.appendChild(a);
210                 toc.appendChild(li);
211         }
212         prefform.parentNode.insertBefore(toc, prefform.parentNode.childNodes[0]);
213         document.getElementById('prefsubmit').id = 'prefcontrol';
216 function uncoversection() {
217         var oldsecid = this.parentNode.parentNode.selectedid;
218         var newsec = document.getElementById(this.secid);
219         if (oldsecid != this.secid) {
220                 var ul = document.getElementById('preftoc');
221                 document.getElementById(oldsecid).style.display = 'none';
222                 newsec.style.display = 'block';
223                 ul.selectedid = this.secid;
224                 var lis = ul.getElementsByTagName('li');
225                 for (var i = 0; i< lis.length; i++) {
226                         lis[i].className = '';
227                 }
228                 this.parentNode.className = 'selected';
229         }
230         return false;
233 // Timezone stuff
234 // tz in format [+-]HHMM
235 function checkTimezone(tz, msg) {
236         var localclock = new Date();
237         // returns negative offset from GMT in minutes
238         var tzRaw = localclock.getTimezoneOffset();
239         var tzHour = Math.floor( Math.abs(tzRaw) / 60);
240         var tzMin = Math.abs(tzRaw) % 60;
241         var tzString = ((tzRaw >= 0) ? "-" : "+") + ((tzHour < 10) ? "0" : "") + tzHour + ((tzMin < 10) ? "0" : "") + tzMin;
242         if (tz != tzString) {
243                 var junk = msg.split('$1');
244                 document.write(junk[0] + "UTC" + tzString + junk[1]);
245         }
248 function unhidetzbutton() {
249         var tzb = document.getElementById('guesstimezonebutton');
250         if (tzb) {
251                 tzb.style.display = 'inline';
252         }
255 // in [-]HH:MM format...
256 // won't yet work with non-even tzs
257 function fetchTimezone() {
258         // FIXME: work around Safari bug
259         var localclock = new Date();
260         // returns negative offset from GMT in minutes
261         var tzRaw = localclock.getTimezoneOffset();
262         var tzHour = Math.floor( Math.abs(tzRaw) / 60);
263         var tzMin = Math.abs(tzRaw) % 60;
264         var tzString = ((tzRaw >= 0) ? "-" : "") + ((tzHour < 10) ? "0" : "") + tzHour +
265                 ":" + ((tzMin < 10) ? "0" : "") + tzMin;
266         return tzString;
269 function guessTimezone(box) {
270         document.getElementsByName("wpHourDiff")[0].value = fetchTimezone();
273 function showTocToggle() {
274         if (document.createTextNode) {
275                 // Uses DOM calls to avoid document.write + XHTML issues
277                 var linkHolder = document.getElementById('toctitle');
278                 if (!linkHolder) {
279                         return;
280                 }
282                 var outerSpan = document.createElement('span');
283                 outerSpan.className = 'toctoggle';
285                 var toggleLink = document.createElement('a');
286                 toggleLink.id = 'togglelink';
287                 toggleLink.className = 'internal';
288                 toggleLink.href = 'javascript:toggleToc()';
289                 toggleLink.appendChild(document.createTextNode(tocHideText));
291                 outerSpan.appendChild(document.createTextNode('['));
292                 outerSpan.appendChild(toggleLink);
293                 outerSpan.appendChild(document.createTextNode(']'));
295                 linkHolder.appendChild(document.createTextNode(' '));
296                 linkHolder.appendChild(outerSpan);
298                 var cookiePos = document.cookie.indexOf("hidetoc=");
299                 if (cookiePos > -1 && document.cookie.charAt(cookiePos + 8) == 1) {
300                         toggleToc();
301                 }
302         }
305 function changeText(el, newText) {
306         // Safari work around
307         if (el.innerText) {
308                 el.innerText = newText;
309         } else if (el.firstChild && el.firstChild.nodeValue) {
310                 el.firstChild.nodeValue = newText;
311         }
314 function toggleToc() {
315         var toc = document.getElementById('toc').getElementsByTagName('ul')[0];
316         var toggleLink = document.getElementById('togglelink');
318         if (toc && toggleLink && toc.style.display == 'none') {
319                 changeText(toggleLink, tocHideText);
320                 toc.style.display = 'block';
321                 document.cookie = "hidetoc=0";
322         } else {
323                 changeText(toggleLink, tocShowText);
324                 toc.style.display = 'none';
325                 document.cookie = "hidetoc=1";
326         }
329 var mwEditButtons = [];
330 var mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
332 // this function generates the actual toolbar buttons with localized text
333 // we use it to avoid creating the toolbar where javascript is not enabled
334 function addButton(imageFile, speedTip, tagOpen, tagClose, sampleText, imageId) {
335         // Don't generate buttons for browsers which don't fully
336         // support it.
337         mwEditButtons[mwEditButtons.length] =
338                 {"imageId": imageId,
339                  "imageFile": imageFile,
340                  "speedTip": speedTip,
341                  "tagOpen": tagOpen,
342                  "tagClose": tagClose,
343                  "sampleText": sampleText};
346 // this function generates the actual toolbar buttons with localized text
347 // we use it to avoid creating the toolbar where javascript is not enabled
348 function mwInsertEditButton(parent, item) {
349         var image = document.createElement("img");
350         image.width = 23;
351         image.height = 22;
352         image.className = "mw-toolbar-editbutton";
353         if (item.imageId) image.id = item.imageId;
354         image.src = item.imageFile;
355         image.border = 0;
356         image.alt = item.speedTip;
357         image.title = item.speedTip;
358         image.style.cursor = "pointer";
359         image.onclick = function() {
360                 insertTags(item.tagOpen, item.tagClose, item.sampleText);
361                 return false;
362         };
364         parent.appendChild(image);
365         return true;
368 function mwSetupToolbar() {
369         var toolbar = document.getElementById('toolbar');
370         if (!toolbar) { return false; }
372         var textbox = document.getElementById('wpTextbox1');
373         if (!textbox) { return false; }
375         // Don't generate buttons for browsers which don't fully
376         // support it.
377         if (!(document.selection && document.selection.createRange)
378                 && textbox.selectionStart === null) {
379                 return false;
380         }
382         for (var i = 0; i < mwEditButtons.length; i++) {
383                 mwInsertEditButton(toolbar, mwEditButtons[i]);
384         }
385         for (var i = 0; i < mwCustomEditButtons.length; i++) {
386                 mwInsertEditButton(toolbar, mwCustomEditButtons[i]);
387         }
388         return true;
391 function escapeQuotes(text) {
392         var re = new RegExp("'","g");
393         text = text.replace(re,"\\'");
394         re = new RegExp("\\n","g");
395         text = text.replace(re,"\\n");
396         return escapeQuotesHTML(text);
399 function escapeQuotesHTML(text) {
400         var re = new RegExp('&',"g");
401         text = text.replace(re,"&amp;");
402         re = new RegExp('"',"g");
403         text = text.replace(re,"&quot;");
404         re = new RegExp('<',"g");
405         text = text.replace(re,"&lt;");
406         re = new RegExp('>',"g");
407         text = text.replace(re,"&gt;");
408         return text;
411 // apply tagOpen/tagClose to selection in textarea,
412 // use sampleText instead of selection if there is none
413 function insertTags(tagOpen, tagClose, sampleText) {
414         var txtarea;
415         if (document.editform) {
416                 txtarea = document.editform.wpTextbox1;
417         } else {
418                 // some alternate form? take the first one we can find
419                 var areas = document.getElementsByTagName('textarea');
420                 txtarea = areas[0];
421         }
422         var selText, isSample = false;
424         if (document.selection  && document.selection.createRange) { // IE/Opera
426                 //save window scroll position
427                 if (document.documentElement && document.documentElement.scrollTop)
428                         var winScroll = document.documentElement.scrollTop
429                 else if (document.body)
430                         var winScroll = document.body.scrollTop;
431                 //get current selection  
432                 txtarea.focus();
433                 var range = document.selection.createRange();
434                 selText = range.text;
435                 //insert tags
436                 checkSelectedText();
437                 range.text = tagOpen + selText + tagClose;
438                 //mark sample text as selected
439                 if (isSample && range.moveStart) {
440                         if (window.opera)
441                                 tagClose = tagClose.replace(/\n/g,'');
442                         range.moveStart('character', - tagClose.length - selText.length); 
443                         range.moveEnd('character', - tagClose.length); 
444                 }
445                 range.select();   
446                 //restore window scroll position
447                 if (document.documentElement && document.documentElement.scrollTop)
448                         document.documentElement.scrollTop = winScroll
449                 else if (document.body)
450                         document.body.scrollTop = winScroll;
452         } else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla
454                 //save textarea scroll position
455                 var textScroll = txtarea.scrollTop;
456                 //get current selection
457                 txtarea.focus();
458                 var startPos = txtarea.selectionStart;
459                 var endPos = txtarea.selectionEnd;
460                 selText = txtarea.value.substring(startPos, endPos);
461                 //insert tags
462                 checkSelectedText();
463                 txtarea.value = txtarea.value.substring(0, startPos)
464                         + tagOpen + selText + tagClose
465                         + txtarea.value.substring(endPos, txtarea.value.length);
466                 //set new selection
467                 if (isSample) {
468                         txtarea.selectionStart = startPos + tagOpen.length;
469                         txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
470                 } else {
471                         txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
472                         txtarea.selectionEnd = txtarea.selectionStart;
473                 }
474                 //restore textarea scroll position
475                 txtarea.scrollTop = textScroll;
476         } 
478         function checkSelectedText(){
479                 if (!selText) {
480                         selText = sampleText;
481                         isSample = true;
482                 } else if (selText.charAt(selText.length - 1) == ' ') { //exclude ending space char
483                         selText = selText.substring(0, selText.length - 1);
484                         tagClose += ' '
485                 } 
486         }
492  * Set the accesskey prefix based on browser detection.
493  */
494 var tooltipAccessKeyPrefix = 'alt-';
495 if (is_opera) {
496         tooltipAccessKeyPrefix = 'shift-esc-';
497 } else if (is_safari
498            || navigator.userAgent.toLowerCase().indexOf('mac') != -1
499            || navigator.userAgent.toLowerCase().indexOf('konqueror') != -1 ) {
500         tooltipAccessKeyPrefix = 'ctrl-';
501 } else if (is_ff2_x11 || is_ff2_win) {
502         tooltipAccessKeyPrefix = 'alt-shift-';
504 var tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?.\]$/;
507  * Add the appropriate prefix to the accesskey shown in the tooltip.
508  * If the nodeList parameter is given, only those nodes are updated;
509  * otherwise, all the nodes that will probably have accesskeys by
510  * default are updated.
512  * @param Array nodeList -- list of elements to update
513  */
514 function updateTooltipAccessKeys( nodeList ) {
515         if ( !nodeList ) {
516                 // skins without a "column-one" element don't seem to have links with accesskeys either
517                 var columnOne = document.getElementById("column-one");
518                 if ( columnOne )
519                         updateTooltipAccessKeys( columnOne.getElementsByTagName("a") );
520                 // these are rare enough that no such optimization is needed
521                 updateTooltipAccessKeys( document.getElementsByTagName("input") );
522                 updateTooltipAccessKeys( document.getElementsByTagName("label") );
523                 return;
524         }
526         for ( var i = 0; i < nodeList.length; i++ ) {
527                 var element = nodeList[i];
528                 var tip = element.getAttribute("title");
529                 var key = element.getAttribute("accesskey");
530                 if ( key && tooltipAccessKeyRegexp.exec(tip) ) {
531                         tip = tip.replace(tooltipAccessKeyRegexp,
532                                           "["+tooltipAccessKeyPrefix+key+"]");
533                         element.setAttribute("title", tip );
534                 }
535         }
539  * Add a link to one of the portlet menus on the page, including:
541  * p-cactions: Content actions (shown as tabs above the main content in Monobook)
542  * p-personal: Personal tools (shown at the top right of the page in Monobook)
543  * p-navigation: Navigation
544  * p-tb: Toolbox
546  * This function exists for the convenience of custom JS authors.  All
547  * but the first three parameters are optional, though providing at
548  * least an id and a tooltip is recommended.
550  * By default the new link will be added to the end of the list.  To
551  * add the link before a given existing item, pass the DOM node of
552  * that item (easily obtained with document.getElementById()) as the
553  * nextnode parameter; to add the link _after_ an existing item, pass
554  * the node's nextSibling instead.
556  * @param String portlet -- id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
557  * @param String href -- link URL
558  * @param String text -- link text (will be automatically lowercased by CSS for p-cactions in Monobook)
559  * @param String id -- id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
560  * @param String tooltip -- text to show when hovering over the link, without accesskey suffix
561  * @param String accesskey -- accesskey to activate this link (one character, try to avoid conflicts)
562  * @param Node nextnode -- the DOM node before which the new item should be added, should be another item in the same list
564  * @return Node -- the DOM node of the new item (an LI element) or null
565  */
566 function addPortletLink(portlet, href, text, id, tooltip, accesskey, nextnode) {
567         var node = document.getElementById(portlet);
568         if ( !node ) return null;
569         node = node.getElementsByTagName( "ul" )[0];
570         if ( !node ) return null;
572         var link = document.createElement( "a" );
573         link.appendChild( document.createTextNode( text ) );
574         link.href = href;
576         var item = document.createElement( "li" );
577         item.appendChild( link );
578         if ( id ) item.id = id;
580         if ( accesskey ) {
581                 link.setAttribute( "accesskey", accesskey );
582                 tooltip += " ["+accesskey+"]";
583         }
584         if ( tooltip ) {
585                 link.setAttribute( "title", tooltip );
586         }
587         if ( accesskey && tooltip ) {
588                 updateTooltipAccessKeys( new Array( link ) );
589         }
591         if ( nextnode && nextnode.parentNode == node )
592                 node.insertBefore( item, nextnode );
593         else
594                 node.appendChild( item );  // IE compatibility (?)
596         return item;
601  * Set up accesskeys/tooltips from the deprecated ta array.  If doId
602  * is specified, only set up for that id.  Note that this function is
603  * deprecated and will not be supported indefinitely -- use
604  * updateTooltipAccessKey() instead.
606  * @param mixed doId string or null
607  */
608 function akeytt( doId ) {
609         // A lot of user scripts (and some of the code below) break if
610         // ta isn't defined, so we make sure it is.  Explictly using
611         // window.ta avoids a "ta is not defined" error.
612         if (!window.ta) window.ta = new Array;
614         // Make a local, possibly restricted, copy to avoid clobbering
615         // the original.
616         var ta;
617         if ( doId ) {
618                 ta = [doId];
619         } else {
620                 ta = window.ta;
621         }
623         // Now deal with evil deprecated ta
624         var watchCheckboxExists = document.getElementById( 'wpWatchthis' ) ? true : false;
625         for (var id in ta) {
626                 var n = document.getElementById(id);
627                 if (n) {
628                         var a = null;
629                         var ak = '';
630                         // Are we putting accesskey in it
631                         if (ta[id][0].length > 0) {
632                                 // Is this object a object? If not assume it's the next child.
634                                 if (n.nodeName.toLowerCase() == "a") {
635                                         a = n;
636                                 } else {
637                                         a = n.childNodes[0];
638                                 }
639                                 // Don't add an accesskey for the watch tab if the watch
640                                 // checkbox is also available.
641                                 if (a && ((id != 'ca-watch' && id != 'ca-unwatch') || !watchCheckboxExists)) {
642                                         a.accessKey = ta[id][0];
643                                         ak = ' ['+tooltipAccessKeyPrefix+ta[id][0]+']';
644                                 }
645                         } else {
646                                 // We don't care what type the object is when assigning tooltip
647                                 a = n;
648                                 ak = '';
649                         }
651                         if (a) {
652                                 a.title = ta[id][1]+ak;
653                         }
654                 }
655         }
658 function setupRightClickEdit() {
659         if (document.getElementsByTagName) {
660                 var spans = document.getElementsByTagName('span');
661                 for (var i = 0; i < spans.length; i++) {
662                         var el = spans[i];
663                         if(el.className == 'editsection') {
664                                 addRightClickEditHandler(el);
665                         }
666                 }
667         }
670 function addRightClickEditHandler(el) {
671         for (var i = 0; i < el.childNodes.length; i++) {
672                 var link = el.childNodes[i];
673                 if (link.nodeType == 1 && link.nodeName.toLowerCase() == 'a') {
674                         var editHref = link.getAttribute('href');
675                         // find the enclosing (parent) header
676                         var prev = el.parentNode;
677                         if (prev && prev.nodeType == 1 &&
678                         prev.nodeName.match(/^[Hh][1-6]$/)) {
679                                 prev.oncontextmenu = function(e) {
680                                         if (!e) { e = window.event; }
681                                         // e is now the event in all browsers
682                                         var targ;
683                                         if (e.target) { targ = e.target; }
684                                         else if (e.srcElement) { targ = e.srcElement; }
685                                         if (targ.nodeType == 3) { // defeat Safari bug
686                                                 targ = targ.parentNode;
687                                         }
688                                         // targ is now the target element
690                                         // We don't want to deprive the noble reader of a context menu
691                                         // for the section edit link, do we?  (Might want to extend this
692                                         // to all <a>'s?)
693                                         if (targ.nodeName.toLowerCase() != 'a'
694                                         || targ.parentNode.className != 'editsection') {
695                                                 document.location = editHref;
696                                                 return false;
697                                         }
698                                         return true;
699                                 };
700                         }
701                 }
702         }
705 var checkboxes;
706 var lastCheckbox;
708 function setupCheckboxShiftClick() {
709         checkboxes = [];
710         lastCheckbox = null;
711         var inputs = document.getElementsByTagName('input');
712         addCheckboxClickHandlers(inputs);
715 function addCheckboxClickHandlers(inputs, start) {
716         if ( !start) start = 0;
718         var finish = start + 250;
719         if ( finish > inputs.length )
720                 finish = inputs.length;
722         for ( var i = start; i < finish; i++ ) {
723                 var cb = inputs[i];
724                 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' )
725                         continue;
726                 var end = checkboxes.length;
727                 checkboxes[end] = cb;
728                 cb.index = end;
729                 cb.onclick = checkboxClickHandler;
730         }
732         if ( finish < inputs.length ) {
733                 setTimeout( function () {
734                         addCheckboxClickHandlers(inputs, finish);
735                 }, 200 );
736         }
739 function checkboxClickHandler(e) {
740         if (typeof e == 'undefined') {
741                 e = window.event;
742         }
743         if ( !e.shiftKey || lastCheckbox === null ) {
744                 lastCheckbox = this.index;
745                 return true;
746         }
747         var endState = this.checked;
748         var start, finish;
749         if ( this.index < lastCheckbox ) {
750                 start = this.index + 1;
751                 finish = lastCheckbox;
752         } else {
753                 start = lastCheckbox;
754                 finish = this.index - 1;
755         }
756         for (var i = start; i <= finish; ++i ) {
757                 checkboxes[i].checked = endState;
758         }
759         lastCheckbox = this.index;
760         return true;
763 function toggle_element_activation(ida,idb) {
764         if (!document.getElementById) {
765                 return;
766         }
767         document.getElementById(ida).disabled=true;
768         document.getElementById(idb).disabled=false;
771 function toggle_element_check(ida,idb) {
772         if (!document.getElementById) {
773                 return;
774         }
775         document.getElementById(ida).checked=true;
776         document.getElementById(idb).checked=false;
780  * Restore the edit box scroll state following a preview operation,
781  * and set up a form submission handler to remember this state
782  */
783 function scrollEditBox() {
784         var editBox = document.getElementById( 'wpTextbox1' );
785         var scrollTop = document.getElementById( 'wpScrolltop' );
786         var editForm = document.getElementById( 'editform' );
787         if( editBox && scrollTop ) {
788                 if( scrollTop.value )
789                         editBox.scrollTop = scrollTop.value;
790                 addHandler( editForm, 'submit', function() {
791                         document.getElementById( 'wpScrolltop' ).value = document.getElementById( 'wpTextbox1' ).scrollTop; 
792                 } );
793         }
795 hookEvent( 'load', scrollEditBox );
797 var allmessages_nodelist = false;
798 var allmessages_modified = false;
799 var allmessages_timeout = false;
800 var allmessages_running = false;
802 function allmessagesmodified() {
803         allmessages_modified = !allmessages_modified;
804         allmessagesfilter();
807 function allmessagesfilter() {
808         if ( allmessages_timeout )
809                 window.clearTimeout( allmessages_timeout );
811         if ( !allmessages_running )
812                 allmessages_timeout = window.setTimeout( 'allmessagesfilter_do();', 500 );
815 function allmessagesfilter_do() {
816         if ( !allmessages_nodelist )
817                 return;
819         var text = document.getElementById('allmessagesinput').value;
820         var nodef = allmessages_modified;
822         allmessages_running = true;
824         for ( var name in allmessages_nodelist ) {
825                 var nodes = allmessages_nodelist[name];
826                 var display = ( name.indexOf( text ) == -1 ? 'none' : '' );
828                 for ( var i = 0; i < nodes.length; i++)
829                         nodes[i].style.display =
830                                 ( nodes[i].className == "def" && nodef
831                                   ? 'none' : display );
832         }
834         if ( text != document.getElementById('allmessagesinput').value ||
835              nodef != allmessages_modified )
836                 allmessagesfilter_do();  // repeat
838         allmessages_running = false;
841 function allmessagesfilter_init() {
842         if ( allmessages_nodelist )
843                 return;
845         var nodelist = new Array();
846         var templist = new Array();
848         var table = document.getElementById('allmessagestable');
849         if ( !table ) return;
851         var rows = document.getElementsByTagName('tr');
852         for ( var i = 0; i < rows.length; i++ ) {
853                 var id = rows[i].getAttribute('id')
854                 if ( id && id.substring(0,16) != 'sp-allmessages-r' ) continue;
855                 templist[ id ] = rows[i];
856         }
858         var spans = table.getElementsByTagName('span');
859         for ( var i = 0; i < spans.length; i++ ) {
860                 var id = spans[i].getAttribute('id')
861                 if ( id && id.substring(0,17) != 'sp-allmessages-i-' ) continue;
862                 if ( !spans[i].firstChild || spans[i].firstChild.nodeType != 3 ) continue;
864                 var nodes = new Array();
865                 var row1 = templist[ id.replace('i', 'r1') ];
866                 var row2 = templist[ id.replace('i', 'r2') ];
868                 if ( row1 ) nodes[nodes.length] = row1;
869                 if ( row2 ) nodes[nodes.length] = row2;
870                 nodelist[ spans[i].firstChild.nodeValue ] = nodes;
871         }
873         var k = document.getElementById('allmessagesfilter');
874         if (k) { k.style.display = ''; }
876         allmessages_nodelist = nodelist;
879 hookEvent( "load", allmessagesfilter_init );
882         Written by Jonathan Snook, http://www.snook.ca/jonathan
883         Add-ons by Robert Nyman, http://www.robertnyman.com
884         Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
885         From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
887 function getElementsByClassName(oElm, strTagName, oClassNames){
888         var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
889         var arrReturnElements = new Array();
890         var arrRegExpClassNames = new Array();
891         if(typeof oClassNames == "object"){
892                 for(var i=0; i<oClassNames.length; i++){
893                         arrRegExpClassNames[arrRegExpClassNames.length] =
894                                 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
895                 }
896         }
897         else{
898                 arrRegExpClassNames[arrRegExpClassNames.length] =
899                         new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
900         }
901         var oElement;
902         var bMatchesAll;
903         for(var j=0; j<arrElements.length; j++){
904                 oElement = arrElements[j];
905                 bMatchesAll = true;
906                 for(var k=0; k<arrRegExpClassNames.length; k++){
907                         if(!arrRegExpClassNames[k].test(oElement.className)){
908                                 bMatchesAll = false;
909                                 break;
910                         }
911                 }
912                 if(bMatchesAll){
913                         arrReturnElements[arrReturnElements.length] = oElement;
914                 }
915         }
916         return (arrReturnElements)
919 function redirectToFragment(fragment) {
920         var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
921         if (match) {
922                 var webKitVersion = parseInt(match[1]);
923                 if (webKitVersion < 420) {
924                         // Released Safari w/ WebKit 418.9.1 messes up horribly
925                         // Nightlies of 420+ are ok
926                         return;
927                 }
928         }
929         if (is_gecko) {
930                 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
931                 addOnloadHook(function () {
932                         if (window.location.hash == "")
933                                 window.location.hash = fragment;
934                 });
935         } else {
936                 if (window.location.hash == "")
937                         window.location.hash = fragment;
938         }
942  * Table sorting script  by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
943  * Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
944  * Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .
946  * Copyright (c) 1997-2006 Stuart Langridge, Joost de Valk.
948  * @todo don't break on colspans/rowspans (bug 8028)
949  * @todo language-specific digit grouping/decimals (bug 8063)
950  * @todo support all accepted date formats (bug 8226)
951  */
953 var ts_image_path = stylepath+"/common/images/";
954 var ts_image_up = "sort_up.gif";
955 var ts_image_down = "sort_down.gif";
956 var ts_image_none = "sort_none.gif";
957 var ts_europeandate = wgContentLanguage != "en"; // The non-American-inclined can change to "true"
958 var ts_alternate_row_colors = true;
959 var SORT_COLUMN_INDEX;
961 function sortables_init() {
962         var idnum = 0;
963         // Find all tables with class sortable and make them sortable
964         var tables = getElementsByClassName(document, "table", "sortable");
965         for (var ti = 0; ti < tables.length ; ti++) {
966                 if (!tables[ti].id) {
967                         tables[ti].setAttribute('id','sortable_table_id_'+idnum);
968                         ++idnum;
969                 }
970                 ts_makeSortable(tables[ti]);
971         }
974 function ts_makeSortable(table) {
975         var firstRow;
976         if (table.rows && table.rows.length > 0) {
977                 if (table.tHead && table.tHead.rows.length > 0) {
978                         firstRow = table.tHead.rows[table.tHead.rows.length-1];
979                 } else {
980                         firstRow = table.rows[0];
981                 }
982         }
983         if (!firstRow) return;
985         // We have a first row: assume it's the header, and make its contents clickable links
986         for (var i = 0; i < firstRow.cells.length; i++) {
987                 var cell = firstRow.cells[i];
988                 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
989                         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>';
990                 }
991         }
992         if (ts_alternate_row_colors) {
993                 ts_alternate(table);
994         }
997 function ts_getInnerText(el) {
998         if (typeof el == "string") return el;
999         if (typeof el == "undefined") { return el };
1000         if (el.textContent) return el.textContent; // not needed but it is faster
1001         if (el.innerText) return el.innerText;     // IE doesn't have textContent
1002         var str = "";
1004         var cs = el.childNodes;
1005         var l = cs.length;
1006         for (var i = 0; i < l; i++) {
1007                 switch (cs[i].nodeType) {
1008                         case 1: //ELEMENT_NODE
1009                                 str += ts_getInnerText(cs[i]);
1010                                 break;
1011                         case 3: //TEXT_NODE
1012                                 str += cs[i].nodeValue;
1013                                 break;
1014                 }
1015         }
1016         return str;
1019 function ts_resortTable(lnk) {
1020         // get the span
1021         var span = lnk.getElementsByTagName('span')[0];
1023         var td = lnk.parentNode;
1024         var tr = td.parentNode;
1025         var column = td.cellIndex;
1027         var table = tr.parentNode;
1028         while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
1029                 table = table.parentNode;
1030         if (!table) return;
1032         // Work out a type for the column
1033         if (table.rows.length <= 1) return;
1035         // Skip the first row if that's where the headings are
1036         var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
1038         var itm = "";
1039         for (var i = rowStart; i < table.rows.length; i++) {
1040                 if (table.rows[i].cells.length > column) {
1041                         itm = ts_getInnerText(table.rows[i].cells[column]);
1042                         itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
1043                         if (itm != "") break;
1044                 }
1045         }
1047         sortfn = ts_sort_caseinsensitive;
1048         if (itm.match(/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/))
1049                 sortfn = ts_sort_date;
1050         if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/))
1051                 sortfn = ts_sort_date;
1052         if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d$/))
1053                 sortfn = ts_sort_date;
1054         if (itm.match(/^[\u00a3$\u20ac]/)) // pound dollar euro
1055                 sortfn = ts_sort_currency;
1056         if (itm.match(/^[\d.,]+\%?$/))
1057                 sortfn = ts_sort_numeric;
1059         var reverse = (span.getAttribute("sortdir") == 'down');
1061         var newRows = new Array();
1062         for (var j = rowStart; j < table.rows.length; j++) {
1063                 var row = table.rows[j];
1064                 var keyText = ts_getInnerText(row.cells[column]);
1065                 var oldIndex = (reverse ? -j : j);
1067                 newRows[newRows.length] = new Array(row, keyText, oldIndex);
1068         }
1070         newRows.sort(sortfn);
1072         var arrowHTML;
1073         if (reverse) {
1074                         arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
1075                         newRows.reverse();
1076                         span.setAttribute('sortdir','up');
1077         } else {
1078                         arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
1079                         span.setAttribute('sortdir','down');
1080         }
1082         // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
1083         // don't do sortbottom rows
1084         for (var i = 0; i < newRows.length; i++) {
1085                 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
1086                         table.tBodies[0].appendChild(newRows[i][0]);
1087         }
1088         // do sortbottom rows only
1089         for (var i = 0; i < newRows.length; i++) {
1090                 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
1091                         table.tBodies[0].appendChild(newRows[i][0]);
1092         }
1094         // Delete any other arrows there may be showing
1095         var spans = getElementsByClassName(tr, "span", "sortarrow");
1096         for (var i = 0; i < spans.length; i++) {
1097                 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
1098         }
1099         span.innerHTML = arrowHTML;
1101         ts_alternate(table);            
1104 function ts_dateToSortKey(date) {       
1105         // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
1106         if (date.length == 11) {
1107                 switch (date.substr(3,3).toLowerCase()) {
1108                         case "jan": var month = "01"; break;
1109                         case "feb": var month = "02"; break;
1110                         case "mar": var month = "03"; break;
1111                         case "apr": var month = "04"; break;
1112                         case "may": var month = "05"; break;
1113                         case "jun": var month = "06"; break;
1114                         case "jul": var month = "07"; break;
1115                         case "aug": var month = "08"; break;
1116                         case "sep": var month = "09"; break;
1117                         case "oct": var month = "10"; break;
1118                         case "nov": var month = "11"; break;
1119                         case "dec": var month = "12"; break;
1120                         // default: var month = "00";
1121                 }
1122                 return date.substr(7,4)+month+date.substr(0,2);
1123         } else if (date.length == 10) {
1124                 if (ts_europeandate == false) {
1125                         return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
1126                 } else {
1127                         return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
1128                 }
1129         } else if (date.length == 8) {
1130                 yr = date.substr(6,2);
1131                 if (parseInt(yr) < 50) { 
1132                         yr = '20'+yr; 
1133                 } else { 
1134                         yr = '19'+yr; 
1135                 }
1136                 if (ts_europeandate == true) {
1137                         return yr+date.substr(3,2)+date.substr(0,2);
1138                 } else {
1139                         return yr+date.substr(0,2)+date.substr(3,2);
1140                 }
1141         }
1142         return "00000000";
1145 function ts_parseFloat(num) {
1146         if (!num) return 0;
1147         num = parseFloat(num.replace(/,/g, ""));
1148         return (isNaN(num) ? 0 : num);
1151 function ts_sort_date(a,b) {
1152         var aa = ts_dateToSortKey(a[1]);
1153         var bb = ts_dateToSortKey(b[1]);
1154         return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1157 function ts_sort_currency(a,b) {
1158         var aa = ts_parseFloat(a[1].replace(/[^0-9.]/g,''));
1159         var bb = ts_parseFloat(b[1].replace(/[^0-9.]/g,''));
1160         return (aa != bb ? aa - bb : a[2] - b[2]);
1163 function ts_sort_numeric(a,b) {
1164         var aa = ts_parseFloat(a[1]);
1165         var bb = ts_parseFloat(b[1]);
1166         return (aa != bb ? aa - bb : a[2] - b[2]);
1169 function ts_sort_caseinsensitive(a,b) {
1170         var aa = a[1].toLowerCase();
1171         var bb = b[1].toLowerCase();
1172         return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1175 function ts_sort_default(a,b) {
1176         return (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2]);
1179 function ts_alternate(table) {
1180         // Take object table and get all it's tbodies.
1181         var tableBodies = table.getElementsByTagName("tbody");
1182         // Loop through these tbodies
1183         for (var i = 0; i < tableBodies.length; i++) {
1184                 // Take the tbody, and get all it's rows
1185                 var tableRows = tableBodies[i].getElementsByTagName("tr");
1186                 // Loop through these rows
1187                 // Start at 1 because we want to leave the heading row untouched
1188                 for (var j = 0; j < tableRows.length; j++) {
1189                         // Check if j is even, and apply classes for both possible results
1190                         var oldClasses = tableRows[j].className.split(" ");
1191                         var newClassName = "";
1192                         for (var k = 0; k < oldClasses.length; k++) {
1193                                 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
1194                                         newClassName += oldClasses[k] + " ";
1195                         }
1196                         tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
1197                 }
1198         }
1202  * End of table sorting code
1203  */
1207  * Add a cute little box at the top of the screen to inform the user of
1208  * something, replacing any preexisting message.
1210  * @param String message HTML to be put inside the right div
1211  * @param String className   Used in adding a class; should be different for each
1212  *   call to allow CSS/JS to hide different boxes.  null = no class used.
1213  * @return Boolean       True on success, false on failure
1214  */
1215 function jsMsg( message, className ) {
1216         if ( !document.getElementById ) {
1217                 return false;
1218         }
1219         // We special-case skin structures provided by the software.  Skins that
1220         // choose to abandon or significantly modify our formatting can just define
1221         // an mw-js-message div to start with.
1222         var messageDiv = document.getElementById( 'mw-js-message' );
1223         if ( !messageDiv ) {
1224                 messageDiv = document.createElement( 'div' );
1225                 if ( document.getElementById( 'column-content' )
1226                 && document.getElementById( 'content' ) ) {
1227                         // MonoBook, presumably
1228                         document.getElementById( 'content' ).insertBefore(
1229                                 messageDiv,
1230                                 document.getElementById( 'content' ).firstChild
1231                         );
1232                 } else if ( document.getElementById('content')
1233                 && document.getElementById( 'article' ) ) {
1234                         // Non-Monobook but still recognizable (old-style)
1235                         document.getElementById( 'article').insertBefore(
1236                                 messageDiv,
1237                                 document.getElementById( 'article' ).firstChild
1238                         );
1239                 } else {
1240                         return false;
1241                 }
1242         }
1244         messageDiv.setAttribute( 'id', 'mw-js-message' );
1245         if( className ) {
1246                 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
1247         }
1248         messageDiv.innerHTML = message;
1249         return true;
1253  * Inject a cute little progress spinner after the specified element
1255  * @param element Element to inject after
1256  * @param id Identifier string (for use with removeSpinner(), below)
1257  */
1258 function injectSpinner( element, id ) {
1259         var spinner = document.createElement( "img" );
1260         spinner.id = "mw-spinner-" + id;
1261         spinner.src = stylepath + "/common/images/spinner.gif";
1262         spinner.alt = spinner.title = "...";
1263         if( element.nextSibling ) {
1264                 element.parentNode.insertBefore( spinner, element.nextSibling );
1265         } else {
1266                 element.parentNode.appendChild( spinner );
1267         }
1271  * Remove a progress spinner added with injectSpinner()
1273  * @param id Identifier string
1274  */
1275 function removeSpinner( id ) {
1276         var spinner = document.getElementById( "mw-spinner-" + id );
1277         if( spinner ) {
1278                 spinner.parentNode.removeChild( spinner );
1279         }
1282 function runOnloadHook() {
1283         // don't run anything below this for non-dom browsers
1284         if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
1285                 return;
1286         }
1288         // set this before running any hooks, since any errors below
1289         // might cause the function to terminate prematurely
1290         doneOnloadHook = true;
1292         histrowinit();
1293         unhidetzbutton();
1294         tabbedprefs();
1295         updateTooltipAccessKeys( null );
1296         akeytt( null );
1297         scrollEditBox();
1298         setupCheckboxShiftClick();
1299         sortables_init();
1301         // Run any added-on functions
1302         for (var i = 0; i < onloadFuncts.length; i++) {
1303                 onloadFuncts[i]();
1304         }
1308  * Add an event handler to an element
1310  * @param Element element Element to add handler to
1311  * @param String attach Event to attach to
1312  * @param callable handler Event handler callback
1313  */
1314 function addHandler( element, attach, handler ) {
1315         if( window.addEventListener ) {
1316                 element.addEventListener( attach, handler, false );
1317         } else if( window.attachEvent ) {
1318                 element.attachEvent( 'on' + attach, handler );
1319         }
1323  * Add a click event handler to an element
1325  * @param Element element Element to add handler to
1326  * @param callable handler Event handler callback
1327  */
1328 function addClickHandler( element, handler ) {
1329         addHandler( element, 'click', handler );
1331 //note: all skins should call runOnloadHook() at the end of html output,
1332 //      so the below should be redundant. It's there just in case.
1333 hookEvent("load", runOnloadHook);
1334 hookEvent("load", mwSetupToolbar);