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