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