* Added complimentary function for addHandler() called removeHandler() for removing...
[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
293 /**
294 * Set up accesskeys/tooltips from the deprecated ta array. If doId
295 * is specified, only set up for that id. Note that this function is
296 * deprecated and will not be supported indefinitely -- use
297 * updateTooltipAccessKey() instead.
298 *
299 * @param mixed doId string or null
300 */
301 function akeytt( doId ) {
302 // A lot of user scripts (and some of the code below) break if
303 // ta isn't defined, so we make sure it is. Explictly using
304 // window.ta avoids a "ta is not defined" error.
305 if (!window.ta) window.ta = new Array;
306
307 // Make a local, possibly restricted, copy to avoid clobbering
308 // the original.
309 var ta;
310 if ( doId ) {
311 ta = [doId];
312 } else {
313 ta = window.ta;
314 }
315
316 // Now deal with evil deprecated ta
317 var watchCheckboxExists = document.getElementById( 'wpWatchthis' ) ? true : false;
318 for (var id in ta) {
319 var n = document.getElementById(id);
320 if (n) {
321 var a = null;
322 var ak = '';
323 // Are we putting accesskey in it
324 if (ta[id][0].length > 0) {
325 // Is this object a object? If not assume it's the next child.
326
327 if (n.nodeName.toLowerCase() == "a") {
328 a = n;
329 } else {
330 a = n.childNodes[0];
331 }
332 // Don't add an accesskey for the watch tab if the watch
333 // checkbox is also available.
334 if (a && ((id != 'ca-watch' && id != 'ca-unwatch') || !watchCheckboxExists)) {
335 a.accessKey = ta[id][0];
336 ak = ' ['+tooltipAccessKeyPrefix+ta[id][0]+']';
337 }
338 } else {
339 // We don't care what type the object is when assigning tooltip
340 a = n;
341 ak = '';
342 }
343
344 if (a) {
345 a.title = ta[id][1]+ak;
346 }
347 }
348 }
349 }
350
351 var checkboxes;
352 var lastCheckbox;
353
354 function setupCheckboxShiftClick() {
355 checkboxes = [];
356 lastCheckbox = null;
357 var inputs = document.getElementsByTagName('input');
358 addCheckboxClickHandlers(inputs);
359 }
360
361 function addCheckboxClickHandlers(inputs, start) {
362 if ( !start) start = 0;
363
364 var finish = start + 250;
365 if ( finish > inputs.length )
366 finish = inputs.length;
367
368 for ( var i = start; i < finish; i++ ) {
369 var cb = inputs[i];
370 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' )
371 continue;
372 var end = checkboxes.length;
373 checkboxes[end] = cb;
374 cb.index = end;
375 cb.onclick = checkboxClickHandler;
376 }
377
378 if ( finish < inputs.length ) {
379 setTimeout( function () {
380 addCheckboxClickHandlers(inputs, finish);
381 }, 200 );
382 }
383 }
384
385 function checkboxClickHandler(e) {
386 if (typeof e == 'undefined') {
387 e = window.event;
388 }
389 if ( !e.shiftKey || lastCheckbox === null ) {
390 lastCheckbox = this.index;
391 return true;
392 }
393 var endState = this.checked;
394 var start, finish;
395 if ( this.index < lastCheckbox ) {
396 start = this.index + 1;
397 finish = lastCheckbox;
398 } else {
399 start = lastCheckbox;
400 finish = this.index - 1;
401 }
402 for (var i = start; i <= finish; ++i ) {
403 checkboxes[i].checked = endState;
404 }
405 lastCheckbox = this.index;
406 return true;
407 }
408
409 function toggle_element_activation(ida,idb) {
410 if (!document.getElementById) {
411 return;
412 }
413 document.getElementById(ida).disabled=true;
414 document.getElementById(idb).disabled=false;
415 }
416
417 function toggle_element_check(ida,idb) {
418 if (!document.getElementById) {
419 return;
420 }
421 document.getElementById(ida).checked=true;
422 document.getElementById(idb).checked=false;
423 }
424
425 /*
426 Written by Jonathan Snook, http://www.snook.ca/jonathan
427 Add-ons by Robert Nyman, http://www.robertnyman.com
428 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
429 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
430 */
431 function getElementsByClassName(oElm, strTagName, oClassNames){
432 var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
433 var arrReturnElements = new Array();
434 var arrRegExpClassNames = new Array();
435 if(typeof oClassNames == "object"){
436 for(var i=0; i<oClassNames.length; i++){
437 arrRegExpClassNames[arrRegExpClassNames.length] =
438 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
439 }
440 }
441 else{
442 arrRegExpClassNames[arrRegExpClassNames.length] =
443 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
444 }
445 var oElement;
446 var bMatchesAll;
447 for(var j=0; j<arrElements.length; j++){
448 oElement = arrElements[j];
449 bMatchesAll = true;
450 for(var k=0; k<arrRegExpClassNames.length; k++){
451 if(!arrRegExpClassNames[k].test(oElement.className)){
452 bMatchesAll = false;
453 break;
454 }
455 }
456 if(bMatchesAll){
457 arrReturnElements[arrReturnElements.length] = oElement;
458 }
459 }
460 return (arrReturnElements)
461 }
462
463 function redirectToFragment(fragment) {
464 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
465 if (match) {
466 var webKitVersion = parseInt(match[1]);
467 if (webKitVersion < 420) {
468 // Released Safari w/ WebKit 418.9.1 messes up horribly
469 // Nightlies of 420+ are ok
470 return;
471 }
472 }
473 if (is_gecko) {
474 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
475 addOnloadHook(function () {
476 if (window.location.hash == "")
477 window.location.hash = fragment;
478 });
479 } else {
480 if (window.location.hash == "")
481 window.location.hash = fragment;
482 }
483 }
484
485 /*
486 * Table sorting script based on one (c) 1997-2006 Stuart Langridge and Joost
487 * de Valk:
488 * http://www.joostdevalk.nl/code/sortable-table/
489 * http://www.kryogenix.org/code/browser/sorttable/
490 *
491 * @todo don't break on colspans/rowspans (bug 8028)
492 * @todo language-specific digit grouping/decimals (bug 8063)
493 * @todo support all accepted date formats (bug 8226)
494 */
495
496 var ts_image_path = stylepath+"/common/images/";
497 var ts_image_up = "sort_up.gif";
498 var ts_image_down = "sort_down.gif";
499 var ts_image_none = "sort_none.gif";
500 var ts_europeandate = wgContentLanguage != "en"; // The non-American-inclined can change to "true"
501 var ts_alternate_row_colors = false;
502 var ts_number_transform_table = null;
503 var ts_number_regex = null;
504
505 function sortables_init() {
506 var idnum = 0;
507 // Find all tables with class sortable and make them sortable
508 var tables = getElementsByClassName(document, "table", "sortable");
509 for (var ti = 0; ti < tables.length ; ti++) {
510 if (!tables[ti].id) {
511 tables[ti].setAttribute('id','sortable_table_id_'+idnum);
512 ++idnum;
513 }
514 ts_makeSortable(tables[ti]);
515 }
516 }
517
518 function ts_makeSortable(table) {
519 var firstRow;
520 if (table.rows && table.rows.length > 0) {
521 if (table.tHead && table.tHead.rows.length > 0) {
522 firstRow = table.tHead.rows[table.tHead.rows.length-1];
523 } else {
524 firstRow = table.rows[0];
525 }
526 }
527 if (!firstRow) return;
528
529 // We have a first row: assume it's the header, and make its contents clickable links
530 for (var i = 0; i < firstRow.cells.length; i++) {
531 var cell = firstRow.cells[i];
532 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
533 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>';
534 }
535 }
536 if (ts_alternate_row_colors) {
537 ts_alternate(table);
538 }
539 }
540
541 function ts_getInnerText(el) {
542 if (typeof el == "string") return el;
543 if (typeof el == "undefined") { return el };
544 if (el.textContent) return el.textContent; // not needed but it is faster
545 if (el.innerText) return el.innerText; // IE doesn't have textContent
546 var str = "";
547
548 var cs = el.childNodes;
549 var l = cs.length;
550 for (var i = 0; i < l; i++) {
551 switch (cs[i].nodeType) {
552 case 1: //ELEMENT_NODE
553 str += ts_getInnerText(cs[i]);
554 break;
555 case 3: //TEXT_NODE
556 str += cs[i].nodeValue;
557 break;
558 }
559 }
560 return str;
561 }
562
563 function ts_resortTable(lnk) {
564 // get the span
565 var span = lnk.getElementsByTagName('span')[0];
566
567 var td = lnk.parentNode;
568 var tr = td.parentNode;
569 var column = td.cellIndex;
570
571 var table = tr.parentNode;
572 while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
573 table = table.parentNode;
574 if (!table) return;
575
576 if (table.rows.length <= 1) return;
577
578 // Generate the number transform table if it's not done already
579 if (ts_number_transform_table == null) {
580 ts_initTransformTable();
581 }
582
583 // Work out a type for the column
584 // Skip the first row if that's where the headings are
585 var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
586
587 var itm = "";
588 for (var i = rowStart; i < table.rows.length; i++) {
589 if (table.rows[i].cells.length > column) {
590 itm = ts_getInnerText(table.rows[i].cells[column]);
591 itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
592 if (itm != "") break;
593 }
594 }
595
596 // TODO: bug 8226, localised date formats
597 var sortfn = ts_sort_generic;
598 var preprocessor = ts_toLowerCase;
599 if (/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test(itm)) {
600 preprocessor = ts_dateToSortKey;
601 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test(itm)) {
602 preprocessor = ts_dateToSortKey;
603 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d$/.test(itm)) {
604 preprocessor = ts_dateToSortKey;
605 // pound dollar euro yen currency cents
606 } else if (/(^[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test(itm)) {
607 preprocessor = ts_currencyToSortKey;
608 } else if (ts_number_regex.test(itm)) {
609 preprocessor = ts_parseFloat;
610 }
611
612 var reverse = (span.getAttribute("sortdir") == 'down');
613
614 var newRows = new Array();
615 for (var j = rowStart; j < table.rows.length; j++) {
616 var row = table.rows[j];
617 var keyText = ts_getInnerText(row.cells[column]);
618 var oldIndex = (reverse ? -j : j);
619 var preprocessed = preprocessor( keyText );
620
621 newRows[newRows.length] = new Array(row, preprocessed, oldIndex);
622 }
623
624 newRows.sort(sortfn);
625
626 var arrowHTML;
627 if (reverse) {
628 arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
629 newRows.reverse();
630 span.setAttribute('sortdir','up');
631 } else {
632 arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
633 span.setAttribute('sortdir','down');
634 }
635
636 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
637 // don't do sortbottom rows
638 for (var i = 0; i < newRows.length; i++) {
639 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
640 table.tBodies[0].appendChild(newRows[i][0]);
641 }
642 // do sortbottom rows only
643 for (var i = 0; i < newRows.length; i++) {
644 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
645 table.tBodies[0].appendChild(newRows[i][0]);
646 }
647
648 // Delete any other arrows there may be showing
649 var spans = getElementsByClassName(tr, "span", "sortarrow");
650 for (var i = 0; i < spans.length; i++) {
651 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
652 }
653 span.innerHTML = arrowHTML;
654
655 if (ts_alternate_row_colors) {
656 ts_alternate(table);
657 }
658 }
659
660 function ts_initTransformTable() {
661 if ( typeof wgSeparatorTransformTable == "undefined"
662 || ( wgSeparatorTransformTable[0] == '' && wgDigitTransformTable[2] == '' ) )
663 {
664 digitClass = "[0-9,.]";
665 ts_number_transform_table = false;
666 } else {
667 ts_number_transform_table = {};
668 // Unpack the transform table
669 // Separators
670 ascii = wgSeparatorTransformTable[0].split("\t");
671 localised = wgSeparatorTransformTable[1].split("\t");
672 for ( var i = 0; i < ascii.length; i++ ) {
673 ts_number_transform_table[localised[i]] = ascii[i];
674 }
675 // Digits
676 ascii = wgDigitTransformTable[0].split("\t");
677 localised = wgDigitTransformTable[1].split("\t");
678 for ( var i = 0; i < ascii.length; i++ ) {
679 ts_number_transform_table[localised[i]] = ascii[i];
680 }
681
682 // Construct regex for number identification
683 digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\\.'];
684 maxDigitLength = 1;
685 for ( var digit in ts_number_transform_table ) {
686 // Escape regex metacharacters
687 digits.push(
688 digit.replace( /[\\\\$\*\+\?\.\(\)\|\{\}\[\]\-]/,
689 function( s ) { return '\\' + s; } )
690 );
691 if (digit.length > maxDigitLength) {
692 maxDigitLength = digit.length;
693 }
694 }
695 if ( maxDigitLength > 1 ) {
696 digitClass = '[' + digits.join( '', digits ) + ']';
697 } else {
698 digitClass = '(' + digits.join( '|', digits ) + ')';
699 }
700 }
701
702 // We allow a trailing percent sign, which we just strip. This works fine
703 // if percents and regular numbers aren't being mixed.
704 ts_number_regex = new RegExp(
705 "^(" +
706 "[+-]?[0-9][0-9,]*(\\.[0-9,]*)?(E[+-]?[0-9][0-9,]*)?" + // Fortran-style scientific
707 "|" +
708 "[+-]?" + digitClass + "+%?" + // Generic localised
709 ")$", "i"
710 );
711 }
712
713 function ts_toLowerCase( s ) {
714 return s.toLowerCase();
715 }
716
717 function ts_dateToSortKey(date) {
718 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
719 if (date.length == 11) {
720 switch (date.substr(3,3).toLowerCase()) {
721 case "jan": var month = "01"; break;
722 case "feb": var month = "02"; break;
723 case "mar": var month = "03"; break;
724 case "apr": var month = "04"; break;
725 case "may": var month = "05"; break;
726 case "jun": var month = "06"; break;
727 case "jul": var month = "07"; break;
728 case "aug": var month = "08"; break;
729 case "sep": var month = "09"; break;
730 case "oct": var month = "10"; break;
731 case "nov": var month = "11"; break;
732 case "dec": var month = "12"; break;
733 // default: var month = "00";
734 }
735 return date.substr(7,4)+month+date.substr(0,2);
736 } else if (date.length == 10) {
737 if (ts_europeandate == false) {
738 return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
739 } else {
740 return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
741 }
742 } else if (date.length == 8) {
743 yr = date.substr(6,2);
744 if (parseInt(yr) < 50) {
745 yr = '20'+yr;
746 } else {
747 yr = '19'+yr;
748 }
749 if (ts_europeandate == true) {
750 return yr+date.substr(3,2)+date.substr(0,2);
751 } else {
752 return yr+date.substr(0,2)+date.substr(3,2);
753 }
754 }
755 return "00000000";
756 }
757
758 function ts_parseFloat( s ) {
759 if ( !s ) {
760 return 0;
761 }
762 if (ts_number_transform_table != false) {
763 var newNum = '', c;
764
765 for ( var p = 0; p < s.length; p++ ) {
766 c = s.charAt( p );
767 if (c in ts_number_transform_table) {
768 newNum += ts_number_transform_table[c];
769 } else {
770 newNum += c;
771 }
772 }
773 s = newNum;
774 }
775
776 num = parseFloat(s.replace(/,/g, ""));
777 return (isNaN(num) ? s : num);
778 }
779
780 function ts_currencyToSortKey( s ) {
781 return ts_parseFloat(s.replace(/[^0-9.,]/g,''));
782 }
783
784 function ts_sort_generic(a, b) {
785 return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2];
786 }
787
788 function ts_alternate(table) {
789 // Take object table and get all it's tbodies.
790 var tableBodies = table.getElementsByTagName("tbody");
791 // Loop through these tbodies
792 for (var i = 0; i < tableBodies.length; i++) {
793 // Take the tbody, and get all it's rows
794 var tableRows = tableBodies[i].getElementsByTagName("tr");
795 // Loop through these rows
796 // Start at 1 because we want to leave the heading row untouched
797 for (var j = 0; j < tableRows.length; j++) {
798 // Check if j is even, and apply classes for both possible results
799 var oldClasses = tableRows[j].className.split(" ");
800 var newClassName = "";
801 for (var k = 0; k < oldClasses.length; k++) {
802 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
803 newClassName += oldClasses[k] + " ";
804 }
805 tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
806 }
807 }
808 }
809
810 /*
811 * End of table sorting code
812 */
813
814
815 /**
816 * Add a cute little box at the top of the screen to inform the user of
817 * something, replacing any preexisting message.
818 *
819 * @param String -or- Dom Object message HTML to be put inside the right div
820 * @param String className Used in adding a class; should be different for each
821 * call to allow CSS/JS to hide different boxes. null = no class used.
822 * @return Boolean True on success, false on failure
823 */
824 function jsMsg( message, className ) {
825 if ( !document.getElementById ) {
826 return false;
827 }
828 // We special-case skin structures provided by the software. Skins that
829 // choose to abandon or significantly modify our formatting can just define
830 // an mw-js-message div to start with.
831 var messageDiv = document.getElementById( 'mw-js-message' );
832 if ( !messageDiv ) {
833 messageDiv = document.createElement( 'div' );
834 if ( document.getElementById( 'column-content' )
835 && document.getElementById( 'content' ) ) {
836 // MonoBook, presumably
837 document.getElementById( 'content' ).insertBefore(
838 messageDiv,
839 document.getElementById( 'content' ).firstChild
840 );
841 } else if ( document.getElementById('content')
842 && document.getElementById( 'article' ) ) {
843 // Non-Monobook but still recognizable (old-style)
844 document.getElementById( 'article').insertBefore(
845 messageDiv,
846 document.getElementById( 'article' ).firstChild
847 );
848 } else {
849 return false;
850 }
851 }
852
853 messageDiv.setAttribute( 'id', 'mw-js-message' );
854 if( className ) {
855 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
856 }
857
858 if (typeof message === 'object') {
859 while (messageDiv.hasChildNodes()) // Remove old content
860 messageDiv.removeChild(messageDiv.firstChild);
861 messageDiv.appendChild (message); // Append new content
862 }
863 else {
864 messageDiv.innerHTML = message;
865 }
866 return true;
867 }
868
869 /**
870 * Inject a cute little progress spinner after the specified element
871 *
872 * @param element Element to inject after
873 * @param id Identifier string (for use with removeSpinner(), below)
874 */
875 function injectSpinner( element, id ) {
876 var spinner = document.createElement( "img" );
877 spinner.id = "mw-spinner-" + id;
878 spinner.src = stylepath + "/common/images/spinner.gif";
879 spinner.alt = spinner.title = "...";
880 if( element.nextSibling ) {
881 element.parentNode.insertBefore( spinner, element.nextSibling );
882 } else {
883 element.parentNode.appendChild( spinner );
884 }
885 }
886
887 /**
888 * Remove a progress spinner added with injectSpinner()
889 *
890 * @param id Identifier string
891 */
892 function removeSpinner( id ) {
893 var spinner = document.getElementById( "mw-spinner-" + id );
894 if( spinner ) {
895 spinner.parentNode.removeChild( spinner );
896 }
897 }
898
899 function runOnloadHook() {
900 // don't run anything below this for non-dom browsers
901 if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
902 return;
903 }
904
905 // set this before running any hooks, since any errors below
906 // might cause the function to terminate prematurely
907 doneOnloadHook = true;
908
909 updateTooltipAccessKeys( null );
910 akeytt( null );
911 setupCheckboxShiftClick();
912 sortables_init();
913
914 // Run any added-on functions
915 for (var i = 0; i < onloadFuncts.length; i++) {
916 onloadFuncts[i]();
917 }
918 }
919
920 /**
921 * Add an event handler to an element
922 *
923 * @param Element element Element to add handler to
924 * @param String attach Event to attach to
925 * @param callable handler Event handler callback
926 */
927 function addHandler( element, attach, handler ) {
928 if( window.addEventListener ) {
929 element.addEventListener( attach, handler, false );
930 } else if( window.attachEvent ) {
931 element.attachEvent( 'on' + attach, handler );
932 }
933 }
934
935 /**
936 * Add a click event handler to an element
937 *
938 * @param Element element Element to add handler to
939 * @param callable handler Event handler callback
940 */
941 function addClickHandler( element, handler ) {
942 addHandler( element, 'click', handler );
943 }
944
945 /**
946 * Removes an event handler from an element
947 *
948 * @param Element element Element to remove handler from
949 * @param String remove Event to remove
950 * @param callable handler Event handler callback to remove
951 */
952 function removeHandler( element, remove, handler ) {
953 if( window.removeEventListener ) {
954 element.removeEventListener( remove, handler, false );
955 } else if( window.detachEvent ) {
956 element.detachEvent( 'on' + remove, handler );
957 }
958 }
959 //note: all skins should call runOnloadHook() at the end of html output,
960 // so the below should be redundant. It's there just in case.
961 hookEvent("load", runOnloadHook);