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