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