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