MediaWiki:Common.js

From the Super Mario Wiki, the Mario encyclopedia
Revision as of 00:32, December 24, 2017 by Turboo (talk | contribs)
Jump to navigationJump to search

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.
/* Any JavaScript here will be loaded for all users on every page load. */

/* Main Page maintain link on shorter side */
if (mw.config.get('wgTitle') === 'Main Page') {
	function mainPageMaintain() {
		var leftHeight = $('#featured').height() + 10 + $('#poll').height() + 10 + $('#shroom').height();
		var rightHeight = $('#news').height() + 10 + $('#dyk').height();
		if ( rightHeight > leftHeight ) {
			$("#maintain-right").hide();
			$("#maintain-left").show();
		}
	}
	$(mainPageMaintain);
}

/* Automatically add Aboutfile template to file upload description. Source: nl.wikipedia.org/wiki/MediaWiki:Common.js */
if (mw.config.get('wgCanonicalSpecialPageName') === 'Upload' && !document.getElementById('wpForReUpload') && !document.getElementsByClassName('mw-destfile-warning')[0] && !document.getElementsByClassName('error')[0]) {
	function loadAutoAboutfileTemplate() {
		uploadDescription = document.getElementById('wpUploadDescription');
		var doubleBracket = '{' + '{';
		uploadDescription.value = doubleBracket + 'aboutfile\n|1=Subject of the image\n|2=Where you found the image\n|3=Artist\n|4=Describe edits, if any\n|5=Other versions (use file link)\n}}\n' + doubleBracket + 'uncategorized}}';
	}
	$(loadAutoAboutfileTemplate);
}

/* Add a drop-down menu for CheckUser reasons */
if (mw.config.get('wgCanonicalSpecialPageName') === 'CheckUser') {
	function checkUserReasonMenu() {
		var field = document.getElementById('checkreason');
		var menu = '<select id="checkreason" name="reason" style="width:303px;height:23px;margin-top:1px;" onchange="checkUserOther(this.options[this.selectedIndex].value)"><option value="" selected="selected">Please select a reason...</option><option value="Routine new user check">Routine new user check</option><option value="Suspected sockpuppet account">Suspected sockpuppet account</option><option value="Matching a vandal account">Matching a vandal account</option><option value="Other">Other</option></select>';
		field.outerHTML = menu;
	}
	$(checkUserReasonMenu);

	function checkUserOther(name) {
		if (name == 'Other') {
			var menu = document.getElementById('checkreason');
			var field = '<input id="checkreason" maxlength="150" value="" size="46" name="reason">';
			menu.outerHTML = field;
		}
	}
}

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

setUpSynchTable();

/******************************************************************************
 * Shroom Youtube Popups                                                      *
 ******************************************************************************/

function shroomYoutubeController () {
  
    var spans = document.getElementsByClassName("shroomYoutube"); 

    if (spans.length == 0) {
        return;
    }

    this.APIReady = false;
    this.APIContinue = function () {};
    onYouTubeIframeAPIReady = function () {
        this.APIReady = true;
        this.APIContinue;
    }.bind(this);
    this.players = [];

    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    this.containerDiv = document.createElement("div");
    this.containerDiv.className = "shroomYoutubeContainer";
    var shadeDiv = document.createElement("div");
    shadeDiv.className = "shroomYoutubeShade";
    shadeDiv.onclick = this.hideContainer.bind(this);
    this.bgDiv = document.createElement("div");
    this.bgDiv.className = "shroomYoutubeBg";
    var throbber = document.createElement("div");
    throbber.className = "shroomThrobber";
    this.bgDiv.appendChild(throbber);
    var closeButton = document.createElement("div");
    closeButton.className = "shroomYoutubeClose";
    closeButton.onclick = this.hideContainer.bind(this);
    this.bgDiv.appendChild(closeButton);
    this.containerDiv.appendChild(shadeDiv);
    this.containerDiv.appendChild(this.bgDiv);
    document.body.appendChild(this.containerDiv);

    for (var i = 0; i < spans.length; i++) {
        new shroomYoutubeInstance (this, spans[i]) 
    }
  
}

function shroomYoutubeInstance (parent, span) {
  
  this.parent = parent;
  this.span = span;
  this.link = this.span.getElementsByTagName("a")[0];
  this.videoWrapper = document.createElement("div");
  this.videoWrapper.class = "shroomYoutubeVideoWrapper";
  parent.bgDiv.appendChild(this.videoWrapper);
  this.link.onclick = this.showWrapper.bind(this);
  
}

