Jump to content

User:Sreejithk2000/GalleryUsage.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
var badge = function(text, inline, displayZero) {
		var $badge = $(this).find('.mw-badge'),
			badgeStyleClass = 'mw-badge-' + (inline ? 'inline' : 'overlay'),
			isImportant = true;
		if (text === 0 && displayZero) {
			isImportant = false;
			text = '0';
		}
		if (text) {
			if ($badge.length) {
				$badge.toggleClass('mw-badge-important', isImportant).find('.mw-badge-content').text(text);
			} else {
				$badge = $('<div class="mw-badge"></div>').addClass(badgeStyleClass).toggleClass('mw-badge-important', isImportant).append($('<span class="mw-badge-content"></span>').text(text)).appendTo(this);
			}
		} else {
			$badge.remove();
		}
		return this;
	};
var setUsage = function setUsage(elm, src) {
		"use strict";
		var $gu = $('<div>', {
			'class': 'guGU',
			title: "GlobalUsage",
			badge: badge
		});
		$gu.badge = badge;

		var query = {
			action: 'query',
			list: 'imageusage',
			iutitle: src,
			format: 'json'
		};


		$.getJSON(mw.util.wikiScript('api'), query, function(result) {
			var usage = result.query.imageusage;
			var usageCount = 0;

			for (var i = 0; i < usage.length; i++) {
				if (usage[i].ns === 0) {
					usageCount++;
				}
			}
			$(elm).append($gu.badge('Usage: ' + usageCount));
		});
	};

// According to Krinkle, gadgets do not have to wait for $(document).ready()
$('.gallery > li.gallerybox').each(function(i, el) {
	var $el = $(el),
		$th = $el.find('div.thumb').addClass('guThumb'),
		$img = $th.find('img:first'),
		$vid = $th.find('video:first'),
		src,
		t;

	src = $el.find('.gallerytext a');
    t = decodeURIComponent(src.text());
	if (!t) return;
	setUsage($th, mw.config.get('wgFormattedNamespaces')[6] + ':' + t);

	return $th.find('img:first');
});