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