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