MediaWiki:Common.js: Difference between revisions

From the Kingdom Hearts Wiki, the Kingdom Hearts encyclopedia
Jump to navigationJump to search
No edit summary
No edit summary
Line 33: Line 33:
$('#p-logo a').css('background-image', 'url(' + logos[Math.floor(Math.random() * logos.length)] + ')');
$('#p-logo a').css('background-image', 'url(' + logos[Math.floor(Math.random() * logos.length)] + ')');
*/
*/
// ==================
// ==================
//  Code for Template:Suite3
//  Code for Template:Suite3
Line 55: Line 56:
// ==================
// ==================
//  tabber.js
//  tabber.js
//  Authors: Eric Fortin, Alexia E. Smith
// ==================
// ==================


Line 107: Line 109:
});
});


// ==================
// Auto-refresh recent changes
// Code courtesy of pcj of WoWWiki.
// Code courtesy of pcj of WoWWiki.
// This is a modified version of the WoWWiki site version.
// ==================
 
// Code adds a checkbox at the top of the Special:RecentChanges list, next to the header.
// Ticking it sets a cookie (should be individual to wikis) and starts updating the RC list.
// This occurs silently every 30 seconds without a full page reload occuring.


function setCookie(c_name, value, expiredays) {
function setCookie(c_name, value, expiredays) {
Line 168: Line 168:
});
});


// ============================================================
// ==================
// BEGIN Dynamic Navigation Bars (experimantal)
// Countdown, rewrite by Pecoes
// This script is from Wikipedia. For author attribution, please see http://en.wikipedia.org/w/index.php?title=MediaWiki:Common.js&action=history
// Original script by Splarka + Eladkse
 
// ==================
/* 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 collapseTable(tableIndex) {
var Button = document.getElementById("collapseButton" + tableIndex);
var Table = document.getElementById("collapsibleTable" + tableIndex);
 
if (!Table || !Button) {
return false;
}
 
var Rows = Table.getElementsByTagName("tr");
 
if (Button.firstChild.data == collapseCaption) {
for (var i = 1; i < Rows.length; i++) {
Rows[i].style.display = "none";
}
Button.firstChild.data = expandCaption;
} else {
for (var i = 1; i < Rows.length; i++) {
Rows[i].style.display = Rows[0].style.display;
}
Button.firstChild.data = collapseCaption;
}
}
 
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")) {
NavigationBoxes[tableIndex] = Tables[i];
Tables[i].setAttribute("id", "collapsibleTable" + tableIndex);
 
var Button = document.createElement("span");
var ButtonLink = document.createElement("a");
var ButtonText = document.createTextNode(collapseCaption);
 
Button.style.styleFloat = "right";
Button.style.cssFloat = "right";
Button.style.fontWeight = "normal";
Button.style.textAlign = "right";
Button.style.width = "6em";
 
ButtonLink.setAttribute("id", "collapseButton" + tableIndex);
ButtonLink.setAttribute("href", "javascript:collapseTable(" + tableIndex + ");");
ButtonLink.appendChild(ButtonText);
 
Button.appendChild(document.createTextNode("["));
Button.appendChild(ButtonLink);
Button.appendChild(document.createTextNode("]"));
 
var Header = Tables[i].getElementsByTagName("tr")[0].getElementsByTagName("th")[0];
/* only add button and increment count if there is a header row to work with */
if (Header) {
Header.insertBefore(Button, Header.childNodes[0]);
tableIndex++;
}
}
}
 
for (var i = 0; i < tableIndex; i++) {
if (hasClass(NavigationBoxes[i], "collapsed") || (tableIndex >= autoCollapse && hasClass(NavigationBoxes[i], "autocollapse"))) {
collapseTable(i);
}
}
}
$(createCollapseButtons);
 
/** Dynamic Navigation Bars (experimental) *************************************
*
*  Description: See [[Wikipedia:NavFrame]].
*  Maintainers: UNMAINTAINED
*/
 
// set up the words in your language
var NavigationBarHide = '[' + collapseCaption + ']';
var NavigationBarShow = '[' + expandCaption + ']';
 
// set up max count of Navigation Bars on page,
// if there are more, all will be hidden
// NavigationBarShowDefault = 0; // all bars will be hidden
// NavigationBarShowDefault = 1; // on pages with more than 1 bar all bars will be hidden
var NavigationBarShowDefault = autoCollapse;
 
