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