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