MediaWiki:Common.js

Z Nonsensopedii, polskiej encyklopedii humoru
Wersja z dnia 20:10, 22 gru 2016 autorstwa Zen.Xen.ni (dyskusja • edycje) (Uwaga! Może się coś rozpaprać!)

Uwaga: aby zobaczyć zmiany po zapisaniu, może zajść potrzeba wyczyszczenia pamięci podręcznej przeglądarki.

  • Firefox / Safari: Przytrzymaj Shift podczas klikania Odśwież bieżącą stronę, lub naciśnij klawisze Ctrl+F5 lub Ctrl+R (⌘-R na komputerze Mac)
  • Google Chrome: Naciśnij Ctrl-Shift-R (⌘-Shift-R na komputerze Mac)
  • Internet Explorer: Przytrzymaj Ctrl jednocześnie klikając Odśwież lub naciśnij klawisze Ctrl+F5
  • Konqueror: Kliknij polecenie Odśwież lub naciśnij klawisz F5
  • Opera: Wyczyść pamięć podręczną w Narzędzia → Preferencje
/* <pre><nowiki> */
/** COMMON.JS **
 * Plik zawiera funkcje używane w innych skryptach. Edytuj ostrożnie!
 *
 ** - SŁOWNIK UŁATWIAJĄCY PISANIE SKRYPTU **/
importScriptURI("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js");

/** - PODSTAWOWE FUNKCJE **/
function inGroup(a) {
    var b = 0;
    for (i in wgUserGroups) wgUserGroups[i] == a && (b = 1);
    return b
}

function returnObjById(a) {
    var b = null;
    document.getElementById ? b = document.getElementById(a) : document.all ? b = document.all[a] : document.layers && (b = document.layers[a]);
    return b
}
var hasClass = function() {
    var a = {};
    return function(b, c) {
        return (a[c] ? a[c] : a[c] = RegExp("(?:\\s|^)" + c + "(?:\\s|$)")).test(b.className)
    }
}();

function war(l, j, k, w) {
    return (l == 1) ? j : (l % 100 >= 10 && l % 100 <= 20) ? w : (([2, 3, 4]).indexOf(l % 10) != -1) ? k : w;
}

function gnd(g, m, z, n) {
    var X = {
        "male": m,
        "female": z,
        "unknown": n
    };
    return (g) ? X[g] : n;
}

function dTemu(l) {
    var N = Math.floor(l / 1000),
        D = Math.floor(N / 86400),
        H = Math.floor((N - D * 86400) / 3600),
        I = Math.floor((N - D * 86400 - H * 3600) / 60);
    return {
        d: D,
        h: H,
        i: I,
        text: (D ? D + " d" + war(D, "zień", "ni", "ni") + " " : "") + (H ? H + " godz. " : "") + (I ? I + " min" + (!H ? "ut" + war(I, "ę", "y", "") : "") + " temu" : "przed chwilą")
    };
}

/* Archiwizacja Porum */
function zipForum() {
    if (!("Forum" != wgCanonicalNamespace || "view" != wgAction || "Strona główna" == wgTitle))
        if (!document.getElementById("naglowekforum") || document.getElementById("nieodkopuj")) $("#ca-edit a")[0].style.color = "DarkKhaki", $("#ca-edit a")[0].href = "", $("#ca-edit a")[0].title = "Ten wątek jest archiwalny, prosimy o nieedytowanie go."
}
/* Wyświetlenie nazwy użytkownika ([[Szablon:USERNAME]]) */
function UserNameReplace() {
    if (!("undefined" != typeof disableUsernameReplace && disableUsernameReplace || null == wgUserName)) {
        var a = YAHOO.util.Dom.getElementsByClassName("insertusername", "span", document.getElementById("bodyContent")),
            b;
        for (b in a) a[b].innerHTML = wgUserName
    }
}
/* Import CSS i Wyświetlany przycisk do usuwania */
function EKNuke() {
    1 == inGroup("sysop") && $(".nuke").css("display", "inline")
    1 == inGroup("content-moderator") && $(".nuke").css("display", "inline")
}

