15cc99536edc40141f23750996b3f08a6363c92f
[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;<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>';
570 }
571 }
572 if (ts_alternate_row_colors) {
573 ts_alternate(table);
574 }
575 }
576
577 function ts_getInnerText(el) {
578 return getInnerText( el );
579 }
580
581 function ts_resortTable(lnk) {
582 // get the span
583 var span = lnk.getElementsByTagName('span')[0];
584
585 var td = lnk.parentNode;
586 var tr = td.parentNode;
587 var column = td.cellIndex;
588
589 var table = tr.parentNode;
590 while (table && !(table.tagName && table.tagName.toLowerCase() == 'table'))
591 table = table.parentNode;
592 if (!table) return;
593
594 if (table.rows.length <= 1) return;
595
596 // Generate the number transform table if it's not done already
597 if (ts_number_transform_table == null) {
598 ts_initTransformTable();
599 }
600
601 // Work out a type for the column
602 // Skip the first row if that's where the headings are
603 var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
604
605 var itm = "";
606 for (var i = rowStart; i < table.rows.length; i++) {
607 if (table.rows[i].cells.length > column) {
608 itm = ts_getInnerText(table.rows[i].cells[column]);
609 itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
610 if (itm != "") break;
611 }
612 }
613
614 // TODO: bug 8226, localised date formats
615 var sortfn = ts_sort_generic;
616 var preprocessor = ts_toLowerCase;
617 if (/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test(itm)) {
618 preprocessor = ts_dateToSortKey;
619 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test(itm)) {
620 preprocessor = ts_dateToSortKey;
621 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d$/.test(itm)) {
622 preprocessor = ts_dateToSortKey;
623 // pound dollar euro yen currency cents
624 } else if (/(^[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test(itm)) {
625 preprocessor = ts_currencyToSortKey;
626 } else if (ts_number_regex.test(itm)) {
627 preprocessor = ts_parseFloat;
628 }
629
630 var reverse = (span.getAttribute("sortdir") == 'down');
631
632 var newRows = new Array();
633 for (var j = rowStart; j < table.rows.length; j++) {
634 var row = table.rows[j];
635 var keyText = ts_getInnerText(row.cells[column]);
636 var oldIndex = (reverse ? -j : j);
637 var preprocessed = preprocessor( keyText );
638
639 newRows[newRows.length] = new Array(row, preprocessed, oldIndex);
640 }
641
642 newRows.sort(sortfn);
643
644 var arrowHTML;
645 if (reverse) {
646 arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
647 newRows.reverse();
648 span.setAttribute('sortdir','up');
649 } else {
650 arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
651 span.setAttribute('sortdir','down');
652 }
653
654 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
655 // don't do sortbottom rows
656 for (var i = 0; i < newRows.length; i++) {
657 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
658 table.tBodies[0].appendChild(newRows[i][0]);
659 }
660 // do sortbottom rows only
661 for (var i = 0; i < newRows.length; i++) {
662 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
663 table.tBodies[0].appendChild(newRows[i][0]);
664 }
665
666 // Delete any other arrows there may be showing
667 var spans = getElementsByClassName(tr, "span", "sortarrow");
668 for (var i = 0; i < spans.length; i++) {
669 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
670 }
671 span.innerHTML = arrowHTML;
672
673 if (ts_alternate_row_colors) {
674 ts_alternate(table);
675 }
676 }
677
678 function ts_initTransformTable() {
679 if ( typeof wgSeparatorTransformTable == "undefined"
680 || ( wgSeparatorTransformTable[0] == '' && wgDigitTransformTable[2] == '' ) )
681 {
682 digitClass = "[0-9,.]";
683 ts_number_transform_table = false;
684 } else {
685 ts_number_transform_table = {};
686 // Unpack the transform table
687 // Separators
688 ascii = wgSeparatorTransformTable[0].split("\t");
689 localised = wgSeparatorTransformTable[1].split("\t");
690 for ( var i = 0; i < ascii.length; i++ ) {
691 ts_number_transform_table[localised[i]] = ascii[i];
692 }
693 // Digits
694 ascii = wgDigitTransformTable[0].split("\t");
695 localised = wgDigitTransformTable[1].split("\t");
696 for ( var i = 0; i < ascii.length; i++ ) {
697 ts_number_transform_table[localised[i]] = ascii[i];
698 }
699
700 // Construct regex for number identification
701 digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\\.'];
702 maxDigitLength = 1;
703 for ( var digit in ts_number_transform_table ) {
704 // Escape regex metacharacters
705 digits.push(
706 digit.replace( /[\\\\$\*\+\?\.\(\)\|\{\}\[\]\-]/,
707 function( s ) { return '\\' + s; } )
708 );
709 if (digit.length > maxDigitLength) {
710 maxDigitLength = digit.length;
711 }
712 }
713 if ( maxDigitLength > 1 ) {
714 digitClass = '[' + digits.join( '', digits ) + ']';
715 } else {
716 digitClass = '(' + digits.join( '|', digits ) + ')';
717 }
718 }
719
720 // We allow a trailing percent sign, which we just strip. This works fine
721 // if percents and regular numbers aren't being mixed.
722 ts_number_regex = new RegExp(
723 "^(" +
724 "[+-]?[0-9][0-9,]*(\\.[0-9,]*)?(E[+-]?[0-9][0-9,]*)?" + // Fortran-style scientific
725 "|" +
726 "[+-]?" + digitClass + "+%?" + // Generic localised
727 ")$", "i"
728 );
729 }
730
731 function ts_toLowerCase( s ) {
732 return s.toLowerCase();
733 }
734
735 function ts_dateToSortKey(date) {
736 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
737 if (date.length == 11) {
738 switch (date.substr(3,3).toLowerCase()) {
739 case "jan": var month = "01"; break;
740 case "feb": var month = "02"; break;
741 case "mar": var month = "03"; break;
742 case "apr": var month = "04"; break;
743 case "may": var month = "05"; break;
744 case "jun": var month = "06"; break;
745 case "jul": var month = "07"; break;
746 case "aug": var month = "08"; break;
747 case "sep": var month = "09"; break;
748 case "oct": var month = "10"; break;
749 case "nov": var month = "11"; break;
750 case "dec": var month = "12"; break;
751 // default: var month = "00";
752 }
753 return date.substr(7,4)+month+date.substr(0,2);
754 } else if (date.length == 10) {
755 if (ts_europeandate == false) {
756 return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
757 } else {
758 return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
759 }
760 } else if (date.length == 8) {
761 yr = date.substr(6,2);
762 if (parseInt(yr) < 50) {
763 yr = '20'+yr;
764 } else {
765 yr = '19'+yr;
766 }
767 if (ts_europeandate == true) {
768 return yr+date.substr(3,2)+date.substr(0,2);
769 } else {
770 return yr+date.substr(0,2)+date.substr(3,2);
771 }
772 }
773 return "00000000";
774 }
775
776 function ts_parseFloat( s ) {
777 if ( !s ) {
778 return 0;
779 }
780 if (ts_number_transform_table != false) {
781 var newNum = '', c;
782
783 for ( var p = 0; p < s.length; p++ ) {
784 c = s.charAt( p );
785 if (c in ts_number_transform_table) {
786 newNum += ts_number_transform_table[c];
787 } else {
788 newNum += c;
789 }
790 }
791 s = newNum;
792 }
793
794 num = parseFloat(s.replace(/,/g, ""));
795 return (isNaN(num) ? s : num);
796 }
797
798 function ts_currencyToSortKey( s ) {
799 return ts_parseFloat(s.replace(/[^0-9.,]/g,''));
800 }
801
802 function ts_sort_generic(a, b) {
803 return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2];
804 }
805
806 function ts_alternate(table) {
807 // Take object table and get all it's tbodies.
808 var tableBodies = table.getElementsByTagName("tbody");
809 // Loop through these tbodies
810 for (var i = 0; i < tableBodies.length; i++) {
811 // Take the tbody, and get all it's rows
812 var tableRows = tableBodies[i].getElementsByTagName("tr");
813 // Loop through these rows
814 // Start at 1 because we want to leave the heading row untouched
815 for (var j = 0; j < tableRows.length; j++) {
816 // Check if j is even, and apply classes for both possible results
817 var oldClasses = tableRows[j].className.split(" ");
818 var newClassName = "";
819 for (var k = 0; k < oldClasses.length; k++) {
820 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
821 newClassName += oldClasses[k] + " ";
822 }
823 tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
824 }
825 }
826 }
827
828 /*
829 * End of table sorting code
830 */
831
832
833 /**
834 * Add a cute little box at the top of the screen to inform the user of
835 * something, replacing any preexisting message.
836 *
837 * @param String -or- Dom Object message HTML to be put inside the right div
838 * @param String className Used in adding a class; should be different for each
839 * call to allow CSS/JS to hide different boxes. null = no class used.
840 * @return Boolean True on success, false on failure
841 */
842 function jsMsg( message, className ) {
843 if ( !document.getElementById ) {
844 return false;
845 }
846 // We special-case skin structures provided by the software. Skins that
847 // choose to abandon or significantly modify our formatting can just define
848 // an mw-js-message div to start with.
849 var messageDiv = document.getElementById( 'mw-js-message' );
850 if ( !messageDiv ) {
851 messageDiv = document.createElement( 'div' );
852 if ( document.getElementById( 'column-content' )
853 && document.getElementById( 'content' ) ) {
854 // MonoBook, presumably
855 document.getElementById( 'content' ).insertBefore(
856 messageDiv,
857 document.getElementById( 'content' ).firstChild
858 );
859 } else if ( document.getElementById('content')
860 && document.getElementById( 'article' ) ) {
861 // Non-Monobook but still recognizable (old-style)
862 document.getElementById( 'article').insertBefore(
863 messageDiv,
864 document.getElementById( 'article' ).firstChild
865 );
866 } else {
867 return false;
868 }
869 }
870
871 messageDiv.setAttribute( 'id', 'mw-js-message' );
872 messageDiv.style.display = 'block';
873 if( className ) {
874 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
875 }
876
877 if (typeof message === 'object') {
878 while (messageDiv.hasChildNodes()) // Remove old content
879 messageDiv.removeChild(messageDiv.firstChild);
880 messageDiv.appendChild (message); // Append new content
881 }
882 else {
883 messageDiv.innerHTML = message;
884 }
885 return true;
886 }
887
888 /**
889 * Inject a cute little progress spinner after the specified element
890 *
891 * @param element Element to inject after
892 * @param id Identifier string (for use with removeSpinner(), below)
893 */
894 function injectSpinner( element, id ) {
895 var spinner = document.createElement( "img" );
896 spinner.id = "mw-spinner-" + id;
897 spinner.src = stylepath + "/common/images/spinner.gif";
898 spinner.alt = spinner.title = "...";
899 if( element.nextSibling ) {
900 element.parentNode.insertBefore( spinner, element.nextSibling );
901 } else {
902 element.parentNode.appendChild( spinner );
903 }
904 }
905
906 /**
907 * Remove a progress spinner added with injectSpinner()
908 *
909 * @param id Identifier string
910 */
911 function removeSpinner( id ) {
912 var spinner = document.getElementById( "mw-spinner-" + id );
913 if( spinner ) {
914 spinner.parentNode.removeChild( spinner );
915 }
916 }
917
918 function runOnloadHook() {
919 // don't run anything below this for non-dom browsers
920 if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
921 return;
922 }
923
924 // set this before running any hooks, since any errors below
925 // might cause the function to terminate prematurely
926 doneOnloadHook = true;
927
928 updateTooltipAccessKeys( null );
929 akeytt( null );
930 setupCheckboxShiftClick();
931 sortables_init();
932
933 // Run any added-on functions
934 for (var i = 0; i < onloadFuncts.length; i++) {
935 onloadFuncts[i]();
936 }
937 }
938
939 /**
940 * Add an event handler to an element
941 *
942 * @param Element element Element to add handler to
943 * @param String attach Event to attach to
944 * @param callable handler Event handler callback
945 */
946 function addHandler( element, attach, handler ) {
947 if( window.addEventListener ) {
948 element.addEventListener( attach, handler, false );
949 } else if( window.attachEvent ) {
950 element.attachEvent( 'on' + attach, handler );
951 }
952 }
953
954 /**
955 * Add a click event handler to an element
956 *
957 * @param Element element Element to add handler to
958 * @param callable handler Event handler callback
959 */
960 function addClickHandler( element, handler ) {
961 addHandler( element, 'click', handler );
962 }
963
964 /**
965 * Removes an event handler from an element
966 *
967 * @param Element element Element to remove handler from
968 * @param String remove Event to remove
969 * @param callable handler Event handler callback to remove
970 */
971 function removeHandler( element, remove, handler ) {
972 if( window.removeEventListener ) {
973 element.removeEventListener( remove, handler, false );
974 } else if( window.detachEvent ) {
975 element.detachEvent( 'on' + remove, handler );
976 }
977 }
978 //note: all skins should call runOnloadHook() at the end of html output,
979 // so the below should be redundant. It's there just in case.
980 hookEvent("load", runOnloadHook);