shroomYoutubeInstance.prototype.showWrapper = function (e) {
  
  if (e.button == 0 &&
      !e.ctrlKey &&
      !e.altKey &&
      !e.shiftKey) {
    if (!this.parent.APIReady) {
      this.parent.containerDiv.className="shroomYoutubeContainer visible";
      this.parent.APIContinue = this.span.onclick; //should invoke this function again...
      return false;
    } else if (this.videoWrapper.firstChild == null) {
      this.videoWrapper.appendChild(document.createElement("div"));
      var player = new YT.Player(this.videoWrapper.firstChild, {
        width: '420',
        height: '315',
        videoId: this.span.dataset.video,
        events: {
          'onReady': this.onPlayerReady.bind(this),
          'onStateChange': this.onPlayerStateChange.bind(this)
        }
      });
      this.parent.addPlayer(player);
    }
    var visibles = this.parent.containerDiv.getElementsByClassName("visible");
    while (visibles.length > 0) {
      visibles[0].className="shroomYoutubeVideoWrapper";
    }
  
    this.parent.containerDiv.className="shroomYoutubeContainer visible";
    this.videoWrapper.className="shroomYoutubeVideoWrapper visible";
    return false;
  } else {
    return true;
  }
  
}

shroomYoutubeInstance.prototype.onPlayerStateChange = function (e) {
  
  switch (e.data) {
    case -1:
    case 0:
    case 5:
      this.span.className = "shroomYoutube stopState";
      break;
    case 1:
      this.parent.pauseOthers(e);
    case 3:
      this.span.className = "shroomYoutube playState";
      break;
    case 2:
      this.span.className = "shroomYoutube pauseState";
      break;
  }
  
}

shroomYoutubeInstance.prototype.onPlayerReady = function (e) {
  e.target.playVideo();
}

shroomYoutubeController.prototype.pauseOthers = function(e) {
  for (var i = 0; i < this.players.length; i++) {
    if (this.players[i] != e.target) {
      this.players[i].pauseVideo();
    }
  }
}

shroomYoutubeController.prototype.hideContainer = function () {
  this.containerDiv.className="shroomYoutubeContainer";
}

shroomYoutubeController.prototype.addPlayer = function (player) { 
  
  this.players.push(player);
  
}

new shroomYoutubeController ();


/** pollspinner *****************************************************************
 *
 * description: this shows every awards poll to a user on the main page
 * maintainers: 2257
 */

function pollspinner_boxSetup(nextPoll) {

    var spinner = document.getElementsByClassName("pollspinner")[0];
    spinner.className = "pollspinner animated throbbing";

    var pollSubstitute = nextPoll.getElementsByClassName("pollspinner_poll")[0];
    pollSubstitute.id = "PDI_container" + pollSubstitute.dataset.pollid;

    while (pollSubstitute.childNodes.length > 0) {
        pollSubstitute.removeChild(pollSubstitute.childNodes[0]);
    }

    this['pd_callback_' + pollSubstitute.dataset.pollid] = pollspinner_callback;

    var pdscript = document.createElement("script");
    pdscript.type = "text/javascript";
    pdscript.language = "javascript";
    pdscript.src = "https://s3.polldaddy.com/p/" + pollSubstitute.dataset.pollid + ".js";
    pdscript.onload = function() {

        var spinner = document.getElementsByClassName("pollspinner")[0];
        spinner.className = "pollspinner animated";

        var votebuttonOuter = nextPoll.getElementsByClassName("pds-votebutton-outer")[0];        
        var skip = document.createElement("a");
        skip.className = "pds-vote-button pollspinner_skip";
        skip.appendChild(document.createTextNode("Skip"));
        skip.addEventListener("click", pollspinner_skip.bind(null, spinner));
        votebuttonOuter.insertBefore(skip, votebuttonOuter.getElementsByClassName("pds-vote-button")[0].nextSibling);

        var pdsBoxTop = nextPoll.getElementsByClassName("pds-box-top")[0];
        var throbber = document.createElement("div");
        throbber.className = "throbber";
        throbber.appendChild(document.createTextNode("Loading next poll..."));
        pdsBoxTop.appendChild(throbber);

        nextPoll.dataset.loaded = true;
        pollspinner_activate(nextPoll);
    }
    pollSubstitute.appendChild(pdscript);

}

function pollspinner_getNext_random(unansweredPolls) {

    return Math.floor(Math.random() * unansweredPolls.length);
    
}

function pollspinner_getNext_sequential(unansweredPolls) {

    return 0;

}

