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