User:Donkey/common.js

From Brickipedia, the LEGO Wiki

Note: After publishing, 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: Press Ctrl-F5.
mw.loader.localLoad = function( url ) { return mw.loader.load( '//minecraft.gamepedia.com/index.php?title=' + url + '&action=raw&ctype=text/javascript' ); };

/* Auto-refresh button on Special:RecentChanges */
function setCookie(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}
var ajaxPages = new Array("Special:RecentChanges");
var ajaxRCOverride = false;
var rcRefresh = 30000;
function ajaxRC() {
	appTo = $(".firstHeading");
	appTo.append('&nbsp;<span style="position:absolute; right:75px;"><span style="position:relative; top:2px;"><span style="position:relative; top:-12px; right:-15px;" id="autoRefreshProgress"><img src="/images/loader.gif" border="0" alt="AJAX operation in progress" /></span><span style="font-size: xx-small; cursor:help;" title="Automatically refresh the current page every ' + Math.floor(rcRefresh / 1000) + ' seconds">AUTO-REFRESH:</span><input type="checkbox" id="autoRefreshToggle"></span></span>');
	$("#autoRefreshToggle").click(function () {
		setCookie("ajaxRC", $("#autoRefreshToggle").is(":checked") ? "on" : "off")
		loadRCData()
	});
	$("#autoRefreshProgress").hide();
	if (getCookie("ajaxRC") == "on" || ajaxRCOverride) {
		$("#autoRefreshToggle").attr("checked", "checked");
		setTimeout("loadRCData();", rcRefresh);
	}
}
function loadRCData() {
	if (!$("#autoRefreshToggle").is(":checked")) return;
	$('#autoRefreshProgress').show()
	$(article).load(location.href + " " + article + " > *", function (data) {
		$(article + " .mw-collapsible").makeCollapsible();
		$('#autoRefreshProgress').hide()
		if ($("#autoRefreshToggle").is(":checked")) setTimeout("loadRCData();", rcRefresh);
	});
}
$(function () {
	article = "#bodyContent";
	for (x in ajaxPages) {
		if (mw.config.get('wgPageName') == ajaxPages[x] && $("#autoRefreshToggle").length == 0) ajaxRC();
	}
});

function setUpSynchTable () {
  var tables = document.getElementsByClassName("awardsSynchronisedTable");
  for (var k = 0; k < tables.length; k++) {
    var rows = tables[k].rows;
    for (var i = 0; i < rows.length; i++) {
      var cells = rows[i].cells;
      for (var j = 0; j < cells.length; j++) {
        cells[j].style.verticalAlign = "top";
        var synchDiv = document.createElement("DIV");
        synchDiv.style.position = "relative";
        synchDiv.className = "synchDiv";
        var childs = cells[j].childNodes;
        while (childs.length > 0) {
          synchDiv.appendChild(childs[0]);
        }
        cells[j].appendChild(synchDiv);
      }
    }
  }
  if (tables.length > 0) {
    document.onscroll = synchTableOnScroll;
  }
}

function synchTableOnScroll() {
  
  var divs = document.getElementsByClassName("synchDiv");
  for (var i = 0; i < divs.length; i++) {
    var parent = divs[i].parentNode;
    var parentRect = parent.getBoundingClientRect();
    var offset;
    if (window.innerHeight > divs[i].offsetHeight) {
      offset = Math.min(Math.max(-1 * parentRect.top, 0), parent.clientHeight - divs[i].offsetHeight);
    } else {
      offset = Math.min(Math.max(-1 * parentRect.top / (parent.clientHeight - window.innerHeight) * (parent.clientHeight - divs[i].offsetHeight), 0), parent.clientHeight - divs[i].offsetHeight);
    }
    divs[i].style.top = offset + "px";
  }
}

/** Scripts **/


// [[User:Majr/inputCounter.js]]
// Adds a character counter to input fields
mw.loader.localLoad( 'User:Majr/inputCounter.js' );

// [[User:Majr/codeLinks.js]]
mw.loader.localLoad( 'User:Majr/codeLinks.js' );

// [[User:Majr/renderConsoleOutput.js]]
// Allows the output wikitext of the lua console to be rendered
if ( $( '#mw-scribunto-console' ).length ) {
	mw.loader.localLoad( 'User:Majr/renderConsoleOutput.js' );
}

/** General fixes **/