function Zab() {
    var KL = {
            e: wgRestrictionEdit.length ? (wgRestrictionEdit[0] == "autoconfirmed" ? 1 : 2) : 0,
            m: wgRestrictionMove.length ? (wgRestrictionMove[0] == "autoconfirmed" ? 1 : 2) : 0
        },
        WK = [false, "półzabezpieczona przed edycją", "zabezpieczona przed edycją", "półzabezpieczona przed przeniesieniem", "półzabezpieczona", "zabezpieczona przed edycją, półzabezpieczona przed przeniesieniem", "zabezpieczona przed przeniesieniem", "półzabezpieczona przed edycją, zabezpieczona przed przeniesieniem", "zabezpieczona"],
        ML = parseInt(String(KL.m) + String(KL.e), 3);
    WK[ML] && $("<span class='restr'>Strona " + WK[ML] + ".</span>").css({
        float: "right",
        marginTop: "2px"
    }).appendTo("#contentSub");
}
YAHOO.util.Event.onContentReady('column-one', zipForum);
addOnloadHook(UserNameReplace);
$(document).ready(EKNuke);
(typeof wgRestrictionEdit != "undefined" || typeof wgRestrictionMove != "undefined") && $("#contentSub").ready(Zab);
$(function() {
    $('input#searchInput').attr({
        'placeholder': 'Szukaj'
    });
});
$(function() {
    $(".yt-iframe").each(function() {
        this.innerHTML = "<iframe src=\"//www.youtube-nocookie.com/embed/" + this.id + "?rel=0&autohide=1&modestbranding=1\" frameborder=\"0\" allowfullscreen></iframe>";
    });
});

/*** IMPORTY SKRYPTÓW ***/
importArticles({
    type: "script",
    articles: [
        "MediaWiki:Dynamiczne_adresy_IP.js",
        "MediaWiki:Glosowanie.js",
        "MediaWiki:Enhanced-upload.js"
    ]
});

/*** Skrypty dotyczące Gry ***/
/* Zmiana tytułu "Gra:Gra" na samo "Gra" */
$("#firstHeading").ready(function() {
    if ($("#firstHeading").html() == "Gra:Gra") {
        $("#firstHeading").html("Gra");
    }
});

/* BEGIN Dynamic Navigation Bars (experimantal)
 * pochodzi z http://en.wikipedia.org/wiki/MediaWiki:Monobook.js
 * autorzy: http://en.wikipedia.org/w/index.php?title=MediaWiki:Monobook.js&action=history
 * licencja: GFDL
 */
// set up the words in your language
var NavigationBarHide = '[ Ukryj ]';
var NavigationBarShow = '[ Pokaż ]';

// 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 = 1;

// 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 (NavChild.className == 'NavPic') {
                NavChild.style.display = 'none';
            }
            if (NavChild.className == '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 (NavChild.className == 'NavPic') {
                NavChild.style.display = 'block';
            }
            if (NavChild.className == '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
    for (var i = 0; NavFrame = document.getElementsByTagName("div")[i]; i++) {
        // if found a navigation bar
        if (NavFrame.className == "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 (NavFrame.childNodes[j].className == "NavHead") {
                    NavFrame.childNodes[j].appendChild(NavToggle);
                }
            }
            NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
        }
    }
    // if more Navigation Bars found than Default: hide all
    if (NavigationBarShowDefault < indexNavigationBar && !wgTitle.match(/Najbardziej poszablonowana/)) {
        for (var i = 1; i <= indexNavigationBar; i++) {
            toggleNavigationBar(i);
        }
    }

}

YAHOO.util.Event.onContentReady('bodyContent', createNavigationBarToggleButton);

/** Collapsible tables **
 *  Description: Allows tables to be collapsed, showing only the header. See
 *  [[en:Wikipedia:NavFrame]].
 *  Maintainers: [[User:R. Koot]]
 */

var autoCollapse = 2;
var collapseCaption = "Ukryj";
var expandCaption = "Pokaż";

