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