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