MediaWiki:Common.js

From RationalWiki
Jump to navigation Jump to search

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 / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
/* 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 ( mw.config.get('wgAjaxLicensePreview') ) {
      licenses.onchange();
    }
  }
}

if (mw.config.get('wgPageName') == 'Special:Upload') 
{
  $(document).ready(fixLicenseSelector);
  mw.loader.load( '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" );
    var Button, ButtonLink, ButtonText, CreateLink, CreateButton;

    for ( var i = 0; i < Tables.length; i++ ) {
        if ( ! hasClass( Tables[i], "collapsible" ) ) continue

        /* 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 );
        }

        // If there's already a button only add the JS handlers so the user can
        // add buttons at any location.
        Button = $(Tables[i]).find('.collapseButton')
        if (window.debug) {
            console.log(Tables[i])
            console.log(Button)
        }
        if ( Button.length > 0 ) {
            CreateButton = false;
            ButtonLink = Button.find('a')
            if ( ButtonLink.length === 0 ) {
                ButtonLink = document.createElement( "a" )
                ButtonText = document.createTextNode( collapseCaption );
                CreateLink = true;
            }
            else {
                ButtonLink = ButtonLink[0]
                CreateLink = false;
            }
            Button = Button[0]
        }
        else {
            Button     = document.createElement( "span" );
            ButtonLink = document.createElement( "a" );
            ButtonText = document.createTextNode( collapseCaption );
            Button.className = "collapseButton";  //Styles are declared in Common.css
            CreateLink = true;
            CreateButton = true;
        }

        ButtonLink.style.color = Header.style.color;
        ButtonLink.setAttribute( "id", "collapseButton" + id );
        ButtonLink.setAttribute( "href", "javascript:collapseToggleTable('" + id + "');" );

        if ( CreateLink ) {
            ButtonLink.appendChild( ButtonText );
            Button.appendChild( document.createTextNode( "[" ) );
            Button.appendChild( ButtonLink );
            Button.appendChild( document.createTextNode( "]" ) );
        }

        if ( CreateButton ) {
            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 );
            }
        }
    }

 
}

$( 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;
			}
		}
	}
}

$(document).ready(addOnclickEventsToCollapsedCommentLinks);

/*
  override for inserMyNames
*/

if (!('insertMyNameOverride' in window)) window.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 && mw.config.get('wgUserName')) {
		nameSpan.innerHTML = mw.config.get('wgUserName') + (window.insertMyNameOverride ? '<sub>fake name</sub>' : '');
	}
}

$(document).ready(insertMyName);

/*
  insertMyName2
    uses class instead of id, allows more than one replacement per page
*/

function insertMyName2() {
  if (!mw.config.get('wgUserName')) return;
  newtext = mw.config.get('wgUserName') + (window.insertMyNameOverride ? '<sub>fake name</sub>' : '');
  $('#bodyContent .myName').each( function() {
    this.innerHTML = newtext;
  } );
}

$(document).ready(insertMyName2);

/*
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()
{
	$("#bodyContent .evolve").each(function()
	{
		startbutton = document.createElement("span");
		startbutton.style.cursor = "pointer";
		startbutton.innerHTML = "start";
		startbutton.style.color = "blue";
		setOnclick(startbutton, this);
		this.parentNode.insertBefore(startbutton, this)
		space = document.createElement("TEXT");
		if (space.textContent != undefined)
		{
			space.textContent = " ";
		} else
		{
			space.innerText = " ";
		}
		this.parentNode.insertBefore(space, this)
	})
}

$(document).ready(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;
    }
}

/****************************************
 * Template:a
 ****************************************/
$(document).on('ready', function() {
	var msgs = {
		a: 'View stored copy at archive.is',
		w: 'View stored copy at wayback machine',
	}
 
	// Unfortunatly adding a title attribute can't be done with wiki markup
	$('div#content .archive_link > sup > a.external').each(function() {
		$(this).attr('title', msgs[$(this).html()])
	})
});
$(document).on('ready', function() {
	var msgs = {
		a: 'View stored copy at archive.is',
		w: 'View stored copy at wayback machine',
	}
 
	// Unfortunatly adding a title attribute can't be done with wiki markup
	$('div#content .archive_link > sup > a.external').each(function() {
		$(this).attr('title', msgs[$(this).html()])
	})
});