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