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