// shows and hides content and picture (if available) of navigation bars
// Parameters:
//    indexNavigationBar: the index of navigation bar to be toggled
function toggleNavigationBar(indexNavigationBar) {
var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
 
if (!NavFrame || !NavToggle) {
return false;
}
 
// if shown now
if (NavToggle.firstChild.data == NavigationBarHide) {
for (
var NavChild = NavFrame.firstChild;
NavChild != null;
NavChild = NavChild.nextSibling) {
if (hasClass(NavChild, 'NavPic')) {
NavChild.style.display = 'none';
}
if (hasClass(NavChild, 'NavContent')) {
NavChild.style.display = 'none';
}
}
NavToggle.firstChild.data = NavigationBarShow;
 
// if hidden now
} else if (NavToggle.firstChild.data == NavigationBarShow) {
for (
var NavChild = NavFrame.firstChild;
NavChild != null;
NavChild = NavChild.nextSibling) {
if (hasClass(NavChild, 'NavPic')) {
NavChild.style.display = 'block';
}
if (hasClass(NavChild, 'NavContent')) {
NavChild.style.display = 'block';
}
}
NavToggle.firstChild.data = NavigationBarHide;
}
}
 
// adds show/hide-button to navigation bars
function createNavigationBarToggleButton() {
var indexNavigationBar = 0;
// iterate over all < div >-elements
var divs = document.getElementsByTagName("div");
for (
var i = 0;
NavFrame = divs[i];
i++) {
// if found a navigation bar
if (hasClass(NavFrame, "NavFrame")) {
 
indexNavigationBar++;
var NavToggle = document.createElement("a");
NavToggle.className = 'NavToggle';
NavToggle.setAttribute('id', 'NavToggle' + indexNavigationBar);
NavToggle.setAttribute('href', 'javascript:toggleNavigationBar(' + indexNavigationBar + ');');
 
var NavToggleText = document.createTextNode(NavigationBarHide);
NavToggle.appendChild(NavToggleText);
// Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked)
for (
var j = 0;
j < NavFrame.childNodes.length;
j++) {
if (hasClass(NavFrame.childNodes[j], "NavHead")) {
NavFrame.childNodes[j].appendChild(NavToggle);
}
}
NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
}
}
// if more Navigation Bars found than Default: hide all
if (NavigationBarShowDefault < indexNavigationBar) {
for (
var i = 1;
i <= indexNavigationBar;
i++) {
toggleNavigationBar(i);
}
}
 
}
$(createNavigationBarToggleButton);
 
/**
* Countdown
*
* Version: 2.0
*
* Rewrite by Pecoes
* Original script by Splarka + Eladkse
*
* documentation and examples at:
* http://dev.wikia.com/wiki/Countdown
* (some things like languages options removed)
*/


;(function (module, mw, $) {
;(function (module, mw, $) {
Line 520: Line 312:
      
      
}(window.countdownTimer = window.countdownTimer || {}, mediaWiki, jQuery));
}(window.countdownTimer = window.countdownTimer || {}, mediaWiki, jQuery));
// **************************************************
//  - end -  JavaScript countdown timer
// **************************************************

Revision as of 05:31, 25 March 2017

/* Any JavaScript here will be loaded for all users on every page load. */

/* 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|description=\n|purpose=\n|game=\n|source=\n}}';
	}

	$(loadAutoAboutfileTemplate);
}

/* Shrinking talk bubble sprites */
$(document).ready(function () {
	if (document.readyState != "complete") {
		setTimeout(arguments.callee, 100);
		return;
	}
	$("table.talkbubble").each(function () {
		$(this).find("td").first().width(90).css("text-align", "center").find("img").each(function () {
			if ($(this).width() > 90) $(this).css("height", "auto").width(90);
		});
	});
});

// ===========
// Code for alternating wiki logo
// Author: Porplemontage
// =============
/*
var logos = ['/images/b/bc/Wiki.png', '/images/9/97/Wiki_3.png', '/images/d/d7/Wiki_2.png'];
$('#p-logo a').css('background-image', 'url(' + logos[Math.floor(Math.random() * logos.length)] + ')');
*/

// ==================
//  Code for Template:Suite3
//  Author: Soxra
// ==================

$(document).ready(function () {
	$(".morphMaster").each(function () {
		var $master = $(this);
		var $tabs = $master.find(".morphTabBox");
		var $container = $master.find(".morphTabContainer");

		$tabs.find(".morphLink").click(function () {
			var id = $(this).attr("id");
			id = id.substr(0, id.length - 4);
			$container.find(".morphContent").hide();
			$container.find("#" + id + "Content").show();
		});
	});
});

// ==================
//  tabber.js
//  Authors: Eric Fortin, Alexia E. Smith
// ==================

(function($) {
	$.fn.tabber = function() {
		return this.each(function() {
			// create tabs
			var $this = $(this),
			    tabContent = $this.children('.tabbertab'),
			    nav = $('<ul>').addClass('tabbernav');
			tabContent.each(function() {
				var anchor = $('<a>').text(this.title).attr('title', this.title).attr('href', 'javascript:void(0);');
				$('<li>').append(anchor).appendTo(nav);
			});
			$this.prepend(nav);

			/**
			 * Internal helper function for showing content
			 * @param  string title to show, matching only 1 tab
			 * @return true if matching tab could be shown
			 */
			function showContent(title) {
				var content = tabContent.filter('[title="' + title + '"]');
				if (content.length !== 1) return false;
				tabContent.hide();
				content.show();
				nav.find('.tabberactive').removeClass('tabberactive');
				nav.find('a[title="' + title + '"]').parent().addClass('tabberactive');
				return true;
			}
			// setup initial state
			var loc = location.hash.replace('#', '');
			if ( loc == '' || !showContent(loc) ) {
				showContent(tabContent.first().attr('title'));
			}

			// Repond to clicks on the nav tabs
			nav.on('click', 'a', function(e) {
				var title = $(this).attr('title');
				e.preventDefault();
				location.hash = '#' + title;
				showContent( title );
			});

			$this.addClass('tabberlive');
		});
	};
})(jQuery);