function collapseTable(tableIndex) {
    var Button = document.getElementById("collapseButton" + tableIndex);
    var Table = document.getElementById("collapsibleTable" + tableIndex);

    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;
    } 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")) {

            /* 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];
            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.style.color = Header.style.color;
            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("]"));

            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);
        } else if (hasClass(NavigationBoxes[i], "innercollapse")) {
            var element = NavigationBoxes[i];
            while (element = element.parentNode) {
                if (hasClass(element, "outercollapse")) {
                    collapseTable(i);
                    break;
                }
            }
        }
    }
}
jQuery(document).ready(createCollapseButtons);

/* Zmiana tytułu strony, autor: [[user:Vae]], Public Domain   */
/* Użycie: {{nibytytul|Przykladowy tytul}}                    */
/*         {{nibytytul|Przykladowy tytul|sub=Podtytul}}       */

function uChangeTitle() {
    var staryTytul = null;
    staryTytul = returnObjById("firstHeading"); /* monobook */
    if (!staryTytul) {
        var h1 = document.body.getElementsByTagName("h1");
        staryTytul = h1[0];
    }
    var nowyTytul = null;
    nowyTytul = returnObjById("uTytulStrony");
    if (nowyTytul && staryTytul) {
        // sprawdzamy, czy zawiera cudzyslowy (np. strona edycji)
        // jesli tak, podmieniamy tylko zawartosc cudzyslowow
        if (staryTytul.innerHTML.match(/^.*?„.*?”.*?$/))
            staryTytul.innerHTML = staryTytul.innerHTML.replace(/^(.*?)„.*?”(.*?)$/, "$1" + "„" + nowyTytul.innerHTML + "”" + "$2");
        else if (staryTytul.innerHTML.match(/<span>/i))
            staryTytul.innerHTML = staryTytul.innerHTML.replace(/^(.*?)<span>/, returnObjById("uTytulStrony").innerHTML + "<span>");
        else
            staryTytul.innerHTML = returnObjById("uTytulStrony").innerHTML;
        staryTytul.style.backgroundColor = nowyTytul.style.backgroundColor;
        staryTytul.style.color = nowyTytul.style.color;
        // sprawdzamy, czy podtytul tez jest do zamiany
        var ssub = returnObjById("uPodtytulStrony");
        var sub = returnObjById("siteSub");
        if (ssub && ssub.innerHTML && sub) {
            sub.innerHTML = ssub.innerHTML;
        }
    }

    if (returnObjById("uLogoStrony")) {
        var a = (skin == "monobook") ? returnObjById("p-logo").getElementsByTagName('a')[0] : returnObjById("wiki_logo");
        a.style.backgroundImage = "url(" + returnObjById("uLogoStrony").getElementsByTagName('img')[0].src + ")";
    }
    return;
}
addOnloadHook(uChangeTitle);

/* komentarz w formularzu rejestracji */
YAHOO.util.Event.onContentReady('userlogin2', function() {
    $('#wpNameTD')[0].innerHTML += '<p style="font-size:9pt;">Nazwa użytkownika <b>może</b> zawierać spacje oraz polskie znaki.</p>';
    $('#wpEmailTD')[0].innerHTML += '<p style="font-size:9pt;">Podanie adresu e-mail nie jest obowiązkowe. Będzie on jednak porzebny, jeśli zapomnisz hasła.</p>';
});

/* Skrypt dla Szablon:Galeria */
function toggleImage(group, remindex, shwindex) {
    jQuery("#ImageGroupsGr" + group + "Im" + remindex).hide();
    jQuery("#ImageGroupsGr" + group + "Im" + shwindex).show();
}

