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