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