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