function pollspinner_activate(element) {

    var spinner = document.getElementsByClassName("pollspinner")[0];
    var activeBoxes = spinner.querySelectorAll("[data-status='active']");
    for (var i = 0; i < activeBoxes.length; i++) {
        activeBoxes[i].dataset.status = "unanswered";
    }
    
    var visibleBoxes = spinner.getElementsByClassName("pollspinnerbox visible");
    while (visibleBoxes.length > 0) {
        visibleBoxes[0].className = visibleBoxes[0].className.replace(/ *visible */g, " ") + " hidden";
    }

    element.dataset.status = "active";
    spinner.style.height = element.offsetHeight + "px";
    element.className = element.className.replace(/ *hidden */g, " ") + " visible";

}


function pollspinner_getNext() {
    
    var spinner = document.getElementsByClassName("pollspinner")[0];

    var unansweredPolls = spinner.querySelectorAll("[data-status='unanswered']");
    var skippedPolls = spinner.querySelectorAll("[data-status='skipped']");
    
    if (unansweredPolls.length > 0) {
        
        var nextPoll;

        switch (spinner.dataset.order) {
            case "sequential":
                nextPoll = pollspinner_getNext_sequential(unansweredPolls);
                break;
            case "random":
            default:
                nextPoll = pollspinner_getNext_random(unansweredPolls);
                break;
        }

        if (unansweredPolls[nextPoll].dataset.loaded) {
            pollspinner_activate(unansweredPolls[nextPoll]);
        } else {
            pollspinner_boxSetup(unansweredPolls[nextPoll]);
        }
        
    } else if (skippedPolls.length > 0) {
        
        for (var i = 0; i < skippedPolls.length; i++) {
            skippedPolls[i].dataset.status = "unanswered";
        }

        pollspinner_getNext();
        
    } else {

        var end = spinner.getElementsByClassName("pollspinnerbox end");
        
        if (mw.config.get("wgUserName") == null) {
            
            end[0].innerHTML = "The power of the Votes is restored to the poll... and it's all thanks to you! Thank you!";
            
        } else {
            
            end[0].innerHTML = mw.config.get("wgUserName") + "! The power of the Votes is restored to the poll... and it's all thanks to you! Thank you, " + mw.config.get("wgUserName") + "!";
            
        }
        
        pollspinner_activate(end[0]);
    }
    
}

function pollspinner_callback( json ) {
    
    var obj = jQuery.parseJSON( json );
    
    if ( obj.result == 'registered' || obj.result == 'already-registered' ) {
        
        var spinner = document.getElementsByClassName("pollspinner")[0];

        var active = document.querySelectorAll("[data-status='active']")[0];
        active.dataset.status = "answered";
        var pdsBoxTop = active.getElementsByClassName("pds-box-top")[0];
        var throbber = document.createElement("div");
        throbber.className = "throbber";
        throbber.appendChild(document.createTextNode("Loading next poll..."));
        pdsBoxTop.appendChild(throbber);

        pollspinner_getNext();        
    }
}

function pollspinner_skip (spinner) {

    var activePoll = spinner.querySelectorAll("[data-status='active']");
    if (activePoll.length > 0) {
        activePoll[0].dataset.status = "skipped";
        pollspinner_getNext();
    }
    
}

function pollspinner_begin (intro){

    this.className += " clicked"; 
    intro.dataset.status = "answered";
    pollspinner_getNext();

}

function pollspinner_setup () {
    
    var spinner = document.getElementsByClassName("pollspinner")[0];
    
    if (spinner != null) {
        
        var preload = new Image();
        preload.src = "https://wiki.userpedia.net/images/8/82/Pollthrobber.png";
        
        spinner.className = "pollspinner animated";
        var pollSpinnerBoxes = spinner.getElementsByClassName("pollspinnerbox");
        
        for (var i = 0; i < pollSpinnerBoxes.length; i++) {
            pollSpinnerBoxes[i].dataset.status = "unanswered";
        }

        var end = document.createElement("div");
        end.className = "pollspinnerbox end";
        end.dataset.status = "end";
        spinner.appendChild(end);
        
        var intro = spinner.getElementsByClassName("pollspinnerbox intro")[0];
        if (intro != null) {
            var begin = intro.getElementsByClassName("pollspinner_begin")[0];
            begin.addEventListener("click", pollspinner_begin.bind(begin, intro));
            pollspinner_activate(intro);
        } else {
            pollspinner_getNext();
        }

    }
}

pollspinner_setup();