Revert r34541 for the moment pending further review & discussion...
[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 var checkboxes;
465 var lastCheckbox;
466
467 function setupCheckboxShiftClick() {
468 checkboxes = [];
469 lastCheckbox = null;
470 var inputs = document.getElementsByTagName('input');
471 addCheckboxClickHandlers(inputs);
472 }
473
474 function addCheckboxClickHandlers(inputs, start) {
475 if ( !start) start = 0;
476
477 var finish = start + 250;
478 if ( finish > inputs.length )
479 finish = inputs.length;
480
481 for ( var i = start; i < finish; i++ ) {
482 var cb = inputs[i];
483 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' )
484 continue;
485 var end = checkboxes.length;
486 checkboxes[end] = cb;
487 cb.index = end;
488 cb.onclick = checkboxClickHandler;
489 }
490
491 if ( finish < inputs.length ) {
492 setTimeout( function () {
493 addCheckboxClickHandlers(inputs, finish);
494 }, 200 );
495 }
496 }
497
498 function checkboxClickHandler(e) {
499 if (typeof e == 'undefined') {
500 e = window.event;
501 }
502 if ( !e.shiftKey || lastCheckbox === null ) {
503 lastCheckbox = this.index;
504 return true;
505 }
506 var endState = this.checked;
507 var start, finish;
508 if ( this.index < lastCheckbox ) {
509 start = this.index + 1;
510 finish = lastCheckbox;
511 } else {
512 start = lastCheckbox;
513 finish = this.index - 1;
514 }
515 for (var i = start; i <= finish; ++i ) {
516 checkboxes[i].checked = endState;
517 }
518 lastCheckbox = this.index;
519 return true;
520 }
521
522 function toggle_element_activation(ida,idb) {
523 if (!document.getElementById) {
524 return;
525 }
526 document.getElementById(ida).disabled=true;
527 document.getElementById(idb).disabled=false;
528 }
529
530 function toggle_element_check(ida,idb) {
531 if (!document.getElementById) {
532 return;
533 }
534 document.getElementById(ida).checked=true;
535 document.getElementById(idb).checked=false;
536 }
537
538 /**
539 * Restore the edit box scroll state following a preview operation,
540 * and set up a form submission handler to remember this state
541 */
542 function scrollEditBox() {
543 var editBox = document.getElementById( 'wpTextbox1' );
544 var scrollTop = document.getElementById( 'wpScrolltop' );
545 var editForm = document.getElementById( 'editform' );
546 if( editBox && scrollTop ) {
547 if( scrollTop.value )
548 editBox.scrollTop = scrollTop.value;
549 addHandler( editForm, 'submit', function() {
550 document.getElementById( 'wpScrolltop' ).value = document.getElementById( 'wpTextbox1' ).scrollTop;
551 } );
552 }
553 }
554 hookEvent( 'load', scrollEditBox );
555
556 /*
557 Written by Jonathan Snook, http://www.snook.ca/jonathan
558 Add-ons by Robert Nyman, http://www.robertnyman.com
559 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
560 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
561 */
562 function getElementsByClassName(oElm, strTagName, oClassNames){
563 var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
564 var arrReturnElements = new Array();
565 var arrRegExpClassNames = new Array();
566 if(typeof oClassNames == "object"){
567 for(var i=0; i<oClassNames.length; i++){
568 arrRegExpClassNames[arrRegExpClassNames.length] =
569 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
570 }
571 }
572 else{
573 arrRegExpClassNames[arrRegExpClassNames.length] =
574 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
575 }
576 var oElement;
577 var bMatchesAll;
578 for(var j=0; j<arrElements.length; j++){
579 oElement = arrElements[j];
580 bMatchesAll = true;
581 for(var k=0; k<arrRegExpClassNames.length; k++){
582 if(!arrRegExpClassNames[k].test(oElement.className)){
583 bMatchesAll = false;
584 break;
585 }
586 }
587 if(bMatchesAll){
588 arrReturnElements[arrReturnElements.length] = oElement;
589 }
590 }
591 return (arrReturnElements)
592 }
593
594 function redirectToFragment(fragment) {
595 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
596 if (match) {
597 var webKitVersion = parseInt(match[1]);
598 if (webKitVersion < 420) {
599 // Released Safari w/ WebKit 418.9.1 messes up horribly
600 // Nightlies of 420+ are ok
601 return;
602 }
603 }
604 if (is_gecko) {
605 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
606 addOnloadHook(function () {
607 if (window.location.hash == "")
608 window.location.hash = fragment;
609 });
610 } else {
611 if (window.location.hash == "")
612 window.location.hash = fragment;
613 }
614 }
615
616 /*
617 * Table sorting script by Joost de Valk, check it out at http://www.joostdevalk.nl/code/sortable-table/.
618 * Based on a script from http://www.kryogenix.org/code/browser/sorttable/.
619 * Distributed under the MIT license: http://www.kryogenix.org/code/browser/licence.html .
620 *
621 * Copyright (c) 1997-2006 Stuart Langridge, Joost de Valk.
622 *
623 * @todo don't break on colspans/rowspans (bug 8028)
624 * @todo language-specific digit grouping/decimals (bug 8063)
625 * @todo support all accepted date formats (bug 8226)
626 */
627
628 var ts_image_path = stylepath+"/common/images/";
629 var ts_image_up = "sort_up.gif";
630 var ts_image_down = "sort_down.gif";
631 var ts_image_none = "sort_none.gif";
632 var ts_europeandate = wgContentLanguage != "en"; // The non-American-inclined can change to "true"
633 var ts_alternate_row_colors = true;
634 var SORT_COLUMN_INDEX;
635
636 function sortables_init() {
637 var idnum = 0;
638 // Find all tables with class sortable and make them sortable
639 var tables = getElementsByClassName(document, "table", "sortable");
640 for (var ti = 0; ti < tables.length ; ti++) {
641 if (!tables[ti].id) {
642 tables[ti].setAttribute('id','sortable_table_id_'+idnum);
643 ++idnum;
644 }
645 ts_makeSortable(tables[ti]);
646 }
647 }
648
649 function ts_makeSortable(table) {
650 var firstRow;
651 if (table.rows && table.rows.length > 0) {
652 if (table.tHead && table.tHead.rows.length > 0) {
653 firstRow = table.tHead.rows[table.tHead.rows.length-1];
654 } else {
655 firstRow = table.rows[0];
656 }
657 }
658 if (!firstRow) return;
659
660 // We have a first row: assume it's the header, and make its contents clickable links
661 for (var i = 0; i < firstRow.cells.length; i++) {
662 var cell = firstRow.cells[i];
663 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
664 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>';
665 }
666 }
667 if (ts_alternate_row_colors) {
668 ts_alternate(table);
669 }
670 }
671
672 function ts_getInnerText(el) {
673 if (typeof el == "string") return el;
674 if (typeof el == "undefined") { return el };
675 if (el.textContent) return el.textContent; // not needed but it is faster
676 if (el.innerText) return el.innerText; // IE doesn't have textContent
677 var str = "";
678
679 var cs = el.childNodes;
680 var l = cs.length;
681 for (var i = 0; i < l; i++) {
682 switch (cs[i].nodeType) {
683 case 1: //ELEMENT_NODE
684 str += ts_getInnerText(cs[i]);
685 break;
686 case 3: //TEXT_NODE
687 str += cs[i].nodeValue;
688 break;
689 }
690 }
691 return str;
692 }
693
694 function ts_resortTable(lnk) {
695 // get the span
696 var span = lnk.getElementsByTagName('span')[0];
697
698 var td = lnk.parentNode;
699 var tr = td.parentNode;
700 var column = td.cellIndex;
701
702 var table = tr.parentNode;
703 while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
704 table = table.parentNode;
705 if (!table) return;
706
707 // Work out a type for the column
708 if (table.rows.length <= 1) return;
709
710 // Skip the first row if that's where the headings are
711 var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
712
713 var itm = "";
714 for (var i = rowStart; i < table.rows.length; i++) {
715 if (table.rows[i].cells.length > column) {
716 itm = ts_getInnerText(table.rows[i].cells[column]);
717 itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
718 if (itm != "") break;
719 }
720 }
721
722 sortfn = ts_sort_caseinsensitive;
723 if (itm.match(/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/))
724 sortfn = ts_sort_date;
725 if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/))
726 sortfn = ts_sort_date;
727 if (itm.match(/^\d\d[\/.-]\d\d[\/.-]\d\d$/))
728 sortfn = ts_sort_date;
729 if (itm.match(/^[\u00a3$\u20ac]/)) // pound dollar euro
730 sortfn = ts_sort_currency;
731 if (itm.match(/^[\d.,]+\%?$/))
732 sortfn = ts_sort_numeric;
733
734 var reverse = (span.getAttribute("sortdir") == 'down');
735
736 var newRows = new Array();
737 for (var j = rowStart; j < table.rows.length; j++) {
738 var row = table.rows[j];
739 var keyText = ts_getInnerText(row.cells[column]);
740 var oldIndex = (reverse ? -j : j);
741
742 newRows[newRows.length] = new Array(row, keyText, oldIndex);
743 }
744
745 newRows.sort(sortfn);
746
747 var arrowHTML;
748 if (reverse) {
749 arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
750 newRows.reverse();
751 span.setAttribute('sortdir','up');
752 } else {
753 arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
754 span.setAttribute('sortdir','down');
755 }
756
757 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
758 // don't do sortbottom rows
759 for (var i = 0; i < newRows.length; i++) {
760 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
761 table.tBodies[0].appendChild(newRows[i][0]);
762 }
763 // do sortbottom rows only
764 for (var i = 0; i < newRows.length; i++) {
765 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
766 table.tBodies[0].appendChild(newRows[i][0]);
767 }
768
769 // Delete any other arrows there may be showing
770 var spans = getElementsByClassName(tr, "span", "sortarrow");
771 for (var i = 0; i < spans.length; i++) {
772 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
773 }
774 span.innerHTML = arrowHTML;
775
776 ts_alternate(table);
777 }
778
779 function ts_dateToSortKey(date) {
780 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
781 if (date.length == 11) {
782 switch (date.substr(3,3).toLowerCase()) {
783 case "jan": var month = "01"; break;
784 case "feb": var month = "02"; break;
785 case "mar": var month = "03"; break;
786 case "apr": var month = "04"; break;
787 case "may": var month = "05"; break;
788 case "jun": var month = "06"; break;
789 case "jul": var month = "07"; break;
790 case "aug": var month = "08"; break;
791 case "sep": var month = "09"; break;
792 case "oct": var month = "10"; break;
793 case "nov": var month = "11"; break;
794 case "dec": var month = "12"; break;
795 // default: var month = "00";
796 }
797 return date.substr(7,4)+month+date.substr(0,2);
798 } else if (date.length == 10) {
799 if (ts_europeandate == false) {
800 return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
801 } else {
802 return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
803 }
804 } else if (date.length == 8) {
805 yr = date.substr(6,2);
806 if (parseInt(yr) < 50) {
807 yr = '20'+yr;
808 } else {
809 yr = '19'+yr;
810 }
811 if (ts_europeandate == true) {
812 return yr+date.substr(3,2)+date.substr(0,2);
813 } else {
814 return yr+date.substr(0,2)+date.substr(3,2);
815 }
816 }
817 return "00000000";
818 }
819
820 function ts_parseFloat(num) {
821 if (!num) return 0;
822 num = parseFloat(num.replace(/,/g, ""));
823 return (isNaN(num) ? 0 : num);
824 }
825
826 function ts_sort_date(a,b) {
827 var aa = ts_dateToSortKey(a[1]);
828 var bb = ts_dateToSortKey(b[1]);
829 return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
830 }
831
832 function ts_sort_currency(a,b) {
833 var aa = ts_parseFloat(a[1].replace(/[^0-9.]/g,''));
834 var bb = ts_parseFloat(b[1].replace(/[^0-9.]/g,''));
835 return (aa != bb ? aa - bb : a[2] - b[2]);
836 }
837
838 function ts_sort_numeric(a,b) {
839 var aa = ts_parseFloat(a[1]);
840 var bb = ts_parseFloat(b[1]);
841 return (aa != bb ? aa - bb : a[2] - b[2]);
842 }
843
844 function ts_sort_caseinsensitive(a,b) {
845 var aa = a[1].toLowerCase();
846 var bb = b[1].toLowerCase();
847 return (aa < bb ? -1 : aa > bb ? 1 : a[2] - b[2]);
848 }
849
850 function ts_sort_default(a,b) {
851 return (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2]);
852 }
853
854 function ts_alternate(table) {
855 // Take object table and get all it's tbodies.
856 var tableBodies = table.getElementsByTagName("tbody");
857 // Loop through these tbodies
858 for (var i = 0; i < tableBodies.length; i++) {
859 // Take the tbody, and get all it's rows
860 var tableRows = tableBodies[i].getElementsByTagName("tr");
861 // Loop through these rows
862 // Start at 1 because we want to leave the heading row untouched
863 for (var j = 0; j < tableRows.length; j++) {
864 // Check if j is even, and apply classes for both possible results
865 var oldClasses = tableRows[j].className.split(" ");
866 var newClassName = "";
867 for (var k = 0; k < oldClasses.length; k++) {
868 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
869 newClassName += oldClasses[k] + " ";
870 }
871 tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
872 }
873 }
874 }
875
876 /*
877 * End of table sorting code
878 */
879
880
881 /**
882 * Add a cute little box at the top of the screen to inform the user of
883 * something, replacing any preexisting message.
884 *
885 * @param String message HTML to be put inside the right div
886 * @param String className Used in adding a class; should be different for each
887 * call to allow CSS/JS to hide different boxes. null = no class used.
888 * @return Boolean True on success, false on failure
889 */
890 function jsMsg( message, className ) {
891 if ( !document.getElementById ) {
892 return false;
893 }
894 // We special-case skin structures provided by the software. Skins that
895 // choose to abandon or significantly modify our formatting can just define
896 // an mw-js-message div to start with.
897 var messageDiv = document.getElementById( 'mw-js-message' );
898 if ( !messageDiv ) {
899 messageDiv = document.createElement( 'div' );
900 if ( document.getElementById( 'column-content' )
901 && document.getElementById( 'content' ) ) {
902 // MonoBook, presumably
903 document.getElementById( 'content' ).insertBefore(
904 messageDiv,
905 document.getElementById( 'content' ).firstChild
906 );
907 } else if ( document.getElementById('content')
908 && document.getElementById( 'article' ) ) {
909 // Non-Monobook but still recognizable (old-style)
910 document.getElementById( 'article').insertBefore(
911 messageDiv,
912 document.getElementById( 'article' ).firstChild
913 );
914 } else {
915 return false;
916 }
917 }
918
919 messageDiv.setAttribute( 'id', 'mw-js-message' );
920 if( className ) {
921 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
922 }
923 messageDiv.innerHTML = message;
924 return true;
925 }
926
927 /**
928 * Inject a cute little progress spinner after the specified element
929 *
930 * @param element Element to inject after
931 * @param id Identifier string (for use with removeSpinner(), below)
932 */
933 function injectSpinner( element, id ) {
934 var spinner = document.createElement( "img" );
935 spinner.id = "mw-spinner-" + id;
936 spinner.src = stylepath + "/common/images/spinner.gif";
937 spinner.alt = spinner.title = "...";
938 if( element.nextSibling ) {
939 element.parentNode.insertBefore( spinner, element.nextSibling );
940 } else {
941 element.parentNode.appendChild( spinner );
942 }
943 }
944
945 /**
946 * Remove a progress spinner added with injectSpinner()
947 *
948 * @param id Identifier string
949 */
950 function removeSpinner( id ) {
951 var spinner = document.getElementById( "mw-spinner-" + id );
952 if( spinner ) {
953 spinner.parentNode.removeChild( spinner );
954 }
955 }
956
957 function runOnloadHook() {
958 // don't run anything below this for non-dom browsers
959 if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
960 return;
961 }
962
963 // set this before running any hooks, since any errors below
964 // might cause the function to terminate prematurely
965 doneOnloadHook = true;
966
967 updateTooltipAccessKeys( null );
968 akeytt( null );
969 scrollEditBox();
970 setupCheckboxShiftClick();
971 sortables_init();
972
973 // Run any added-on functions
974 for (var i = 0; i < onloadFuncts.length; i++) {
975 onloadFuncts[i]();
976 }
977 }
978
979 /**
980 * Add an event handler to an element
981 *
982 * @param Element element Element to add handler to
983 * @param String attach Event to attach to
984 * @param callable handler Event handler callback
985 */
986 function addHandler( element, attach, handler ) {
987 if( window.addEventListener ) {
988 element.addEventListener( attach, handler, false );
989 } else if( window.attachEvent ) {
990 element.attachEvent( 'on' + attach, handler );
991 }
992 }
993
994 /**
995 * Add a click event handler to an element
996 *
997 * @param Element element Element to add handler to
998 * @param callable handler Event handler callback
999 */
1000 function addClickHandler( element, handler ) {
1001 addHandler( element, 'click', handler );
1002 }
1003 //note: all skins should call runOnloadHook() at the end of html output,
1004 // so the below should be redundant. It's there just in case.
1005 hookEvent("load", runOnloadHook);
1006 hookEvent("load", mwSetupToolbar);