$( function() { 
'use strict';


// Add a subpages link to pages
if ( mw.config.get( 'wgArticleId' ) != 0 ) {
	mw.util.addPortletLink (
		'p-tb',
		'/Special:PrefixIndex/' + mw.config.get( 'wgRelevantPageName' ) + '/',
		'Subpages',
		't-subpages',
		'Subpages of the article'
	);
}

/** Mostly direct code from [[User:Majr/hydra.js]] **/

// Modify the editing toolbar
if ( $.inArray( mw.config.get( 'wgAction' ), [ 'edit', 'submit' ] ) > -1 ) {
	mw.loader.using( 'ext.wikiEditor.toolbar', function() {

		// Modify the text added by the signature button.
		var $button = $( '#wikiEditor-section-main > .group-insert > a[rel="signature"]' );
		if ( $button.length ) {
			var action = $button.data( 'action' );
			action.options.pre = '<span class=nowrap>~~' + '~~</span>';
			$button.data( 'action', action );
		}

		// Add an option to insert <code> tags
		$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
			section: 'advanced',
			group: 'format',
			tools: {
				code: {
					label: 'Code formatting',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/6/62/Toolbar_code.png',
					action: {
						type: 'encapsulate',
						options: { pre: '<code>', post: '</code>' }
					}
				}
			}
		// Add an option to insert template braces
		} ).wikiEditor( 'addToToolbar', {
			section: 'advanced',
			group: 'insert',
			tools: {
				sign: {
					label: 'Template',
					type: 'button',
					icon: '//upload.wikimedia.org/wikipedia/commons/4/43/Button-template.png',
					action: {
						type: 'replace',
						options: { pre: '{{', post: '}}' }
					}
				}
			}
		// Add characters to the symbols insert page
		} ).on( 'wikiEditor-toolbar-buildSection-characters', function (event, section) {
      	  section.pages.symbols.characters.push( '¦', '²{', '}²' );
  		} );
	} );
}

// Add 0th section edit button to first infobox which is in the 0th section
var $firstInfobox = $( '.notaninfobox' ).first();
if ( !$firstInfobox.prevAll( 'h1, h2, h3, h4, h5, h6' ).length ) {
	$firstInfobox.children( '.infobox-title' ).css( 'padding-left', 50 ).prepend(
		$( '<span>' ).addClass( 'mw-editsection' ).css( {
			float: 'right',
			lineHeight: 'inherit'
		} ).append(
			'[',
			$( '<a>' ).prop( 'href', '/' + mw.config.get( 'wgPageName' ) + '?action=edit&section=0' ).text( 'edit' ),
			']'
		)
	);
}

} );

/** Testing stuff **/

mw.loader.load( '//minecraft.gamepedia.com/index.php?title=User:Majr/goToTop.js&action=raw&ctype=text/javascript' );

/* Welcome script from [[User:ITechieGamer]] */

$(document).ready(function() {
  // Add a new portal before the social profiles in the toolbox
  var $welcomeGroup = $('<div class="portal collapsed" role="navigation" id="p-welcome" aria-labelledby="p-welcome-label"></div>').append($('<h3 id="p-welcome-label">Welcoming users</h3>')),
      $welcomeBody = $('<div class="body"></div>'),
      $goodWelcomeLink = $('<a id="t-goodwelcome" href="#" title="Welcome a user">Good welcome</a>'),
      $badWelcomeLink = $('<a id="t-badwelcome" href="#" title="Welcome a user">Bad welcome</a>'),
      $newUserLink = $('<a id="t-newusers" href="/index.php?title=Special:ListAllUsers&group=&username=&editsOnly=0&creationSort=1" title="List of new users">New users</a>');
  $($welcomeGroup.append($welcomeBody.html($('<ul id="p-welcome-list"></ul>').append($('<li/>').html($goodWelcomeLink)).append($('<li/>').html($badWelcomeLink)).append($('<li/>').html($newUserLink))))).insertBefore('#p-socialProfiles');

  $('#t-goodwelcome').click( function() {
    // Notify the user for the username
    var username = prompt('Who would you like to good welcome?');
    if(username == '' || username == null) return;

    // Welcome the user
    window.open('/index.php?action=edit&section=new&title=User_talk:'+username+'&preload=Template:Welcome&preloadtitle=Welcome%21&preloadparams%5b%5d='+username+'&preloadparams%5b%5d=%7e', '_blank');
  });

  $('#t-badwelcome').click( function() {
    // Notify the user for the username
    var username = prompt('Who would you like to bad welcome?');
    if(username == '' || username == null) return;

    // Welcome the user
    window.open('/index.php?action=edit&section=new&title=User_talk:'+username+'&preload=Template:Welcome/bad&preloadtitle=Welcome&preloadparams%5b%5d=%7e', '_blank');
  });
});

/* Add image at the top right corner to blocked users' userpages */

if ( mw.config.get( 'wgRelevantUserName' ) ) {
	$( function() {
		'use strict';
		var title = 'Blocked user';
		( new mw.Api() ).get( {
			action: 'query',
			format: 'json',
			list: 'blocks',
			formatversion: 2,
			bkusers: mw.config.get( 'wgRelevantUserName' )
		} ).done( function( data ) {
			if ( data.query.blocks.length ) {
				$( '.mw-indicators' ).prepend(
					'<a href="//commons.wikimedia.org/wiki/File:Blocked_user.svg" class="mw-indicator" id="gadget-blockindicator" title="' + title + '">' +
						'<img src="//upload.wikimedia.org/wikipedia/commons/4/4f/Blocked_user.svg" height="20">' +
					'</a>'
				);
			}
		} );
	} );
}

// Scripts, some imported from Wiki Pedia, and modified to use on this wiki //

mw.loader.load( '//commons.wikimedia.org/w/index.php?title=MediaWiki:Gadget-HotCat.js&action=raw&ctype=text/javascript' );

