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