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