function ImageGroup() {
    jQuery('div.ImageGroup').each(function(i, group) {
        var unitnode = jQuery('div.ImageGroupUnits', group).get(0);
        if (unitnode == undefined) {
            return 1;
        }
        var units = jQuery(unitnode).children('.center');
        var count = units.get().length;
        if (count <= 1) {
            return 1;
        }
        units.each(function(j, currentimage) {
            jQuery(currentimage).attr('id', "ImageGroupsGr" + i + "Im" + j);
            var leftlink = jQuery('<a href="#"/>');
            if (j != 0) {
                leftlink.text('◀').click(function() {
                    toggleImage(i, j, j - 1);
                    return false;
                });
            }
            var rightlink = jQuery('<a href="#"/>');
            if (j != count - 1) {
                rightlink.text('▶').click(function() {
                    toggleImage(i, j, j + 1);
                    return false;
                });
            }
            jQuery('<div/>').css({
                    'font-size': '110%',
                    'font-weight': 'bold'
                })
                .append(leftlink)
                .append('<samp>(' + (j + 1) + '/' + count + ')</samp>')
                .append(rightlink)
                .prependTo(jQuery(currentimage));
            if (j != 0) {
                jQuery(currentimage).hide().addClass('noprint');
            }
        });
    });
}
$(ImageGroup);

/* </nowiki></pre> */

// KOD NA ŚNIEG – autor: Szewek
(function() {
	'use strict';
	var NUM_FLAKES = 40;
	var status = true, handle, STBN, flakes, Flake, PI_2, canvas, context, drawCircle, i, range, resizeWindow, xpos;
	SBTN = $('<button id="snieg-switch">Przełącz śnieg</button>').appendTo("div#content");
	SBTN.click(function(){
		status = !status;
		if (status) 
			handle = requestAnimationFrame(step);
		else {
			cancelAnimationFrame(handle);
			context.clearRect(0, 0, w, h);
		}
	});	
	PI_2 = 2 * Math.PI;
	canvas = $('<canvas style="z-index: 500; pointer-events: none; position: fixed; top: 0; left: 0;" id="snieg"></canvas>').appendTo("body")[0];
	context = canvas.getContext("2d");
	window.w = 0;
	window.h = 0;
	resizeWindow = function() {
		window.w = canvas.width = window.innerWidth;
		return (window.h = canvas.height = window.innerHeight);
	};
	window.addEventListener('resize', resizeWindow, false);
	$(function() {return setTimeout(resizeWindow, 0);});
	range = function(a, b) {return (b - a) * Math.random() + a;};
	drawCircle = function(x, y, r) {
		context.beginPath();
		context.arc(x, y, r, 0, PI_2, false);
		context.fill();
		context.stroke();
	};
	xpos = 0.5;
	document.onmousemove = function(e) {return (xpos = e.pageX / w);};
	window.requestAnimationFrame = (function() {
		return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
			return window.setTimeout(callback, 1000 / 60);
		};
	})();
	Flake = (function() {
		function Flake() {
			this.r = ~~range(4, 8);
			this.r2 = 2 * this.r;
			this.replace();
		}
		Flake.prototype.replace = function() {
			this.x = range(-this.r2, w - this.r2);
			this.y = range(-20, h - this.r2);
			this.xmax = w - this.r;
			this.ymax = h - this.r;
			this.vx = range(0, 2) + 8 * xpos - 5;
			this.vy = 0.5 * this.r + range(-0.5, 0.5);
		};
		Flake.prototype.draw = function() {
			var f;
			this.x += this.vx;
			this.y += this.vy;
			if (this.y > this.ymax) {
				this.replace();
			}
			if (!((0 < (f = this.x) && f < this.xmax))) {
				this.x = (this.x + this.xmax) % this.xmax;
			}
			drawCircle(~~this.x, ~~this.y, this.r);
		};
		return Flake;
	})();
	flakes = (function() {
		var i, a = [];
		for (i = 0; i < NUM_FLAKES; i++)
			a.push(new Flake());
		return a;
	})();
	window.step = function() {
		var i, len;
		context.clearRect(0, 0, w, h);
		context.fillStyle = "rgba(255,255,255,1)";
		context.lineWidth = 2;
		context.strokeStyle = "rgba(0,0,0,0.25)";
		for (i = 0, len = flakes.length; i < len; i++)
			flakes[i].draw();
		handle = requestAnimationFrame(step);
	};
	handle = requestAnimationFrame(step);
	console.log("Załadowano śnieg");
})();