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