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