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