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