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