mw.loader.load('//en.wikipedia.org/w/index.php?title=Mediawiki:Gadget-popups.js&action=raw&ctype=text/javascript');

mw.loader.load('//m.wikimedia.org/w/index.php?title=Mediawiki:Gadget-markblocked.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=Mediawiki:Gadget-edittop.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=Mediawiki:Gadget-charinsert.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=Mediawiki:Gadget-extlinks.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:PrimeHunter/My_subpages.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:The_Evil_IP_address/hdedit.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Theopolisme/ajaxWatchlist.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Equazcion/SafetyEdit.js&action=raw&ctype=text/javascript');

mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ReferenceTooltips.js&action=raw&ctype=text/javascript');
/**
 * charinsert loader
 */

$( function () {
    var tab, tablink;

    tab = document.getElementById('ca-addsection');
    if ( !tab ) {
        return;
    }

    tablink = tab.getElementsByTagName('a')[0];
    if ( !tablink ) {
        return;
    }

    tablink.firstChild.nodeValue = '+';
    if ( mw.config.get( 'skin' ) === 'monobook' ) {
      tablink.style.paddingLeft = ".4em";
      tablink.style.paddingRight = ".4em";
    }
});

// This only shows alerts for things after this handler is installed of course.
// Because this is a gadget, error reporting can thus be inconsistent.
var originalErrorHandler = window.onerror || null;
// Column and error args are optional
window.onerror = function ( message, url, line, colomn, error ) {
	var $msg = $( '<p>' );
	if ( url ) {
		$( '<span>' )
			.text( url + ' at line ' + line + ': ' )
			.appendTo( $msg );
	}
	$( '<span>' )
		.text( message )
		.appendTo( $msg );

	mw.notify( $msg, {
		autoHide: true,
		autoHideSeconds: 10,
		tag: null,
		title: 'An error occured:',
		type: 'error'
	} );
	if (originalErrorHandler) {
		return originalErrorHandler.apply(this, arguments);
	}
};
// unbind on leaving the page
$( window )
	.on( 'unload', function () {
		window.onerror = originalErrorHandler;
	} );

$( function() {
	'use strict';
	var restrictions = mw.config.get( 'wgRestrictionEdit' );
	if ( restrictions ) {
		if ( restrictions.indexOf( 'sysop' ) !== -1 ) {
			$( '.mw-indicators' ).prepend( '<img title="Page protected" id="gadget-protectionindicators-' + restrictions[ 0 ] + '" src="//upload.wikimedia.org/wikipedia/commons/5/59/Padlock.svg" height="20" />' );
		} else if ( restrictions.indexOf( 'autoconfirmed' ) !== -1 ) {
			$( '.mw-indicators' ).prepend( '<img title="Semi protected page" id="gadget-protectionindicators-' + restrictions[ 0 ] + '" src="//upload.wikimedia.org/wikipedia/commons/f/fc/Padlock-silver.svg" height="20" />' );
		} else if ( restrictions.indexOf( 'director' ) !== -1 ) {
			$( 'mw-indicators' ).prepend( '<img title="This page is director-protected so only directors can edit it." id="gadget-protectionindicators-' + restrictions[ 0 ] + '" src="//upload.wikimedia.org/wikipedia/commons/4/4f/Padlock-purple.svg" height="20" />' );
		}
		}
	}
);

// See [[User:Equazcion/SafetyEdit]]
 
if (  
	// Activate on edits
	(( wgAction == "edit" ) || ( wgAction == "submit" ))){
 
	// Insert the checkbox
	$('#mw-editpage-watch').after('&#160;<input title="Click this box to enable the Save button" class="ruSure" type="checkbox"></input>&#160;<label style="color:#62090B;" title="Enable the Save button" for="ruSure">Enable save</label>');
 
	// Disable the save button on load
	$('input[name="wpSave"]').prop("disabled", true);
 
	// Set summary line to disable enter key saving when it recieves focus.
	// Unbinding on load doesn't work since MediaWiki JS will bind after this. 
	$('#wpSummary').focus(function(){
		$(this).unbind();
	});
 
	// Set the change function for the checkbox
	$('input.ruSure').change(function(){
		if ($(this).prop("checked")){
 
			// We use the name attribute so all potential save buttons (produced by other scripts etc) are affected
			$('input[name="wpSave"]').prop("disabled", false);
 
			// If checked, undo our summary line focus event from above 
			$('#wpSummary').unbind('focus');
 
			// Make enter key on summary line save again
			$('#wpSummary').keydown(function(event){
				if (event.keyCode == 13) {
					$('form#editform').submit();
					return false;
				}
			});
		} else {
			$('input[name="wpSave"]').prop("disabled", true);
 
			// Here we can just unbind without a focus event, because MediaWiki JS won't supercede us again
			$('#wpSummary').unbind();
		}
	});
}
//[[Category:Wikipedia scripts]]

$( '#ca-nstab-user a' ).text( 'Userpage' );
$( '#ca-talk a' ).text( 'Chat' );
$( '#ca-history a' ).text( 'Page history' );