* add OutputPage::addScriptFile() for easier adding of JS files, similar to OutputPag...
[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 /*
802 Written by Jonathan Snook, http://www.snook.ca/jonathan
803 Add-ons by Robert Nyman, http://www.robertnyman.com
804 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
805 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
806 */
807 function getElementsByClassName(oElm, strTagName, oClassNames){
808 var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
809 var arrReturnElements = new Array();
810 var arrRegExpClassNames = new Array();
811 if(typeof oClassNames == "object"){
812 for(var i=0; i<oClassNames.length; i++){
813 arrRegExpClassNames[arrRegExpClassNames.length] =
814 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
815 }
816 }
817 else{
818 arrRegExpClassNames[arrRegExpClassNames.length] =
819 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
820 }
821 var oElement;
822 var bMatchesAll;
823 for(var j=0; j<arrElements.length; j++){
824 oElement = arrElements[j];
825 bMatchesAll = true;
826 for(var k=0; k<arrRegExpClassNames.length; k++){
827 if(!arrRegExpClassNames[k].test(oElement.className)){
828 bMatchesAll = false;
829 break;
830 }
831 }
832 if(bMatchesAll){
833 arrReturnElements[arrReturnElements.length] = oElement;
834 }
835 }
836 return (arrReturnElements)
837 }
838
839 function redirectToFragment(fragment) {
840 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
841 if (match) {
842 var webKitVersion = parseInt(match[1]);
843 if (webKitVersion < 420) {
844 // Released Safari w/ WebKit 418.9.1 messes up horribly
845 // Nightlies of 420+ are ok
846 return;
847 }
848 }
849 if (is_gecko) {
850 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
851 addOnloadHook(function () {
852 if (window.location.hash == "")
853 window.location.hash = fragment;
854 });
855 } else {
856 if (window.location.hash == "")
857 window.location.hash = fragment;
858 }
859 }
860
861 /*
862 * Table sorting script by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
863 * Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
864 * Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .
865 *
866 * Copyright (c) 1997-2006 Stuart Langridge, Joost de Valk.
867 *
868 * @todo don't break on colspans/rowspans (bug 8028)
869 * @todo language-specific digit grouping/decimals (bug 8063)
870 * @todo support all accepted date formats (bug 8226)
871 */
872
873 var ts_image_path = stylepath+"/common/images/";
874 var ts_image_up = "sort_up.gif";
875 var ts_image_down = "sort_down.gif";
876 var ts_image_none = "sort_none.gif";
877 var ts_europeandate = wgContentLanguage != "en"; // The non-American-inclined can change to "true"
878 var ts_alternate_row_colors = true;
879 var SORT_COLUMN_INDEX;
880
881 function sortables_init() {
882 var idnum = 0;
883 // Find all tables with class sortable and make them sortable
884 var tables = getElementsByClassName(document, "table", "sortable");
885 for (var ti = 0; ti < tables.length ; ti++) {
886 if (!tables[ti].id) {
887 tables[ti].setAttribute('id','sortable_table_id_'+idnum);
888 ++idnum;
889 }
890 ts_makeSortable(tables[ti]);
891 }
892 }
893
894 function ts_makeSortable(table) {
895 var firstRow;
896 if (table.rows && table.rows.length > 0) {
897 if (table.tHead && table.tHead.rows.length > 0) {
898 firstRow = table.tHead.rows[table.tHead.rows.length-1];
899 } else {
900 firstRow = table.rows[0];
901 }
902 }
903 if (!firstRow) return;
904
905 // We have a first row: assume it's the header, and make its contents clickable links
906 for (var i = 0; i < firstRow.cells.length; i++) {
907 var cell = firstRow.cells[i];
908 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
909 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>';
910 }
911 }
912 if (ts_alternate_row_colors) {
913 ts_alternate(table);
914 }
915 }
916
917 function ts_getInnerText(el) {
918 if (typeof el == "string") return el;
919 if (typeof el == "undefined") { return el };
920 if (el.textContent) return el.textContent; // not needed but it is faster
921 if (el.innerText) return el.innerText; // IE doesn't have textContent
922 var str = "";
923
924 var cs = el.childNodes;
925 var l = cs.length;
926 for (var i = 0; i < l; i++) {
927 switch (cs[i].nodeType) {
928 case 1: //ELEMENT_NODE
929 str += ts_getInnerText(cs[i]);
930 break;
931 case 3: //TEXT_NODE
932 str += cs[i].nodeValue;
933 break;
934 }
935 }
936 return str;
937 }
938
939 function ts_resortTable(lnk) {
940 // get the span
941 var span = lnk.getElementsByTagName('span')[0];
942
943 var td = lnk.parentNode;
944 var tr = td.parentNode;
945 var column = td.cellIndex;
946
947 var table = tr.parentNode;
948 while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
949 table = table.parentNode;
950 if (!table) return;
951
952 // Work out a type for the column
953 if (table.rows.length <= 1) return;
954
955 // Skip the first row if that's where the headings are
956 var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
957
958 var itm = "";
959 for (var i = rowStart; i < table.rows.length; i++) {
960 if (table.rows[i].cells.length > column) {
961 itm = ts_getInnerText(table.rows[i].cells[column]);
962 itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
963 if (itm != "") break;
964 }
965 }
966
967 sortfn = ts_sort_caseinsensitive;
968 if (itm.match(/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/))
969 sortfn = ts_sort_date;
970 if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/))
971 sortfn = ts_sort_date;
972 if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d$/))
973 sortfn = ts_sort_date;
974 if (itm.match(/^[\u00a3$\u20ac]/)) // pound dollar euro
975 sortfn = ts_sort_currency;
976 if (itm.match(/^[\d.,]+\%?$/))
977 sortfn = ts_sort_numeric;
978
979 var reverse = (span.getAttribute("sortdir") == 'down');
980
981 var newRows = new Array();
982 for (var j = rowStart; j < table.rows.length; j++) {
983 var row = table.rows[j];
984 var keyText = ts_getInnerText(row.cells[column]);
985 var oldIndex = (reverse ? -j : j);
986
987 newRows[newRows.length] = new Array(row, keyText, oldIndex);
988 }
989
990 newRows.sort(sortfn);
991
992 var arrowHTML;
993 if (reverse) {
994 arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
995 newRows.reverse();
996 span.setAttribute('sortdir','up');
997 } else {
998 arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
999 span.setAttribute('sortdir','down');
1000 }
1001
1002 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
1003 // don't do sortbottom rows
1004 for (var i = 0; i < newRows.length; i++) {
1005 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
1006 table.tBodies[0].appendChild(newRows[i][0]);
1007 }
1008 // do sortbottom rows only
1009 for (var i = 0; i < newRows.length; i++) {
1010 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
1011 table.tBodies[0].appendChild(newRows[i][0]);
1012 }
1013
1014 // Delete any other arrows there may be showing
1015 var spans = getElementsByClassName(tr, "span", "sortarrow");
1016 for (var i = 0; i < spans.length; i++) {
1017 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
1018 }
1019 span.innerHTML = arrowHTML;
1020
1021 ts_alternate(table);
1022 }
1023
1024 function ts_dateToSortKey(date) {
1025 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
1026 if (date.length == 11) {
1027 switch (date.substr(3,3).toLowerCase()) {
1028 case "jan": var month = "01"; break;
1029 case "feb": var month = "02"; break;
1030 case "mar": var month = "03"; break;
1031 case "apr": var month = "04"; break;
1032 case "may": var month = "05"; break;
1033 case "jun": var month = "06"; break;
1034 case "jul": var month = "07"; break;
1035 case "aug": var month = "08"; break;
1036 case "sep": var month = "09"; break;
1037 case "oct": var month = "10"; break;
1038 case "nov": var month = "11"; break;
1039 case "dec": var month = "12"; break;
1040 // default: var month = "00";
1041 }
1042 return date.substr(7,4)+month+date.substr(0,2);
1043 } else if (date.length == 10) {
1044 if (ts_europeandate == false) {
1045 return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
1046 } else {
1047 return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
1048 }
1049 } else if (date.length == 8) {
1050 yr = date.substr(6,2);
1051 if (parseInt(yr) < 50) {
1052 yr = '20'+yr;
1053 } else {
1054 yr = '19'+yr;
1055 }
1056 if (ts_europeandate == true) {
1057 return yr+date.substr(3,2)+date.substr(0,2);
1058 } else {
1059 return yr+date.substr(0,2)+date.substr(3,2);
1060 }
1061 }
1062 return "00000000";
1063 }
1064
1065 function ts_parseFloat(num) {
1066 if (!num) return 0;
1067 num = parseFloat(num.replace(/,/g, ""));
1068 return (isNaN(num) ? 0 : num);
1069 }
1070
1071 function ts_sort_date(a,b) {
1072 var aa = ts_dateToSortKey(a[1]);
1073 var bb = ts_dateToSortKey(b[1]);
1074 return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1075 }
1076
1077 function ts_sort_currency(a,b) {
1078 var aa = ts_parseFloat(a[1].replace(/[^0-9.]/g,''));
1079 var bb = ts_parseFloat(b[1].replace(/[^0-9.]/g,''));
1080 return (aa != bb ? aa - bb : a[2] - b[2]);
1081 }
1082
1083 function ts_sort_numeric(a,b) {
1084 var aa = ts_parseFloat(a[1]);
1085 var bb = ts_parseFloat(b[1]);
1086 return (aa != bb ? aa - bb : a[2] - b[2]);
1087 }
1088
1089 function ts_sort_caseinsensitive(a,b) {
1090 var aa = a[1].toLowerCase();
1091 var bb = b[1].toLowerCase();
1092 return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
1093 }
1094
1095 function ts_sort_default(a,b) {
1096 return (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2]);
1097 }
1098
1099 function ts_alternate(table) {
1100 // Take object table and get all it's tbodies.
1101 var tableBodies = table.getElementsByTagName("tbody");
1102 // Loop through these tbodies
1103 for (var i = 0; i < tableBodies.length; i++) {
1104 // Take the tbody, and get all it's rows
1105 var tableRows = tableBodies[i].getElementsByTagName("tr");
1106 // Loop through these rows
1107 // Start at 1 because we want to leave the heading row untouched
1108 for (var j = 0; j < tableRows.length; j++) {
1109 // Check if j is even, and apply classes for both possible results
1110 var oldClasses = tableRows[j].className.split(" ");
1111 var newClassName = "";
1112 for (var k = 0; k < oldClasses.length; k++) {
1113 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
1114 newClassName += oldClasses[k] + " ";
1115 }
1116 tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
1117 }
1118 }
1119 }
1120
1121 /*
1122 * End of table sorting code
1123 */
1124
1125
1126 /**
1127 * Add a cute little box at the top of the screen to inform the user of
1128 * something, replacing any preexisting message.
1129 *
1130 * @param String message HTML to be put inside the right div
1131 * @param String className Used in adding a class; should be different for each
1132 * call to allow CSS/JS to hide different boxes. null = no class used.
1133 * @return Boolean True on success, false on failure
1134 */
1135 function jsMsg( message, className ) {
1136 if ( !document.getElementById ) {
1137 return false;
1138 }
1139 // We special-case skin structures provided by the software. Skins that
1140 // choose to abandon or significantly modify our formatting can just define
1141 // an mw-js-message div to start with.
1142 var messageDiv = document.getElementById( 'mw-js-message' );
1143 if ( !messageDiv ) {
1144 messageDiv = document.createElement( 'div' );
1145 if ( document.getElementById( 'column-content' )
1146 && document.getElementById( 'content' ) ) {
1147 // MonoBook, presumably
1148 document.getElementById( 'content' ).insertBefore(
1149 messageDiv,
1150 document.getElementById( 'content' ).firstChild
1151 );
1152 } else if ( document.getElementById('content')
1153 && document.getElementById( 'article' ) ) {
1154 // Non-Monobook but still recognizable (old-style)
1155 document.getElementById( 'article').insertBefore(
1156 messageDiv,
1157 document.getElementById( 'article' ).firstChild
1158 );
1159 } else {
1160 return false;
1161 }
1162 }
1163
1164 messageDiv.setAttribute( 'id', 'mw-js-message' );
1165 if( className ) {
1166 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
1167 }
1168 messageDiv.innerHTML = message;
1169 return true;
1170 }
1171
1172 /**
1173 * Inject a cute little progress spinner after the specified element
1174 *
1175 * @param element Element to inject after
1176 * @param id Identifier string (for use with removeSpinner(), below)
1177 */
1178 function injectSpinner( element, id ) {
1179 var spinner = document.createElement( "img" );
1180 spinner.id = "mw-spinner-" + id;
1181 spinner.src = stylepath + "/common/images/spinner.gif";
1182 spinner.alt = spinner.title = "...";
1183 if( element.nextSibling ) {
1184 element.parentNode.insertBefore( spinner, element.nextSibling );
1185 } else {
1186 element.parentNode.appendChild( spinner );
1187 }
1188 }
1189
1190 /**
1191 * Remove a progress spinner added with injectSpinner()
1192 *
1193 * @param id Identifier string
1194 */
1195 function removeSpinner( id ) {
1196 var spinner = document.getElementById( "mw-spinner-" + id );
1197 if( spinner ) {
1198 spinner.parentNode.removeChild( spinner );
1199 }
1200 }
1201
1202 function runOnloadHook() {
1203 // don't run anything below this for non-dom browsers
1204 if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
1205 return;
1206 }
1207
1208 // set this before running any hooks, since any errors below
1209 // might cause the function to terminate prematurely
1210 doneOnloadHook = true;
1211
1212 histrowinit();
1213 unhidetzbutton();
1214 tabbedprefs();
1215 updateTooltipAccessKeys( null );
1216 akeytt( null );
1217 scrollEditBox();
1218 setupCheckboxShiftClick();
1219 sortables_init();
1220
1221 // Run any added-on functions
1222 for (var i = 0; i < onloadFuncts.length; i++) {
1223 onloadFuncts[i]();
1224 }
1225 }
1226
1227 /**
1228 * Add an event handler to an element
1229 *
1230 * @param Element element Element to add handler to
1231 * @param String attach Event to attach to
1232 * @param callable handler Event handler callback
1233 */
1234 function addHandler( element, attach, handler ) {
1235 if( window.addEventListener ) {
1236 element.addEventListener( attach, handler, false );
1237 } else if( window.attachEvent ) {
1238 element.attachEvent( 'on' + attach, handler );
1239 }
1240 }
1241
1242 /**
1243 * Add a click event handler to an element
1244 *
1245 * @param Element element Element to add handler to
1246 * @param callable handler Event handler callback
1247 */
1248 function addClickHandler( element, handler ) {
1249 addHandler( element, 'click', handler );
1250 }
1251 //note: all skins should call runOnloadHook() at the end of html output,
1252 // so the below should be redundant. It's there just in case.
1253 hookEvent("load", runOnloadHook);
1254 hookEvent("load", mwSetupToolbar);