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