$(document).ready(function() {
	$('.tabber').tabber();
});

// ==================
// Auto-refresh recent changes
// Code courtesy of pcj of WoWWiki.
// ==================

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; margin-left:10px;"><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 style="position:relative; top:5px; left:5px;" id="autoRefreshProgress"><img src="/images/loader.gif" border="0" alt="AJAX operation in progress" /></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();
	}
});

// ==================
// Countdown, rewrite by Pecoes
// Original script by Splarka + Eladkse
// ==================

;(function (module, mw, $) {
    
    'use strict';
    
    var translations = $.extend(true, {
        en: {
            and: 'and',
            second: 'second',
            seconds: 'seconds',
            minute: 'minute',
            minutes: 'minutes',
            hour: 'hour',
            hours: 'hours',
            day: 'day',
            days: 'days'
        }
    }, module.translations || {}),
    i18n = translations[
        mw.config.get('wgContentLanguage')
    ] || translations.en;

    var countdowns = [];
    
    var NO_LEADING_ZEROS = 1;
    
    function output (i, diff) {
        /*jshint bitwise:false*/
        var delta, result, parts = [];
        delta = diff % 60;
        parts.unshift(delta + ' ' + i18n[delta === 1 ? 'second' : 'seconds']);
        diff = Math.floor(diff / 60);
        delta = diff % 60;
        parts.unshift(delta + ' ' + i18n[delta === 1 ? 'minute' : 'minutes']);
        diff = Math.floor(diff / 60);
        delta = diff % 24;
        parts.unshift(delta + ' ' + i18n[delta === 1 ? 'hour'   : 'hours'  ]);
        diff = Math.floor(diff / 24);
        parts.unshift(diff  + ' ' + i18n[diff  === 1 ? 'day'    : 'days'   ]);
        result = parts.pop();
        if (countdowns[i].opts & NO_LEADING_ZEROS) {
            while (parts.length && parts[0][0] === '0') {
                parts.shift();
            }
        }
        if (parts.length) {
            result = parts.join(', ') + ' ' + i18n.and + ' ' + result;
        }
        countdowns[i].node.text(result);
    }
    
    function end(i) {
        var c = countdowns[i].node.parent();
        switch (c.attr('data-end')) {
            case 'remove':
                c.remove();
                countdowns.splice(i, 1);
                return;
            case 'stop':
                output(i, 0);
                countdowns.splice(i, 1);
                return;
            case 'toggle':
                var toggle = c.attr('data-toggle');
                if (toggle && $(toggle).length) {
                    $(toggle).css('display', 'inline');
                    c.css('display', 'none');
                    countdowns.splice(i, 1);
                    return;
                }
                break;
            case 'callback':
                var callback = c.attr('data-callback');
                if (callback && $.isFunction(module[callback])) {
                    output(i, 0);
                    countdowns.splice(i, 1);
                    module[callback].call(c);
                    return;
                }
                break;
        }
        countdowns[i].countup = true;
        output(i, 0);
    }
    
    function update () {
        var now = Date.now();
        $.each(countdowns.slice(0), function (i, countdown) {
            var diff = Math.floor((countdown.date - now) / 1000);
            if (diff <= 0 && !countdown.countup) {
                end(i);
            } else {
                output(i, Math.abs(diff));
            }
        });
        if (countdowns.length) {
            window.setTimeout(function () {
                update();
            }, 1000);
        }
    }
    
    function getOptions (node) {
        /*jshint bitwise:false*/
        var text = node.parent().attr('data-options'),
            opts = 0;
        if (text) {
            if (/no-leading-zeros/.test(text)) {
                opts |= NO_LEADING_ZEROS;
            }
        }
        return opts;
    }
    
    $(function () {
        var countdown = $('.countdown');
        if (!countdown.length) return;
        $('.nocountdown').css('display', 'none');
        countdown
        .css('display', 'inline')
        .find('.countdowndate')
        .each(function () {
            var $this = $(this),
                date = (new Date($this.text())).valueOf();
            if (isNaN(date)) {
                $this.text('BAD DATE');
                return;
            }
            countdowns.push({
                node: $this,
                opts: getOptions($this),
                date: date,
            });
        });
        if (countdowns.length) {
            update();
        }
    });
    
}(window.countdownTimer = window.countdownTimer || {}, mediaWiki, jQuery));