Merge IEFixes.js into wikibits.js
[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 // Start at 4 to minimize the chance of breaking on IE10 :)
29 var ie6_bugs = /msie [4-6]/.test( clientPC );
30
31 // Global external objects used by this script.
32 /*extern ta, stylepath, skin */
33
34 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
35 var doneOnloadHook;
36
37 if (!window.onloadFuncts) {
38 var onloadFuncts = [];
39 }
40
41 function addOnloadHook(hookFunct) {
42 // Allows add-on scripts to add onload functions
43 if(!doneOnloadHook) {
44 onloadFuncts[onloadFuncts.length] = hookFunct;
45 } else {
46 hookFunct(); // bug in MSIE script loading
47 }
48 }
49
50
51 function hookEvent(hookName, hookFunct) {
52 addHandler(window, hookName, hookFunct);
53 }
54
55 function importScript(page) {
56 // TODO: might want to introduce a utility function to match wfUrlencode() in PHP
57 var uri = wgScript + '?title=' +
58 encodeURIComponent(page.replace(/ /g,'_')).replace(/%2F/ig,'/').replace(/%3A/ig,':') +
59 '&action=raw&ctype=text/javascript';
60 return importScriptURI(uri);
61 }
62
63 var loadedScripts = {}; // included-scripts tracker
64 function importScriptURI(url) {
65 if (loadedScripts[url]) {
66 return null;
67 }
68 loadedScripts[url] = true;
69 var s = document.createElement('script');
70 s.setAttribute('src', url);
71 s.setAttribute('type', 'text/javascript');
72 document.getElementsByTagName('head')[0].appendChild(s);
73 return s;
74 }
75
76 function importStylesheet(page) {
77 return importStylesheetURI(wgScript + '?action=raw&ctype=text/css&title=' + encodeURIComponent(page.replace(/ /g,'_')));
78 }
79
80 function importStylesheetURI(url, media) {
81 var l = document.createElement('link');
82 l.type = 'text/css';
83 l.rel = 'stylesheet';
84 l.href = url;
85 if( media ) {
86 l.media = media;
87 }
88 document.getElementsByTagName('head')[0].appendChild(l);
89 return l;
90 }
91
92 function appendCSS(text) {
93 var s = document.createElement('style');
94 s.type = 'text/css';
95 s.rel = 'stylesheet';
96 if ( s.styleSheet ) {
97 s.styleSheet.cssText = text; //IE
98 } else {
99 s.appendChild(document.createTextNode(text + '')); //Safari sometimes borks on null
100 }
101 document.getElementsByTagName('head')[0].appendChild(s);
102 return s;
103 }
104
105 // special stylesheet links
106 if (typeof stylepath != 'undefined' && typeof skin != 'undefined') {
107 // FIXME: This tries to load the stylesheets even for skins where they
108 // don't exist, i.e., everything but Monobook.
109 if (opera6_bugs) {
110 importStylesheetURI(stylepath+'/'+skin+'/Opera6Fixes.css');
111 } else if (opera7_bugs) {
112 importStylesheetURI(stylepath+'/'+skin+'/Opera7Fixes.css');
113 } else if (opera95_bugs) {
114 importStylesheetURI(stylepath+'/'+skin+'/Opera9Fixes.css');
115 } else if (ff2_bugs) {
116 importStylesheetURI(stylepath+'/'+skin+'/FF2Fixes.css');
117 }
118 }
119
120
121 if (wgBreakFrames) {
122 // Un-trap us from framesets
123 if (window.top != window) {
124 window.top.location = window.location;
125 }
126 }
127
128 function showTocToggle() {
129 if (document.createTextNode) {
130 // Uses DOM calls to avoid document.write + XHTML issues
131
132 var linkHolder = document.getElementById('toctitle');
133 var existingLink = document.getElementById('togglelink');
134 if (!linkHolder || existingLink) {
135 // Don't add the toggle link twice
136 return;
137 }
138
139 var outerSpan = document.createElement('span');
140 outerSpan.className = 'toctoggle';
141
142 var toggleLink = document.createElement('a');
143 toggleLink.id = 'togglelink';
144 toggleLink.className = 'internal';
145 toggleLink.href = 'javascript:toggleToc()';
146 toggleLink.appendChild(document.createTextNode(tocHideText));
147
148 outerSpan.appendChild(document.createTextNode('['));
149 outerSpan.appendChild(toggleLink);
150 outerSpan.appendChild(document.createTextNode(']'));
151
152 linkHolder.appendChild(document.createTextNode(' '));
153 linkHolder.appendChild(outerSpan);
154
155 var cookiePos = document.cookie.indexOf("hidetoc=");
156 if (cookiePos > -1 && document.cookie.charAt(cookiePos + 8) == 1) {
157 toggleToc();
158 }
159 }
160 }
161
162 function changeText(el, newText) {
163 // Safari work around
164 if (el.innerText) {
165 el.innerText = newText;
166 } else if (el.firstChild && el.firstChild.nodeValue) {
167 el.firstChild.nodeValue = newText;
168 }
169 }
170
171 function toggleToc() {
172 var tocmain = document.getElementById('toc');
173 var toc = document.getElementById('toc').getElementsByTagName('ul')[0];
174 var toggleLink = document.getElementById('togglelink');
175
176 if (toc && toggleLink && toc.style.display == 'none') {
177 changeText(toggleLink, tocHideText);
178 toc.style.display = 'block';
179 document.cookie = "hidetoc=0";
180 tocmain.className = 'toc';
181 } else {
182 changeText(toggleLink, tocShowText);
183 toc.style.display = 'none';
184 document.cookie = "hidetoc=1";
185 tocmain.className = 'toc tochidden';
186 }
187 }
188
189 var mwEditButtons = [];
190 var mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
191
192 function escapeQuotes(text) {
193 var re = new RegExp("'","g");
194 text = text.replace(re,"\\'");
195 re = new RegExp("\\n","g");
196 text = text.replace(re,"\\n");
197 return escapeQuotesHTML(text);
198 }
199
200 function escapeQuotesHTML(text) {
201 var re = new RegExp('&',"g");
202 text = text.replace(re,"&");
203 re = new RegExp('"',"g");
204 text = text.replace(re,""");
205 re = new RegExp('<',"g");
206 text = text.replace(re,"&lt;");
207 re = new RegExp('>',"g");
208 text = text.replace(re,"&gt;");
209 return text;
210 }
211
212
213 /**
214 * Set the accesskey prefix based on browser detection.
215 */
216 var tooltipAccessKeyPrefix = 'alt-';
217 if (is_opera) {
218 tooltipAccessKeyPrefix = 'shift-esc-';
219 } else if (!is_safari_win && is_safari && webkit_version > 526) {
220 tooltipAccessKeyPrefix = 'ctrl-alt-';
221 } else if (!is_safari_win && (is_safari
222 || clientPC.indexOf('mac') != -1
223 || clientPC.indexOf('konqueror') != -1 )) {
224 tooltipAccessKeyPrefix = 'ctrl-';
225 } else if (is_ff2) {
226 tooltipAccessKeyPrefix = 'alt-shift-';
227 }
228 var tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/;
229
230 /**
231 * Add the appropriate prefix to the accesskey shown in the tooltip.
232 * If the nodeList parameter is given, only those nodes are updated;
233 * otherwise, all the nodes that will probably have accesskeys by
234 * default are updated.
235 *
236 * @param Array nodeList -- list of elements to update
237 */
238 function updateTooltipAccessKeys( nodeList ) {
239 if ( !nodeList ) {
240 // Rather than scan all links on the whole page, we can just scan these
241 // containers which contain the relevant links. This is really just an
242 // optimization technique.
243 var linkContainers = [
244 "column-one", // Monobook and Modern
245 "head", "panel", "p-logo" // Vector
246 ];
247 for ( var i in linkContainers ) {
248 var linkContainer = document.getElementById( linkContainers[i] );
249 if ( linkContainer ) {
250 updateTooltipAccessKeys( linkContainer.getElementsByTagName("a") );
251 }
252 }
253 // these are rare enough that no such optimization is needed
254 updateTooltipAccessKeys( document.getElementsByTagName("input") );
255 updateTooltipAccessKeys( document.getElementsByTagName("label") );
256 return;
257 }
258
259 for ( var i = 0; i < nodeList.length; i++ ) {
260 var element = nodeList[i];
261 var tip = element.getAttribute("title");
262 if ( tip && tooltipAccessKeyRegexp.exec(tip) ) {
263 tip = tip.replace(tooltipAccessKeyRegexp,
264 "["+tooltipAccessKeyPrefix+"$5]");
265 element.setAttribute("title", tip );
266 }
267 }
268 }
269
270 /**
271 * Add a link to one of the portlet menus on the page, including:
272 *
273 * p-cactions: Content actions (shown as tabs above the main content in Monobook)
274 * p-personal: Personal tools (shown at the top right of the page in Monobook)
275 * p-navigation: Navigation
276 * p-tb: Toolbox
277 *
278 * This function exists for the convenience of custom JS authors. All
279 * but the first three parameters are optional, though providing at
280 * least an id and a tooltip is recommended.
281 *
282 * By default the new link will be added to the end of the list. To
283 * add the link before a given existing item, pass the DOM node of
284 * that item (easily obtained with document.getElementById()) as the
285 * nextnode parameter; to add the link _after_ an existing item, pass
286 * the node's nextSibling instead.
287 *
288 * @param String portlet -- id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
289 * @param String href -- link URL
290 * @param String text -- link text (will be automatically lowercased by CSS for p-cactions in Monobook)
291 * @param String id -- id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
292 * @param String tooltip -- text to show when hovering over the link, without accesskey suffix
293 * @param String accesskey -- accesskey to activate this link (one character, try to avoid conflicts)
294 * @param Node nextnode -- the DOM node before which the new item should be added, should be another item in the same list
295 *
296 * @return Node -- the DOM node of the new item (an LI element) or null
297 */
298 function addPortletLink(portlet, href, text, id, tooltip, accesskey, nextnode) {
299 var root = document.getElementById(portlet);
300 if ( !root ) {
301 return null;
302 }
303 var node = root.getElementsByTagName( 'ul' )[0];
304 if ( !node ) {
305 return null;
306 }
307
308 // unhide portlet if it was hidden before
309 root.className = root.className.replace( /(^| )emptyPortlet( |$)/, "$2" );
310
311 var span = document.createElement( 'span' );
312 span.appendChild( document.createTextNode( text ) );
313
314 var link = document.createElement( 'a' );
315 link.appendChild( span );
316 link.href = href;
317
318 var item = document.createElement( 'li' );
319 item.appendChild( link );
320 if ( id ) {
321 item.id = id;
322 }
323
324 if ( accesskey ) {
325 link.setAttribute( 'accesskey', accesskey );
326 tooltip += ' [' + accesskey + ']';
327 }
328 if ( tooltip ) {
329 link.setAttribute( 'title', tooltip );
330 }
331 if ( accesskey && tooltip ) {
332 updateTooltipAccessKeys( new Array( link ) );
333 }
334
335 if ( nextnode && nextnode.parentNode == node ) {
336 node.insertBefore( item, nextnode );
337 } else {
338 node.appendChild( item ); // IE compatibility (?)
339 }
340
341 return item;
342 }
343
344 function getInnerText(el) {
345 if ( typeof el == 'string' ) {
346 return el;
347 }
348 if ( typeof el == 'undefined' ) {
349 return el;
350 }
351 if ( el.textContent ) {
352 return el.textContent; // not needed but it is faster
353 }
354 if ( el.innerText ) {
355 return el.innerText; // IE doesn't have textContent
356 }
357 var str = '';
358
359 var cs = el.childNodes;
360 var l = cs.length;
361 for (var i = 0; i < l; i++) {
362 switch (cs[i].nodeType) {
363 case 1: // ELEMENT_NODE
364 str += ts_getInnerText(cs[i]);
365 break;
366 case 3: // TEXT_NODE
367 str += cs[i].nodeValue;
368 break;
369 }
370 }
371 return str;
372 }
373
374 /* Dummy for deprecated function */
375 function akeytt( doId ) {
376 }
377
378 var checkboxes;
379 var lastCheckbox;
380
381 function setupCheckboxShiftClick() {
382 checkboxes = [];
383 lastCheckbox = null;
384 var inputs = document.getElementsByTagName('input');
385 addCheckboxClickHandlers(inputs);
386 }
387
388 function addCheckboxClickHandlers(inputs, start) {
389 if ( !start ) {
390 start = 0;
391 }
392
393 var finish = start + 250;
394 if ( finish > inputs.length ) {
395 finish = inputs.length;
396 }
397
398 for ( var i = start; i < finish; i++ ) {
399 var cb = inputs[i];
400 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' ) {
401 continue;
402 }
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 }
439 lastCheckbox = this.index;
440 return true;
441 }
442
443
444 /*
445 Written by Jonathan Snook, http://www.snook.ca/jonathan
446 Add-ons by Robert Nyman, http://www.robertnyman.com
447 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
448 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
449 */
450 function getElementsByClassName(oElm, strTagName, oClassNames){
451 var arrReturnElements = new Array();
452 if ( typeof( oElm.getElementsByClassName ) == "function" ) {
453 /* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
454 var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
455 if ( strTagName == "*" ) {
456 return arrNativeReturn;
457 }
458 for ( var h=0; h < arrNativeReturn.length; h++ ) {
459 if( arrNativeReturn[h].tagName.toLowerCase() == strTagName.toLowerCase() ) {
460 arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
461 }
462 }
463 return arrReturnElements;
464 }
465 var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
466 var arrRegExpClassNames = new Array();
467 if(typeof oClassNames == "object"){
468 for(var i=0; i<oClassNames.length; i++){
469 arrRegExpClassNames[arrRegExpClassNames.length] =
470 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
471 }
472 } else {
473 arrRegExpClassNames[arrRegExpClassNames.length] =
474 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
475 }
476 var oElement;
477 var bMatchesAll;
478 for(var j=0; j<arrElements.length; j++){
479 oElement = arrElements[j];
480 bMatchesAll = true;
481 for(var k=0; k<arrRegExpClassNames.length; k++){
482 if(!arrRegExpClassNames[k].test(oElement.className)){
483 bMatchesAll = false;
484 break;
485 }
486 }
487 if(bMatchesAll){
488 arrReturnElements[arrReturnElements.length] = oElement;
489 }
490 }
491 return (arrReturnElements);
492 }
493
494 function redirectToFragment(fragment) {
495 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
496 if (match) {
497 var webKitVersion = parseInt(match[1]);
498 if (webKitVersion < 420) {
499 // Released Safari w/ WebKit 418.9.1 messes up horribly
500 // Nightlies of 420+ are ok
501 return;
502 }
503 }
504 if (is_gecko) {
505 // Mozilla needs to wait until after load, otherwise the window doesn't scroll
506 addOnloadHook(function () {
507 if (window.location.hash == '') {
508 window.location.hash = fragment;
509 }
510 });
511 } else {
512 if (window.location.hash == '') {
513 window.location.hash = fragment;
514 }
515 }
516 }
517
518 /*
519 * Table sorting script based on one (c) 1997-2006 Stuart Langridge and Joost
520 * de Valk:
521 * http://www.joostdevalk.nl/code/sortable-table/
522 * http://www.kryogenix.org/code/browser/sorttable/
523 *
524 * @todo don't break on colspans/rowspans (bug 8028)
525 * @todo language-specific digit grouping/decimals (bug 8063)
526 * @todo support all accepted date formats (bug 8226)
527 */
528
529 var ts_image_path = stylepath + '/common/images/';
530 var ts_image_up = 'sort_up.gif';
531 var ts_image_down = 'sort_down.gif';
532 var ts_image_none = 'sort_none.gif';
533 var ts_europeandate = wgContentLanguage != 'en'; // The non-American-inclined can change to "true"
534 var ts_alternate_row_colors = false;
535 var ts_number_transform_table = null;
536 var ts_number_regex = null;
537
538 function sortables_init() {
539 var idnum = 0;
540 // Find all tables with class sortable and make them sortable
541 var tables = getElementsByClassName(document, "table", "sortable");
542 for (var ti = 0; ti < tables.length ; ti++) {
543 if (!tables[ti].id) {
544 tables[ti].setAttribute('id','sortable_table_id_'+idnum);
545 ++idnum;
546 }
547 ts_makeSortable(tables[ti]);
548 }
549 }
550
551 function ts_makeSortable(table) {
552 var firstRow;
553 if (table.rows && table.rows.length > 0) {
554 if (table.tHead && table.tHead.rows.length > 0) {
555 firstRow = table.tHead.rows[table.tHead.rows.length-1];
556 } else {
557 firstRow = table.rows[0];
558 }
559 }
560 if ( !firstRow ) {
561 return;
562 }
563
564 // We have a first row: assume it's the header, and make its contents clickable links
565 for (var i = 0; i < firstRow.cells.length; i++) {
566 var cell = firstRow.cells[i];
567 if ((" "+cell.className+" ").indexOf(" unsortable ") == -1) {
568 cell.innerHTML += '<a href="#" class="sortheader" '
569 + 'onclick="ts_resortTable(this);return false;">'
570 + '<span class="sortarrow">'
571 + '<img src="'
572 + ts_image_path
573 + ts_image_none
574 + '" alt="&darr;"/></span></a>';
575 }
576 }
577 if (ts_alternate_row_colors) {
578 ts_alternate(table);
579 }
580 }
581
582 function ts_getInnerText(el) {
583 return getInnerText( el );
584 }
585
586 function ts_resortTable(lnk) {
587 // get the span
588 var span = lnk.getElementsByTagName('span')[0];
589
590 var td = lnk.parentNode;
591 var tr = td.parentNode;
592 var column = td.cellIndex;
593
594 var table = tr.parentNode;
595 while (table && !(table.tagName && table.tagName.toLowerCase() == 'table')) {
596 table = table.parentNode;
597 }
598 if ( !table ) {
599 return;
600 }
601
602 if ( table.rows.length <= 1 ) {
603 return;
604 }
605
606 // Generate the number transform table if it's not done already
607 if (ts_number_transform_table === null) {
608 ts_initTransformTable();
609 }
610
611 // Work out a type for the column
612 // Skip the first row if that's where the headings are
613 var rowStart = (table.tHead && table.tHead.rows.length > 0 ? 0 : 1);
614
615 var itm = '';
616 for (var i = rowStart; i < table.rows.length; i++) {
617 if (table.rows[i].cells.length > column) {
618 itm = ts_getInnerText(table.rows[i].cells[column]);
619 itm = itm.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "");
620 if ( itm != '' ) {
621 break;
622 }
623 }
624 }
625
626 // TODO: bug 8226, localised date formats
627 var sortfn = ts_sort_generic;
628 var preprocessor = ts_toLowerCase;
629 if (/^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test(itm)) {
630 preprocessor = ts_dateToSortKey;
631 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test(itm)) {
632 preprocessor = ts_dateToSortKey;
633 } else if (/^\d\d[\/.-]\d\d[\/.-]\d\d$/.test(itm)) {
634 preprocessor = ts_dateToSortKey;
635 // (minus sign)([pound dollar euro yen currency]|cents)
636 } else if (/(^([-\u2212] *)?[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test(itm)) {
637 preprocessor = ts_currencyToSortKey;
638 } else if (ts_number_regex.test(itm)) {
639 preprocessor = ts_parseFloat;
640 }
641
642 var reverse = (span.getAttribute("sortdir") == 'down');
643
644 var newRows = new Array();
645 var staticRows = new Array();
646 for (var j = rowStart; j < table.rows.length; j++) {
647 var row = table.rows[j];
648 if((" "+row.className+" ").indexOf(" unsortable ") < 0) {
649 var keyText = ts_getInnerText(row.cells[column]);
650 if(keyText === undefined) {
651 keyText = '';
652 }
653 var oldIndex = (reverse ? -j : j);
654 var preprocessed = preprocessor( keyText.replace(/^[\s\xa0]+/, "").replace(/[\s\xa0]+$/, "") );
655
656 newRows[newRows.length] = new Array(row, preprocessed, oldIndex);
657 } else {
658 staticRows[staticRows.length] = new Array(row, false, j-rowStart);
659 }
660 }
661
662 newRows.sort(sortfn);
663
664 var arrowHTML;
665 if (reverse) {
666 arrowHTML = '<img src="'+ ts_image_path + ts_image_down + '" alt="&darr;"/>';
667 newRows.reverse();
668 span.setAttribute('sortdir','up');
669 } else {
670 arrowHTML = '<img src="'+ ts_image_path + ts_image_up + '" alt="&uarr;"/>';
671 span.setAttribute('sortdir','down');
672 }
673
674 for (var i = 0; i < staticRows.length; i++) {
675 var row = staticRows[i];
676 newRows.splice(row[2], 0, row);
677 }
678
679 // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
680 // don't do sortbottom rows
681 for (var i = 0; i < newRows.length; i++) {
682 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") == -1)
683 table.tBodies[0].appendChild(newRows[i][0]);
684 }
685 // do sortbottom rows only
686 for (var i = 0; i < newRows.length; i++) {
687 if ((" "+newRows[i][0].className+" ").indexOf(" sortbottom ") != -1)
688 table.tBodies[0].appendChild(newRows[i][0]);
689 }
690
691 // Delete any other arrows there may be showing
692 var spans = getElementsByClassName(tr, "span", "sortarrow");
693 for (var i = 0; i < spans.length; i++) {
694 spans[i].innerHTML = '<img src="'+ ts_image_path + ts_image_none + '" alt="&darr;"/>';
695 }
696 span.innerHTML = arrowHTML;
697
698 if (ts_alternate_row_colors) {
699 ts_alternate(table);
700 }
701 }
702
703 function ts_initTransformTable() {
704 if ( typeof wgSeparatorTransformTable == "undefined"
705 || ( wgSeparatorTransformTable[0] == '' && wgDigitTransformTable[2] == '' ) )
706 {
707 digitClass = "[0-9,.]";
708 ts_number_transform_table = false;
709 } else {
710 ts_number_transform_table = {};
711 // Unpack the transform table
712 // Separators
713 ascii = wgSeparatorTransformTable[0].split("\t");
714 localised = wgSeparatorTransformTable[1].split("\t");
715 for ( var i = 0; i < ascii.length; i++ ) {
716 ts_number_transform_table[localised[i]] = ascii[i];
717 }
718 // Digits
719 ascii = wgDigitTransformTable[0].split("\t");
720 localised = wgDigitTransformTable[1].split("\t");
721 for ( var i = 0; i < ascii.length; i++ ) {
722 ts_number_transform_table[localised[i]] = ascii[i];
723 }
724
725 // Construct regex for number identification
726 digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\\.'];
727 maxDigitLength = 1;
728 for ( var digit in ts_number_transform_table ) {
729 // Escape regex metacharacters
730 digits.push(
731 digit.replace( /[\\\\$\*\+\?\.\(\)\|\{\}\[\]\-]/,
732 function( s ) { return '\\' + s; } )
733 );
734 if (digit.length > maxDigitLength) {
735 maxDigitLength = digit.length;
736 }
737 }
738 if ( maxDigitLength > 1 ) {
739 digitClass = '[' + digits.join( '', digits ) + ']';
740 } else {
741 digitClass = '(' + digits.join( '|', digits ) + ')';
742 }
743 }
744
745 // We allow a trailing percent sign, which we just strip. This works fine
746 // if percents and regular numbers aren't being mixed.
747 ts_number_regex = new RegExp(
748 "^(" +
749 "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
750 "|" +
751 "[-+\u2212]?" + digitClass + "+%?" + // Generic localised
752 ")$", "i"
753 );
754 }
755
756 function ts_toLowerCase( s ) {
757 return s.toLowerCase();
758 }
759
760 function ts_dateToSortKey(date) {
761 // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
762 if (date.length == 11) {
763 switch (date.substr(3,3).toLowerCase()) {
764 case "jan": var month = "01"; break;
765 case "feb": var month = "02"; break;
766 case "mar": var month = "03"; break;
767 case "apr": var month = "04"; break;
768 case "may": var month = "05"; break;
769 case "jun": var month = "06"; break;
770 case "jul": var month = "07"; break;
771 case "aug": var month = "08"; break;
772 case "sep": var month = "09"; break;
773 case "oct": var month = "10"; break;
774 case "nov": var month = "11"; break;
775 case "dec": var month = "12"; break;
776 // default: var month = "00";
777 }
778 return date.substr(7,4)+month+date.substr(0,2);
779 } else if (date.length == 10) {
780 if (ts_europeandate == false) {
781 return date.substr(6,4)+date.substr(0,2)+date.substr(3,2);
782 } else {
783 return date.substr(6,4)+date.substr(3,2)+date.substr(0,2);
784 }
785 } else if (date.length == 8) {
786 yr = date.substr(6,2);
787 if (parseInt(yr) < 50) {
788 yr = '20'+yr;
789 } else {
790 yr = '19'+yr;
791 }
792 if (ts_europeandate == true) {
793 return yr+date.substr(3,2)+date.substr(0,2);
794 } else {
795 return yr+date.substr(0,2)+date.substr(3,2);
796 }
797 }
798 return "00000000";
799 }
800
801 function ts_parseFloat( s ) {
802 if ( !s ) {
803 return 0;
804 }
805 if (ts_number_transform_table != false) {
806 var newNum = '', c;
807
808 for ( var p = 0; p < s.length; p++ ) {
809 c = s.charAt( p );
810 if (c in ts_number_transform_table) {
811 newNum += ts_number_transform_table[c];
812 } else {
813 newNum += c;
814 }
815 }
816 s = newNum;
817 }
818 num = parseFloat(s.replace(/[, ]/g, "").replace("\u2212", "-"));
819 return (isNaN(num) ? -Infinity : num);
820 }
821
822 function ts_currencyToSortKey( s ) {
823 return ts_parseFloat(s.replace(/[^-\u22120-9.,]/g,''));
824 }
825
826 function ts_sort_generic(a, b) {
827 return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2];
828 }
829
830 function ts_alternate(table) {
831 // Take object table and get all it's tbodies.
832 var tableBodies = table.getElementsByTagName("tbody");
833 // Loop through these tbodies
834 for (var i = 0; i < tableBodies.length; i++) {
835 // Take the tbody, and get all it's rows
836 var tableRows = tableBodies[i].getElementsByTagName("tr");
837 // Loop through these rows
838 // Start at 1 because we want to leave the heading row untouched
839 for (var j = 0; j < tableRows.length; j++) {
840 // Check if j is even, and apply classes for both possible results
841 var oldClasses = tableRows[j].className.split(" ");
842 var newClassName = "";
843 for (var k = 0; k < oldClasses.length; k++) {
844 if (oldClasses[k] != "" && oldClasses[k] != "even" && oldClasses[k] != "odd")
845 newClassName += oldClasses[k] + " ";
846 }
847 tableRows[j].className = newClassName + (j % 2 == 0 ? "even" : "odd");
848 }
849 }
850 }
851
852 /*
853 * End of table sorting code
854 */
855
856
857 /**
858 * Add a cute little box at the top of the screen to inform the user of
859 * something, replacing any preexisting message.
860 *
861 * @param String -or- Dom Object message HTML to be put inside the right div
862 * @param String className Used in adding a class; should be different for each
863 * call to allow CSS/JS to hide different boxes. null = no class used.
864 * @return Boolean True on success, false on failure
865 */
866 function jsMsg( message, className ) {
867 if ( !document.getElementById ) {
868 return false;
869 }
870 // We special-case skin structures provided by the software. Skins that
871 // choose to abandon or significantly modify our formatting can just define
872 // an mw-js-message div to start with.
873 var messageDiv = document.getElementById( 'mw-js-message' );
874 if ( !messageDiv ) {
875 messageDiv = document.createElement( 'div' );
876 if ( document.getElementById( 'column-content' )
877 && document.getElementById( 'content' ) ) {
878 // MonoBook, presumably
879 document.getElementById( 'content' ).insertBefore(
880 messageDiv,
881 document.getElementById( 'content' ).firstChild
882 );
883 } else if ( document.getElementById('content')
884 && document.getElementById( 'article' ) ) {
885 // Non-Monobook but still recognizable (old-style)
886 document.getElementById( 'article').insertBefore(
887 messageDiv,
888 document.getElementById( 'article' ).firstChild
889 );
890 } else {
891 return false;
892 }
893 }
894
895 messageDiv.setAttribute( 'id', 'mw-js-message' );
896 messageDiv.style.display = 'block';
897 if( className ) {
898 messageDiv.setAttribute( 'class', 'mw-js-message-'+className );
899 }
900
901 if (typeof message === 'object') {
902 while (messageDiv.hasChildNodes()) // Remove old content
903 messageDiv.removeChild(messageDiv.firstChild);
904 messageDiv.appendChild (message); // Append new content
905 }
906 else {
907 messageDiv.innerHTML = message;
908 }
909 return true;
910 }
911
912 /**
913 * Inject a cute little progress spinner after the specified element
914 *
915 * @param element Element to inject after
916 * @param id Identifier string (for use with removeSpinner(), below)
917 */
918 function injectSpinner( element, id ) {
919 var spinner = document.createElement( "img" );
920 spinner.id = "mw-spinner-" + id;
921 spinner.src = stylepath + "/common/images/spinner.gif";
922 spinner.alt = spinner.title = "...";
923 if( element.nextSibling ) {
924 element.parentNode.insertBefore( spinner, element.nextSibling );
925 } else {
926 element.parentNode.appendChild( spinner );
927 }
928 }
929
930 /**
931 * Remove a progress spinner added with injectSpinner()
932 *
933 * @param id Identifier string
934 */
935 function removeSpinner( id ) {
936 var spinner = document.getElementById( "mw-spinner-" + id );
937 if( spinner ) {
938 spinner.parentNode.removeChild( spinner );
939 }
940 }
941
942 function runOnloadHook() {
943 // don't run anything below this for non-dom browsers
944 if (doneOnloadHook || !(document.getElementById && document.getElementsByTagName)) {
945 return;
946 }
947
948 // set this before running any hooks, since any errors below
949 // might cause the function to terminate prematurely
950 doneOnloadHook = true;
951
952 updateTooltipAccessKeys( 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);
1004
1005 if ( ie6_bugs ) {
1006 var isMSIE55 = (window.showModalDialog && window.clipboardData && window.createPopup);
1007 var doneIETransform;
1008 var doneIEAlphaFix;
1009
1010 if (document.attachEvent)
1011 document.attachEvent('onreadystatechange', hookit);
1012
1013 function hookit() {
1014 if (!doneIETransform && document.getElementById && document.getElementById('bodyContent')) {
1015 doneIETransform = true;
1016 relativeforfloats();
1017 fixalpha();
1018 }
1019 }
1020
1021 // png alpha transparency fixes
1022 function fixalpha( logoId ) {
1023 // bg
1024 if (isMSIE55 && !doneIEAlphaFix)
1025 {
1026 var plogo = document.getElementById( logoId || 'p-logo' );
1027 if (!plogo) return;
1028
1029 var logoa = plogo.getElementsByTagName('a')[0];
1030 if (!logoa) return;
1031
1032 var bg = logoa.currentStyle.backgroundImage;
1033 var imageUrl = bg.substring(5, bg.length-2);
1034
1035 doneIEAlphaFix = true;
1036
1037 if (imageUrl.substr(imageUrl.length-4).toLowerCase() == '.png') {
1038 var logospan = logoa.appendChild(document.createElement('span'));
1039
1040 logoa.style.backgroundImage = 'none';
1041 logospan.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + imageUrl + ')';
1042 logospan.style.height = '100%';
1043 logospan.style.position = 'absolute';
1044 logospan.style.width = logoa.currentStyle.width;
1045 logospan.style.cursor = 'hand';
1046 // Center image with hack for IE5.5
1047 if (document.documentElement.dir == "rtl")
1048 {
1049 logospan.style.right = '50%';
1050 logospan.style.setExpression('marginRight', '"-" + (this.offsetWidth / 2) + "px"');
1051 }
1052 else
1053 {
1054 logospan.style.left = '50%';
1055 logospan.style.setExpression('marginLeft', '"-" + (this.offsetWidth / 2) + "px"');
1056 }
1057 logospan.style.top = '50%';
1058 logospan.style.setExpression('marginTop', '"-" + (this.offsetHeight / 2) + "px"');
1059
1060 var linkFix = logoa.appendChild(logoa.cloneNode());
1061 linkFix.style.position = 'absolute';
1062 linkFix.style.height = '100%';
1063 linkFix.style.width = '100%';
1064 }
1065 }
1066 }
1067
1068 // fix ie6 disappering float bug
1069 function relativeforfloats() {
1070 var bc = document.getElementById('bodyContent');
1071 if (bc) {
1072 var tables = bc.getElementsByTagName('table');
1073 var divs = bc.getElementsByTagName('div');
1074 }
1075 setrelative(tables);
1076 setrelative(divs);
1077 }
1078 function setrelative (nodes) {
1079 var i = 0;
1080 while (i < nodes.length) {
1081 if(((nodes[i].style.float && nodes[i].style.float != ('none') ||
1082 (nodes[i].align && nodes[i].align != ('none'))) &&
1083 (!nodes[i].style.position || nodes[i].style.position != 'relative')))
1084 {
1085 nodes[i].style.position = 'relative';
1086 }
1087 i++;
1088 }
1089 }
1090
1091
1092 // Expand links for printing
1093
1094 String.prototype.hasClass = function(classWanted)
1095 {
1096 var classArr = this.split(/\s/);
1097 for (var i=0; i<classArr.length; i++)
1098 if (classArr[i].toLowerCase() == classWanted.toLowerCase()) return true;
1099 return false;
1100 }
1101
1102 var expandedURLs;
1103
1104 onbeforeprint = function() {
1105 expandedURLs = [];
1106
1107 var contentEl = document.getElementById("content");
1108
1109 if (contentEl)
1110 {
1111 var allLinks = contentEl.getElementsByTagName("a");
1112
1113 for (var i=0; i < allLinks.length; i++) {
1114 if (allLinks[i].className.hasClass("external") && !allLinks[i].className.hasClass("free")) {
1115 var expandedLink = document.createElement("span");
1116 var expandedText = document.createTextNode(" (" + allLinks[i].href + ")");
1117 expandedLink.appendChild(expandedText);
1118 allLinks[i].parentNode.insertBefore(expandedLink, allLinks[i].nextSibling);
1119 expandedURLs[i] = expandedLink;
1120 }
1121 }
1122 }
1123 }
1124
1125 onafterprint = function() {
1126 for (var i=0; i < expandedURLs.length; i++)
1127 if (expandedURLs[i])
1128 expandedURLs[i].removeNode(true);
1129 }
1130 }