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