MediaWiki:Common.js
From RationalWiki
Note: After saving, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Clear the cache in Tools → Preferences
/* Any JavaScript here will be loaded for all users on every page load. */ /*Add preview to file upload*/ /*Workaround for bug*/ function fixLicenseSelector() { licenses = document.getElementById("wpLicense"); if ( licenses && licenses.options[1].value == "subst:Nolicense/subst" ) { licenses.selectedIndex = 1; licenses.remove(0); if ( wgAjaxLicensePreview ) { licenses.onchange(); } } } if (wgPageName == 'Special:Upload') { addOnloadHook(fixLicenseSelector); importScript( 'MediaWiki:UploadPreview.js' ); } /* Test if an element has a certain class ************************************** * * Description: Uses regular expressions and caching for better performance. * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]] */ var hasClass = (function () { var reCache = {}; return function (element, className) { return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className); }; })(); /** Collapsible tables ********************************************************* * * Description: Allows tables to be collapsed, showing only the header. See * [[Wikipedia:NavFrame]]. * Maintainers: [[User:R. Koot]] */ var autoCollapse = 2; var collapseCaption = "hide"; var expandCaption = "show"; function collapseSetCookie( id, state ) { var date = new Date(); date.setTime(date.getTime()+(30*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); var c='collapse' + id + '='+state+expires+ '; path=/'; document.cookie = c; } function collapseGetCookieCollapsed( id ) { return document.cookie.indexOf('collapse' + id + '=1')!=-1; } function collapseGetCookieNotCollapsed( id ) { return document.cookie.indexOf('collapse' + id + '=0')!=-1; } function collapseOnlyTable( id ) { var Button = document.getElementById( "collapseButton" + id ); var Table = document.getElementById( id ); if ( !Table || !Button ) { return false; } var Rows = Table.rows; if ( Button.firstChild.data == collapseCaption ) { for ( var i = 1; i < Rows.length; i++ ) { Rows[i].style.display = "none"; } Button.firstChild.data = expandCaption; } } function collapseTableUncollapse( id ) { var Button = document.getElementById( "collapseButton" + id ); var Table = document.getElementById( id ); if ( !Table || !Button ) { return false; } var Rows = Table.rows; if ( Button.firstChild.data == expandCaption ) { for ( var i = 1; i < Rows.length; i++ ) { Rows[i].style.display = Rows[0].style.display; } Button.firstChild.data = collapseCaption; } } function collapseToggleTable( id ) { var Button = document.getElementById( "collapseButton" + id ); var Table = document.getElementById( id ); if ( !Table || !Button ) { return false; } var Rows = Table.rows; if ( Button.firstChild.data == collapseCaption ) { for ( var i = 1; i < Rows.length; i++ ) { Rows[i].style.display = "none"; } Button.firstChild.data = expandCaption; collapseSetCookie(id,1); } else { for ( var i = 1; i < Rows.length; i++ ) { Rows[i].style.display = Rows[0].style.display; } Button.firstChild.data = collapseCaption; collapseSetCookie(id,0); } } function createCollapseButtons() { var tableIndex = 0; var NavigationBoxes = new Object(); var Tables = document.getElementsByTagName( "table" ); for ( var i = 0; i < Tables.length; i++ ) { if ( hasClass( Tables[i], "collapsible" ) ) { /* only add button and increment count if there is a header row to work with */ var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0]; if (!HeaderRow) continue; var Header = HeaderRow.getElementsByTagName( "th" )[0]; if (!Header) continue; NavigationBoxes[ tableIndex ] = Tables[i]; id = Tables[i].getAttribute("id"); if ( id == null || id == "") { id = "collapsibleTable" + tableIndex; Tables[i].setAttribute( "id", id ); } var Button = document.createElement( "span" ); var ButtonLink = document.createElement( "a" ); var ButtonText = document.createTextNode( collapseCaption ); Button.className = "collapseButton"; //Styles are declared in Common.css ButtonLink.style.color = Header.style.color; ButtonLink.setAttribute( "id", "collapseButton" + id ); ButtonLink.setAttribute( "href", "javascript:collapseToggleTable('" + id + "');" ); ButtonLink.appendChild( ButtonText ); Button.appendChild( document.createTextNode( "[" ) ); Button.appendChild( ButtonLink ); Button.appendChild( document.createTextNode( "]" ) ); Header.insertBefore( Button, Header.childNodes[0] ); tableIndex++; } } for ( var i = 0; i < tableIndex; i++ ) { id = NavigationBoxes[i].getAttribute( "id" ); if ( hasClass( NavigationBoxes[i], "remembercollapse" ) ) { if (collapseGetCookieCollapsed(id)) { collapseOnlyTable(id); } } if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) { if ( hasClass( NavigationBoxes[i], "remembercollapse" ) ) { if (!collapseGetCookieNotCollapsed(id)) { collapseOnlyTable(id); } } else { collapseOnlyTable( id ); } } } } addOnloadHook( createCollapseButtons ); function collapsedCommentLinkClickHandler(e) { e = e || window.event; var eventSource = e.target || e.srcElement; // firstly, collapse all tables var Tables = document.getElementsByTagName( "table" ); for ( var i = 0; i < Tables.length; i++ ) { if ( hasClass( Tables[i], "collapsible" ) ) { collapseOnlyTable( Tables[i].id ); } } // now, see if we can find the table to which this anchor refers var anchorIndex = eventSource.href.indexOf('#'); if (anchorIndex != -1) { var anchorName = eventSource.href.substring(anchorIndex+1); var tableDiv = document.getElementById(anchorName); if (tableDiv) { // look for a collapsible table nested in this div, and expand it var tables = tableDiv.getElementsByTagName("table"); for (var i = 0; i < tables.length; ++i) { if (hasClass(tables[i], "collapsible") ) { collapseTableUncollapse(tables[i].id); } } } } } function addOnclickEventsToCollapsedCommentLinks() { var spans = document.getElementsByTagName("span"); for (var i = 0; i < spans.length; ++i) { if (spans[i].hasChildNodes() && hasClass(spans[i], "collapsed_comment_link")) { // look for links amongst this element's daughter elements var daughters = spans[i].getElementsByTagName("a"); for (var j = 0; j < daughters.length; ++j) { // add an onclick handler to this anchor daughters[j].onclick = collapsedCommentLinkClickHandler; } } } } addOnloadHook(addOnclickEventsToCollapsedCommentLinks); /*workaround for IE6 which doesn't support :hover on any element*/ var REG_MSIE = /msie (5|6)/i; var REG_COMPAT = /backcompat/i; function iehover_hide(container) { var hovertargets = getElementsByClassName(container,"*","hover_target"); for (var j = 0; j< hovertargets.length; j++) { target = hovertargets[j]; target.style.display="none"; } } function iehover_display(container) { var hovertargets = getElementsByClassName(container,"*","hover_target"); for (var j = 0; j< hovertargets.length; j++) { target = hovertargets[j]; if (hasClass(target,"inline")) { target.style.display="inline"; } else { target.style.display="block"; } } } function iehover() { if(!REG_MSIE.test(navigator.userAgent) && !REG_COMPAT.test(window.document.compatMode)) { return; } var hovercontainers = getElementsByClassName(document.getElementById("bodyContent"),"*","hover_collapse"); for (var i = 0; i<hovercontainers.length; i++) { container = hovercontainers[i]; container.attachEvent('onmouseenter',function(e) {iehover_display(e.srcElement);}); container.attachEvent('onmouseleave',function(e) {iehover_hide(e.srcElement);}); iehover_hide(container); } } addOnloadHook(iehover); /* Inserts random block reasons from RationalWiki:Random_Block_Reasons and per-user block reasons from user's CustomBlockReasons subpage */ function insertAdditionalBlockReasons() { var blockReasonList = document.getElementById("wpBlockReasonList"); if (null != blockReasonList) { // attempt to get a XmlHTTPRequest object var req = false; if (window.XMLHttpRequest) { // for sane browsers req = new XMLHttpRequest(); } else if (window.ActiveXObject) { // oh dear, here's a nickel kid, get yourself a better browser. req = new ActiveXObject("Microsoft.XMLHTTP"); } if (req) { var reasonsArray; var reasonOption; req.open("GET", "http://rationalwiki.org/wiki/index.php?title=RationalWiki:Random_Block_Reasons&action=raw&ctype=text/javascript", false); req.send(null); if (req.status == 200 && req.responseText != "/* Empty */" ) { // split lines in to an array reasonsArray = req.responseText.split("\n"); reason = reasonsArray[Math.floor(Math.random() * reasonsArray.length)]; var randomOptGroup = document.createElement('optgroup'); randomOptGroup.label = "Random block reason"; reasonOption = document.createElement("option"); reasonOption.value = reason; if (typeof(reasonOption.innerText) != "undefined") { reasonOption.innerText = reason; } else { reasonOption.text = reason; } randomOptGroup.appendChild(reasonOption); blockReasonList.appendChild(randomOptGroup); } req.open("GET", "http://rationalwiki.org/wiki/index.php?title=User:" +wgUserName+ "/CustomBlockReasons&action=raw&ctype=text/javascript", false); req.send(null); if (req.status == 200 && req.responseText != "/* Empty */") { // split lines in to an array reasonsArray = req.responseText.split("\n"); var customOptGroup = document.createElement('optgroup'); customOptGroup.label = "Custom block reasons"; var i; for (i=0;i<reasonsArray.length;++i) { reason = reasonsArray[i]; reasonOption = document.createElement("option"); reasonOption.value = reason; if (typeof(reasonOption.innerText) != "undefined") { reasonOption.innerText = reason; } else { reasonOption.text = reason; } customOptGroup.appendChild(reasonOption); } blockReasonList.appendChild(customOptGroup); } } } } addOnloadHook(insertAdditionalBlockReasons); /* addsectionbottom Add a new section link to the bottom of discussion pages function addsectionbottom() { if (!wgIsArticle) return; if ((document.URL.indexOf('?')>=0) && (document.URL.indexOf('action=delete')>=0)) return; var caplus; if (!(caplus = document.getElementById("ca-addsection"))) return; var addsection = document.createElement("span"); addsection.innerHTML = "<h3> <a " + "href=\"" + caplus.childNodes[0].getAttribute("href") + "\" title=\"" + caplus.childNodes[0].getAttribute("title") + "\" accesskey=\"" + caplus.childNodes[0].getAttribute("accesskey") + "\" >" + (skin == "vector" ? "<span> Add topic</span>" : "<span> Add section</span>" ) + "</a> </h3>" addsection.className = "noprint"; addsection.id = "addsectionbottom"; var content; if (!(content = document.getElementById("bodyContent"))) return; var catlinks = document.getElementById("catlinks"); if (catlinks == null) { content.appendChild(addsection); } else { content.insertBefore(addsection, catlinks); } } addOnloadHook(addsectionbottom); */ /* override for inserMyNames */ if (typeof insertMyNameOverride == 'undefined') insertMyNameOverride = false; /* insertMyName replaces the contents of a span with the id myName with the name of the user viewing the page */ function insertMyName() { var nameSpan = document.getElementById("myName"); if (nameSpan && wgUserName) { nameSpan.innerHTML = wgUserName + (insertMyNameOverride ? '<sub>fake name</sub>' : ''); } } addOnloadHook(insertMyName); /* insertMyName2 uses class instead of id, allows more than one replacement per page */ function insertMyName2() { if (!wgUserName) return; var nameSpans = getElementsByClassName(document.getElementById("bodyContent"),"*","myName"); newtext = wgUserName + (insertMyNameOverride ? '<sub>fake name</sub>' : ''); for (var i=0;i<nameSpans.length;++i) { nameSpans[i].innerHTML = newtext; } } addOnloadHook(insertMyName2); /* Random CP page [[User:Nx]] 01:24, 9 April 2009 (EDT) */ //Toggle indentation randomcpindent = false; function randomCP() { if (n_randompage = document.getElementById('n-randompage')) { if (wgNamespaceNumber == 100 || wgNamespaceNumber == 101) { n_randomcp = document.createElement('li'); n_randomcp.id = "n-randomcp"; n_randomcp.innerHTML = "<a"+' href="/wiki/Special:Random/Conservapedia" title="Load a random page from Conservapedia namespace">Random CP page</a>'; if (randomcpindent) { n_randomcpul = document.createElement('ul'); n_randomcpul.appendChild(n_randomcp); n_randomcp = n_randomcpul; } n_randompage.parentNode.insertBefore(n_randomcp,n_randompage.nextSibling); } } } addOnloadHook(randomCP) /* Dawkins's Weasel by Jeeves */ var _tags_to_evolve = new Array(); var _offspring_per_generation = 1000; var _point_mutation_chance = 0.03; // Why can't javascript be C, blast it. var _A = "A".charCodeAt(0); var _Z = "Z".charCodeAt(0); var _a = "a".charCodeAt(0); var _z = "z".charCodeAt(0); function init_tagged_string(tag) { // fuck IE. Hard. In the arse. var content = tag.textContent != undefined ? tag.textContent : tag.innerText; // probably if we have more than 100 chars, it'll take too long to converge. if (content.length <= 100) { if (!tag.needle) { tag.needle = content; } var mutant = ""; for (var i = 0; i < content.length; ++i) { var rand = Math.floor(Math.random() * 26); var c = content.charCodeAt(i); if (c >= _A && c <= _Z) { c = _A + rand; } else if (c >= _a && c <= _z) { c = _a + rand; } mutant = mutant + String.fromCharCode(c); } if (tag.textContent != undefined) { tag.textContent = mutant; } else { tag.innerText = mutant; } _tags_to_evolve.push(tag); } } function give_birth(tag) { var needle = tag.needle; var haystack = tag.textContent != undefined ? tag.textContent : tag.innerText; var fittest = ""; var fittestDelta = tag.textContent != undefined ? tag.textContent.length + 1 : tag.innerText.length + 1; var kiddies = _offspring_per_generation; while (--kiddies >= 0) { var kiddy = ""; var kiddyDelta = 0; for (var i = 0; i < haystack.length; ++i) { var c = haystack.charCodeAt(i); var target = needle.charCodeAt(i); if (c >= _A && c <= _Z) { var prob = Math.random(); if (prob <= _point_mutation_chance) { var rand = Math.floor(Math.random() * 26); c = _A + rand; } } else if (c >= _a && c <= _z) { var prob = Math.random(); if (prob <= _point_mutation_chance) { var rand = Math.floor(Math.random() * 26); c = _a + rand; } } kiddy = kiddy + String.fromCharCode(c); if (c != target) { ++kiddyDelta; } } if (fittestDelta > kiddyDelta) { fittestDelta = kiddyDelta; fittest = kiddy; } } if (tag.textContent != undefined) { tag.textContent = fittest; } else { tag.innerText = fittest; } return fittestDelta; } function shag_like_bunnies(tag) { var delta = give_birth(tag); if (delta != 0) { setTimeout(function() {shag_like_bunnies(tag);}, 1000); } } function start_string_to_evolve(span) { init_tagged_string(span); setTimeout(function() {shag_like_bunnies(span);}, 1000); } function setOnclick(stuff,tag) { stuff.onclick = function() {start_string_to_evolve(tag);} } function init_strings_to_evolve() { var spans = getElementsByClassName(document.getElementById("bodyContent"),"*","evolve"); for (i = 0; i < spans.length; ++i) { startbutton = document.createElement("span"); startbutton.style.cursor = "pointer"; startbutton.innerHTML = "start"; startbutton.style.color = "blue"; setOnclick(startbutton,spans[i]); spans[i].parentNode.insertBefore(startbutton,spans[i]) space = document.createElement("TEXT"); if (space.textContent != undefined) { space.textContent = " "; } else { space.innerText = " "; } spans[i].parentNode.insertBefore(space,spans[i]) } } addOnloadHook(init_strings_to_evolve); //end Weasel /* Allows customisation of the sidebar *************** */ function ModifySidebar(action, section, name, link) { try { switch (section) { case "languages": var target = "p-lang"; break; case "toolbox": var target = "p-tb"; break; case "navigation": var target = "p-navigation"; break; default: var target = "p-" + section; break; } if (action == "add") { var node = document.getElementById(target) .getElementsByTagName('div')[0] .getElementsByTagName('ul')[0]; var aNode = document.createElement('a'); var liNode = document.createElement('li'); aNode.appendChild(document.createTextNode(name)); aNode.setAttribute('href', link); liNode.appendChild(aNode); liNode.className='plainlinks'; node.appendChild(liNode); } if (action == "remove") { var list = document.getElementById(target) .getElementsByTagName('div')[0] .getElementsByTagName('ul')[0]; var listelements = list.getElementsByTagName('li'); for (var i = 0; i < listelements.length; i++) { if (listelements[i].getElementsByTagName('a')[0].innerHTML == name || listelements[i].getElementsByTagName('a')[0].href == link) { list.removeChild(listelements[i]); } } } } catch(e) { // lets just ignore what's happened return; } }