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