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