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