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