]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - skins/common/wikibits.js
MediaWiki 1.17.0
[autoinstalls/mediawiki.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( mediaWiki.msg( 'hidetoc' ) ) );
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, mediaWiki.msg( 'hidetoc' ) );
202                 toc.style.display = 'block';
203                 document.cookie = "hidetoc=0";
204                 tocmain.className = 'toc';
205         } else {
206                 changeText( toggleLink, mediaWiki.msg( 'showtoc' ) );
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 nodeList Array 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 portlet String id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
315  * @param href String link URL
316  * @param text String link text (will be automatically lowercased by CSS for p-cactions in Monobook)
317  * @param id String id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
318  * @param tooltip String text to show when hovering over the link, without accesskey suffix
319  * @param accesskey String accesskey to activate this link (one character, try to avoid conflicts)
320  * @param nextnode Node 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 link = document.createElement( 'a' );
356         link.appendChild( document.createTextNode( text ) );
357         link.href = href;
358
359         // Wrap in a span - make it work with vector tabs and has no effect on any other portlets
360         var span = document.createElement( 'span' );
361         span.appendChild( link );
362
363         var item = document.createElement( 'li' );
364         item.appendChild( span );
365         if ( id ) {
366                 item.id = id;
367         }
368
369         if ( accesskey ) {
370                 link.setAttribute( 'accesskey', accesskey );
371                 tooltip += ' [' + accesskey + ']';
372         }
373         if ( tooltip ) {
374                 link.setAttribute( 'title', tooltip );
375         }
376         if ( accesskey && tooltip ) {
377                 updateTooltipAccessKeys( new Array( link ) );
378         }
379
380         if ( nextnode && nextnode.parentNode == node ) {
381                 node.insertBefore( item, nextnode );
382         } else {
383                 node.appendChild( item );  // IE compatibility (?)
384         }
385
386         return item;
387 };
388
389 window.getInnerText = function( el ) {
390         if ( typeof el == 'string' ) {
391                 return el;
392         }
393         if ( typeof el == 'undefined' ) {
394                 return el;
395         }
396         // Custom sort value through 'data-sort-value' attribute
397         // (no need to prepend hidden text to change sort value)
398         if ( el.nodeType && el.getAttribute( 'data-sort-value' ) !== null ) {
399                 // Make sure it's a valid DOM element (.nodeType) and that the attribute is set (!null)
400                 return el.getAttribute( 'data-sort-value' );
401         }
402         if ( el.textContent ) {
403                 return el.textContent; // not needed but it is faster
404         }
405         if ( el.innerText ) {
406                 return el.innerText; // IE doesn't have textContent
407         }
408         var str = '';
409
410         var cs = el.childNodes;
411         var l = cs.length;
412         for ( var i = 0; i < l; i++ ) {
413                 switch ( cs[i].nodeType ) {
414                         case 1: // ELEMENT_NODE
415                                 str += ts_getInnerText( cs[i] );
416                                 break;
417                         case 3: // TEXT_NODE
418                                 str += cs[i].nodeValue;
419                                 break;
420                 }
421         }
422         return str;
423 };
424
425 /* Dummy for deprecated function */
426 window.ta = [];
427 window.akeytt = function( doId ) {
428 };
429
430 window.checkboxes = undefined;
431 window.lastCheckbox = undefined;
432
433 window.setupCheckboxShiftClick = function() {
434         checkboxes = [];
435         lastCheckbox = null;
436         var inputs = document.getElementsByTagName( 'input' );
437         addCheckboxClickHandlers( inputs );
438 };
439
440 window.addCheckboxClickHandlers = function( inputs, start ) {
441         if ( !start ) {
442                 start = 0;
443         }
444
445         var finish = start + 250;
446         if ( finish > inputs.length ) {
447                 finish = inputs.length;
448         }
449
450         for ( var i = start; i < finish; i++ ) {
451                 var cb = inputs[i];
452                 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' || ( ' ' + cb.className + ' ' ).indexOf( ' noshiftselect ' )  != -1 ) {
453                         continue;
454                 }
455                 var end = checkboxes.length;
456                 checkboxes[end] = cb;
457                 cb.index = end;
458                 addClickHandler( cb, checkboxClickHandler );
459         }
460
461         if ( finish < inputs.length ) {
462                 setTimeout( function() {
463                         addCheckboxClickHandlers( inputs, finish );
464                 }, 200 );
465         }
466 };
467
468 window.checkboxClickHandler = function( e ) {
469         if ( typeof e == 'undefined' ) {
470                 e = window.event;
471         }
472         if ( !e.shiftKey || lastCheckbox === null ) {
473                 lastCheckbox = this.index;
474                 return true;
475         }
476         var endState = this.checked;
477         var start, finish;
478         if ( this.index < lastCheckbox ) {
479                 start = this.index + 1;
480                 finish = lastCheckbox;
481         } else {
482                 start = lastCheckbox;
483                 finish = this.index - 1;
484         }
485         for ( var i = start; i <= finish; ++i ) {
486                 checkboxes[i].checked = endState;
487                 if( i > start && typeof checkboxes[i].onchange == 'function' ) {
488                         checkboxes[i].onchange(); // fire triggers
489                 }
490         }
491         lastCheckbox = this.index;
492         return true;
493 };
494
495
496 /*
497         Written by Jonathan Snook, http://www.snook.ca/jonathan
498         Add-ons by Robert Nyman, http://www.robertnyman.com
499         Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
500         From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
501 */
502 window.getElementsByClassName = function( oElm, strTagName, oClassNames ) {
503         var arrReturnElements = new Array();
504         if ( typeof( oElm.getElementsByClassName ) == 'function' ) {
505                 /* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
506                 var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
507                 if ( strTagName == '*' ) {
508                         return arrNativeReturn;
509                 }
510                 for ( var h = 0; h < arrNativeReturn.length; h++ ) {
511                         if( arrNativeReturn[h].tagName.toLowerCase() == strTagName.toLowerCase() ) {
512                                 arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
513                         }
514                 }
515                 return arrReturnElements;
516         }
517         var arrElements = ( strTagName == '*' && oElm.all ) ? oElm.all : oElm.getElementsByTagName( strTagName );
518         var arrRegExpClassNames = new Array();
519         if( typeof oClassNames == 'object' ) {
520                 for( var i = 0; i < oClassNames.length; i++ ) {
521                         arrRegExpClassNames[arrRegExpClassNames.length] =
522                                 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
523                 }
524         } else {
525                 arrRegExpClassNames[arrRegExpClassNames.length] =
526                         new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
527         }
528         var oElement;
529         var bMatchesAll;
530         for( var j = 0; j < arrElements.length; j++ ) {
531                 oElement = arrElements[j];
532                 bMatchesAll = true;
533                 for( var k = 0; k < arrRegExpClassNames.length; k++ ) {
534                         if( !arrRegExpClassNames[k].test( oElement.className ) ) {
535                                 bMatchesAll = false;
536                                 break;
537                         }
538                 }
539                 if( bMatchesAll ) {
540                         arrReturnElements[arrReturnElements.length] = oElement;
541                 }
542         }
543         return ( arrReturnElements );
544 };
545
546 window.redirectToFragment = function( fragment ) {
547         var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
548         if ( match ) {
549                 var webKitVersion = parseInt( match[1] );
550                 if ( webKitVersion < 420 ) {
551                         // Released Safari w/ WebKit 418.9.1 messes up horribly
552                         // Nightlies of 420+ are ok
553                         return;
554                 }
555         }
556         if ( window.location.hash == '' ) {
557                 window.location.hash = fragment;
558
559                 // Mozilla needs to wait until after load, otherwise the window doesn't
560                 // scroll.  See <https://bugzilla.mozilla.org/show_bug.cgi?id=516293>.
561                 // There's no obvious way to detect this programmatically, so we use
562                 // version-testing.  If Firefox fixes the bug, they'll jump twice, but
563                 // better twice than not at all, so make the fix hit future versions as
564                 // well.
565                 if ( is_gecko ) {
566                         addOnloadHook(function() {
567                                 if ( window.location.hash == fragment ) {
568                                         window.location.hash = fragment;
569                                 }
570                         });
571                 }
572         }
573 };
574
575 /*
576  * Table sorting script based on one (c) 1997-2006 Stuart Langridge and Joost
577  * de Valk:
578  * http://www.joostdevalk.nl/code/sortable-table/
579  * http://www.kryogenix.org/code/browser/sorttable/
580  *
581  * @todo don't break on colspans/rowspans (bug 8028)
582  * @todo language-specific digit grouping/decimals (bug 8063)
583  * @todo support all accepted date formats (bug 8226)
584  */
585
586 window.ts_image_path = stylepath + '/common/images/';
587 window.ts_image_up = 'sort_up.gif';
588 window.ts_image_down = 'sort_down.gif';
589 window.ts_image_none = 'sort_none.gif';
590 window.ts_europeandate = wgContentLanguage != 'en'; // The non-American-inclined can change to "true"
591 window.ts_alternate_row_colors = false;
592 window.ts_number_transform_table = null;
593 window.ts_number_regex = null;
594
595 window.sortables_init = function() {
596         var idnum = 0;
597         // Find all tables with class sortable and make them sortable
598         var tables = getElementsByClassName( document, 'table', 'sortable' );
599         for ( var ti = 0; ti < tables.length ; ti++ ) {
600                 if ( !tables[ti].id ) {
601                         tables[ti].setAttribute( 'id', 'sortable_table_id_' + idnum );
602                         ++idnum;
603                 }
604                 ts_makeSortable( tables[ti] );
605         }
606 };
607
608 window.ts_makeSortable = function( table ) {
609         var firstRow;
610         if ( table.rows && table.rows.length > 0 ) {
611                 if ( table.tHead && table.tHead.rows.length > 0 ) {
612                         firstRow = table.tHead.rows[table.tHead.rows.length-1];
613                 } else {
614                         firstRow = table.rows[0];
615                 }
616         }
617         if ( !firstRow ) {
618                 return;
619         }
620
621         // We have a first row: assume it's the header, and make its contents clickable links
622         for ( var i = 0; i < firstRow.cells.length; i++ ) {
623                 var cell = firstRow.cells[i];
624                 if ( (' ' + cell.className + ' ').indexOf(' unsortable ') == -1 ) {
625                         $(cell).append ( '<a href="#" class="sortheader" '
626                                 + 'onclick="ts_resortTable(this);return false;">'
627                                 + '<span class="sortarrow">'
628                                 + '<img src="'
629                                 + ts_image_path
630                                 + ts_image_none
631                                 + '" alt="&darr;"/></span></a>');
632                 }
633         }
634         if ( ts_alternate_row_colors ) {
635                 ts_alternate( table );
636         }
637 };
638
639 window.ts_getInnerText = function( el ) {
640         return getInnerText( el );
641 };
642
643 window.ts_resortTable = function( lnk ) {
644         // get the span
645         var span = lnk.getElementsByTagName('span')[0];
646
647         var td = lnk.parentNode;
648         var tr = td.parentNode;
649         var column = td.cellIndex;
650
651         var table = tr.parentNode;
652         while ( table && !( table.tagName && table.tagName.toLowerCase() == 'table' ) ) {
653                 table = table.parentNode;
654         }
655         if ( !table ) {
656                 return;
657         }
658
659         if ( table.rows.length <= 1 ) {
660                 return;
661         }
662
663         // Generate the number transform table if it's not done already
664         if ( ts_number_transform_table === null ) {
665                 ts_initTransformTable();
666         }
667
668         // Work out a type for the column
669         // Skip the first row if that's where the headings are
670         var rowStart = ( table.tHead && table.tHead.rows.length > 0 ? 0 : 1 );
671         var bodyRows = 0;
672         if (rowStart == 0 && table.tBodies) {
673                 for (var i=0; i < table.tBodies.length; i++ ) {
674                         bodyRows += table.tBodies[i].rows.length;
675                 }
676                 if (bodyRows < table.rows.length)
677                         rowStart = 1;
678         }
679         
680         var itm = '';
681         for ( var i = rowStart; i < table.rows.length; i++ ) {
682                 if ( table.rows[i].cells.length > column ) {
683                         itm = ts_getInnerText(table.rows[i].cells[column]);
684                         itm = itm.replace(/^[\s\xa0]+/, '').replace(/[\s\xa0]+$/, '');
685                         if ( itm != '' ) {
686                                 break;
687                         }
688                 }
689         }
690
691         // TODO: bug 8226, localised date formats
692         var sortfn = ts_sort_generic;
693         var preprocessor = ts_toLowerCase;
694         if ( /^\d\d[\/. -][a-zA-Z]{3}[\/. -]\d\d\d\d$/.test( itm ) ) {
695                 preprocessor = ts_dateToSortKey;
696         } else if ( /^\d\d[\/.-]\d\d[\/.-]\d\d\d\d$/.test( itm ) ) {
697                 preprocessor = ts_dateToSortKey;
698         } else if ( /^\d\d[\/.-]\d\d[\/.-]\d\d$/.test( itm ) ) {
699                 preprocessor = ts_dateToSortKey;
700                 // (minus sign)([pound dollar euro yen currency]|cents)
701         } else if ( /(^([-\u2212] *)?[\u00a3$\u20ac\u00a4\u00a5]|\u00a2$)/.test( itm ) ) {
702                 preprocessor = ts_currencyToSortKey;
703         } else if ( ts_number_regex.test( itm ) ) {
704                 preprocessor = ts_parseFloat;
705         }
706
707         var reverse = ( span.getAttribute( 'sortdir' ) == 'down' );
708
709         var newRows = new Array();
710         var staticRows = new Array();
711         for ( var j = rowStart; j < table.rows.length; j++ ) {
712                 var row = table.rows[j];
713                 if( (' ' + row.className + ' ').indexOf(' unsortable ') < 0 ) {
714                         var keyText = ts_getInnerText( row.cells[column] );
715                         if( keyText === undefined ) {
716                                 keyText = ''; 
717                         }
718                         var oldIndex = ( reverse ? -j : j );
719                         var preprocessed = preprocessor( keyText.replace(/^[\s\xa0]+/, '').replace(/[\s\xa0]+$/, '') );
720
721                         newRows[newRows.length] = new Array( row, preprocessed, oldIndex );
722                 } else {
723                         staticRows[staticRows.length] = new Array( row, false, j-rowStart );
724                 }
725         }
726
727         newRows.sort( sortfn );
728
729         var arrowHTML;
730         if ( reverse ) {
731                 arrowHTML = '<img src="' + ts_image_path + ts_image_down + '" alt="&darr;"/>';
732                 newRows.reverse();
733                 span.setAttribute( 'sortdir', 'up' );
734         } else {
735                 arrowHTML = '<img src="' + ts_image_path + ts_image_up + '" alt="&uarr;"/>';
736                 span.setAttribute( 'sortdir', 'down' );
737         }
738
739         for ( var i = 0; i < staticRows.length; i++ ) {
740                 var row = staticRows[i];
741                 newRows.splice( row[2], 0, row );
742         }
743
744         // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
745         // don't do sortbottom rows
746         for ( var i = 0; i < newRows.length; i++ ) {
747                 if ( ( ' ' + newRows[i][0].className + ' ').indexOf(' sortbottom ') == -1 ) {
748                         table.tBodies[0].appendChild( newRows[i][0] );
749                 }
750         }
751         // do sortbottom rows only
752         for ( var i = 0; i < newRows.length; i++ ) {
753                 if ( ( ' ' + newRows[i][0].className + ' ').indexOf(' sortbottom ') != -1 ) {
754                         table.tBodies[0].appendChild( newRows[i][0] );
755                 }
756         }
757
758         // Delete any other arrows there may be showing
759         var spans = getElementsByClassName( tr, 'span', 'sortarrow' );
760         for ( var i = 0; i < spans.length; i++ ) {
761                 spans[i].innerHTML = '<img src="' + ts_image_path + ts_image_none + '" alt="&darr;"/>';
762         }
763         span.innerHTML = arrowHTML;
764
765         if ( ts_alternate_row_colors ) {
766                 ts_alternate( table );
767         }
768 };
769
770 window.ts_initTransformTable = function() {
771         if ( typeof wgSeparatorTransformTable == 'undefined'
772                         || ( wgSeparatorTransformTable[0] == '' && wgDigitTransformTable[2] == '' ) )
773         {
774                 var digitClass = "[0-9,.]";
775                 ts_number_transform_table = false;
776         } else {
777                 ts_number_transform_table = {};
778                 // Unpack the transform table
779                 // Separators
780                 var ascii = wgSeparatorTransformTable[0].split("\t");
781                 var localised = wgSeparatorTransformTable[1].split("\t");
782                 for ( var i = 0; i < ascii.length; i++ ) {
783                         ts_number_transform_table[localised[i]] = ascii[i];
784                 }
785                 // Digits
786                 ascii = wgDigitTransformTable[0].split("\t");
787                 localised = wgDigitTransformTable[1].split("\t");
788                 for ( var i = 0; i < ascii.length; i++ ) {
789                         ts_number_transform_table[localised[i]] = ascii[i];
790                 }
791
792                 // Construct regex for number identification
793                 var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\\.'];
794                 var maxDigitLength = 1;
795                 for ( var digit in ts_number_transform_table ) {
796                         // Escape regex metacharacters
797                         digits.push(
798                                 digit.replace( /[\\\\$\*\+\?\.\(\)\|\{\}\[\]\-]/,
799                                         function( s ) { return '\\' + s; } )
800                         );
801                         if ( digit.length > maxDigitLength ) {
802                                 maxDigitLength = digit.length;
803                         }
804                 }
805                 if ( maxDigitLength > 1 ) {
806                         var digitClass = '[' + digits.join( '', digits ) + ']';
807                 } else {
808                         var digitClass = '(' + digits.join( '|', digits ) + ')';
809                 }
810         }
811
812         // We allow a trailing percent sign, which we just strip.  This works fine
813         // if percents and regular numbers aren't being mixed.
814         ts_number_regex = new RegExp(
815                 "^(" +
816                         "[-+\u2212]?[0-9][0-9,]*(\\.[0-9,]*)?(E[-+\u2212]?[0-9][0-9,]*)?" + // Fortran-style scientific
817                         "|" +
818                         "[-+\u2212]?" + digitClass + "+%?" + // Generic localised
819                 ")$", "i"
820         );
821 };
822
823 window.ts_toLowerCase = function( s ) {
824         return s.toLowerCase();
825 };
826
827 window.ts_dateToSortKey = function( date ) {
828         // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
829         if ( date.length == 11 ) {
830                 switch ( date.substr( 3, 3 ).toLowerCase() ) {
831                         case 'jan':
832                                 var month = '01';
833                                 break;
834                         case 'feb':
835                                 var month = '02';
836                                 break;
837                         case 'mar':
838                                 var month = '03';
839                                 break;
840                         case 'apr':
841                                 var month = '04';
842                                 break;
843                         case 'may':
844                                 var month = '05';
845                                 break;
846                         case 'jun':
847                                 var month = '06';
848                                 break;
849                         case 'jul':
850                                 var month = '07';
851                                 break;
852                         case 'aug':
853                                 var month = '08';
854                                 break;
855                         case 'sep':
856                                 var month = '09';
857                                 break;
858                         case 'oct':
859                                 var month = '10';
860                                 break;
861                         case 'nov':
862                                 var month = '11';
863                                 break;
864                         case 'dec':
865                                 var month = '12';
866                                 break;
867                         // default: var month = '00';
868                 }
869                 return date.substr( 7, 4 ) + month + date.substr( 0, 2 );
870         } else if ( date.length == 10 ) {
871                 if ( ts_europeandate == false ) {
872                         return date.substr( 6, 4 ) + date.substr( 0, 2 ) + date.substr( 3, 2 );
873                 } else {
874                         return date.substr( 6, 4 ) + date.substr( 3, 2 ) + date.substr( 0, 2 );
875                 }
876         } else if ( date.length == 8 ) {
877                 var yr = date.substr( 6, 2 );
878                 if ( parseInt( yr ) < 50 ) {
879                         yr = '20' + yr;
880                 } else {
881                         yr = '19' + yr;
882                 }
883                 if ( ts_europeandate == true ) {
884                         return yr + date.substr( 3, 2 ) + date.substr( 0, 2 );
885                 } else {
886                         return yr + date.substr( 0, 2 ) + date.substr( 3, 2 );
887                 }
888         }
889         return '00000000';
890 };
891
892 window.ts_parseFloat = function( s ) {
893         if ( !s ) {
894                 return 0;
895         }
896         if ( ts_number_transform_table != false ) {
897                 var newNum = '', c;
898
899                 for ( var p = 0; p < s.length; p++ ) {
900                         c = s.charAt( p );
901                         if ( c in ts_number_transform_table ) {
902                                 newNum += ts_number_transform_table[c];
903                         } else {
904                                 newNum += c;
905                         }
906                 }
907                 s = newNum;
908         }
909         var num = parseFloat( s.replace(/[, ]/g, '').replace("\u2212", '-') );
910         return ( isNaN( num ) ? -Infinity : num );
911 };
912
913 window.ts_currencyToSortKey = function( s ) {
914         return ts_parseFloat(s.replace(/[^-\u22120-9.,]/g,''));
915 };
916
917 window.ts_sort_generic = function( a, b ) {
918         return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[2] - b[2];
919 };
920
921 window.ts_alternate = function( table ) {
922         // Take object table and get all it's tbodies.
923         var tableBodies = table.getElementsByTagName( 'tbody' );
924         // Loop through these tbodies
925         for ( var i = 0; i < tableBodies.length; i++ ) {
926                 // Take the tbody, and get all it's rows
927                 var tableRows = tableBodies[i].getElementsByTagName( 'tr' );
928                 // Loop through these rows
929                 // Start at 1 because we want to leave the heading row untouched
930                 for ( var j = 0; j < tableRows.length; j++ ) {
931                         // Check if j is even, and apply classes for both possible results
932                         var oldClasses = tableRows[j].className.split(' ');
933                         var newClassName = '';
934                         for ( var k = 0; k < oldClasses.length; k++ ) {
935                                 if ( oldClasses[k] != '' && oldClasses[k] != 'even' && oldClasses[k] != 'odd' ) {
936                                         newClassName += oldClasses[k] + ' ';
937                                 }
938                         }
939                         tableRows[j].className = newClassName + ( j % 2 == 0 ? 'even' : 'odd' );
940                 }
941         }
942 };
943
944 /*
945  * End of table sorting code
946  */
947
948
949 /**
950  * Add a cute little box at the top of the screen to inform the user of
951  * something, replacing any preexisting message.
952  *
953  * @param message String -or- Dom Object  HTML to be put inside the right div
954  * @param className String   Used in adding a class; should be different for each
955  *   call to allow CSS/JS to hide different boxes.  null = no class used.
956  * @return Boolean       True on success, false on failure
957  */
958 window.jsMsg = function( message, className ) {
959         if ( !document.getElementById ) {
960                 return false;
961         }
962         // We special-case skin structures provided by the software.  Skins that
963         // choose to abandon or significantly modify our formatting can just define
964         // an mw-js-message div to start with.
965         var messageDiv = document.getElementById( 'mw-js-message' );
966         if ( !messageDiv ) {
967                 messageDiv = document.createElement( 'div' );
968                 if ( document.getElementById( 'column-content' )
969                 && document.getElementById( 'content' ) ) {
970                         // MonoBook, presumably
971                         document.getElementById( 'content' ).insertBefore(
972                                 messageDiv,
973                                 document.getElementById( 'content' ).firstChild
974                         );
975                 } else if ( document.getElementById( 'content' )
976                 && document.getElementById( 'article' ) ) {
977                         // Non-Monobook but still recognizable (old-style)
978                         document.getElementById( 'article').insertBefore(
979                                 messageDiv,
980                                 document.getElementById( 'article' ).firstChild
981                         );
982                 } else {
983                         return false;
984                 }
985         }
986
987         messageDiv.setAttribute( 'id', 'mw-js-message' );
988         messageDiv.style.display = 'block';
989         if( className ) {
990                 messageDiv.setAttribute( 'class', 'mw-js-message-' + className );
991         }
992
993         if ( typeof message === 'object' ) {
994                 while ( messageDiv.hasChildNodes() ) { // Remove old content
995                         messageDiv.removeChild( messageDiv.firstChild );
996                 }
997                 messageDiv.appendChild( message ); // Append new content
998         } else {
999                 messageDiv.innerHTML = message;
1000         }
1001         return true;
1002 };
1003
1004 /**
1005  * Inject a cute little progress spinner after the specified element
1006  *
1007  * @param element Element to inject after
1008  * @param id Identifier string (for use with removeSpinner(), below)
1009  */
1010 window.injectSpinner = function( element, id ) {
1011         var spinner = document.createElement( 'img' );
1012         spinner.id = 'mw-spinner-' + id;
1013         spinner.src = stylepath + '/common/images/spinner.gif';
1014         spinner.alt = spinner.title = '...';
1015         if( element.nextSibling ) {
1016                 element.parentNode.insertBefore( spinner, element.nextSibling );
1017         } else {
1018                 element.parentNode.appendChild( spinner );
1019         }
1020 };
1021
1022 /**
1023  * Remove a progress spinner added with injectSpinner()
1024  *
1025  * @param id Identifier string
1026  */
1027 window.removeSpinner = function( id ) {
1028         var spinner = document.getElementById( 'mw-spinner-' + id );
1029         if( spinner ) {
1030                 spinner.parentNode.removeChild( spinner );
1031         }
1032 };
1033
1034 window.runOnloadHook = function() {
1035         // don't run anything below this for non-dom browsers
1036         if ( doneOnloadHook || !( document.getElementById && document.getElementsByTagName ) ) {
1037                 return;
1038         }
1039
1040         // set this before running any hooks, since any errors below
1041         // might cause the function to terminate prematurely
1042         doneOnloadHook = true;
1043
1044         updateTooltipAccessKeys( null );
1045         setupCheckboxShiftClick();
1046
1047         jQuery( document ).ready( sortables_init );
1048
1049         // Run any added-on functions
1050         for ( var i = 0; i < onloadFuncts.length; i++ ) {
1051                 onloadFuncts[i]();
1052         }
1053 };
1054
1055 /**
1056  * Add an event handler to an element
1057  *
1058  * @param element Element to add handler to
1059  * @param attach String Event to attach to
1060  * @param handler callable Event handler callback
1061  */
1062 window.addHandler = function( element, attach, handler ) {
1063         if( element.addEventListener ) {
1064                 element.addEventListener( attach, handler, false );
1065         } else if( element.attachEvent ) {
1066                 element.attachEvent( 'on' + attach, handler );
1067         }
1068 };
1069
1070 window.hookEvent = function( hookName, hookFunct ) {
1071         addHandler( window, hookName, hookFunct );
1072 };
1073
1074 /**
1075  * Add a click event handler to an element
1076  *
1077  * @param element Element to add handler to
1078  * @param handler callable Event handler callback
1079  */
1080 window.addClickHandler = function( element, handler ) {
1081         addHandler( element, 'click', handler );
1082 };
1083
1084 /**
1085  * Removes an event handler from an element
1086  *
1087  * @param element Element to remove handler from
1088  * @param remove String Event to remove
1089  * @param handler callable Event handler callback to remove
1090  */
1091 window.removeHandler = function( element, remove, handler ) {
1092         if( window.removeEventListener ) {
1093                 element.removeEventListener( remove, handler, false );
1094         } else if( window.detachEvent ) {
1095                 element.detachEvent( 'on' + remove, handler );
1096         }
1097 };
1098 // note: all skins should call runOnloadHook() at the end of html output,
1099 //      so the below should be redundant. It's there just in case.
1100 hookEvent( 'load', runOnloadHook );
1101
1102 if ( ie6_bugs ) {
1103         importScriptURI( stylepath + '/common/IEFixes.js' );
1104 }
1105
1106 showTocToggle();