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