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