/*

disFixer v. 2.1.2
by Matma Rex, zmiany by ToSter
cc-by-sa 3.0

Użycie: wybierz disFixer w preferencjach 
lub dodaj do swojego common.js linię
importScript('MediaWiki:Gadget-disFixer.js')

Szerszy opis: ].

*/
disStr = //strings - translate this!
{
	and:			' i ', //used in summary
	autosummaryBegin:       'poprawa linków do',
	dabsShort:		'ujedn.',
	redirsShort:		'przek.',

	categoryDabPages:       'Kategoria:Strony ujednoznaczniające',
	wikipediaDabPage:       'Wikipedia:Strona ujednoznaczniająca',

	fixLinks:		'Popraw linki do ujednoznacznień i przekierowań', //main button
	fixLinksDisam:		'Popraw linki do ujednoznacznień',
	fixLinksRedir:		'Popraw linki do przekierowań',
	wait:			'Czekaj...', //main button after click

	noRedirLinks:		'Brak linków do przekierowań.',
	fixingInProgress:       'Rozwiązywanie przekierowań: trwa...',

	fixRedirsOnly:		'Popraw przekierowania (Wykonaj także inne zmiany! Sama poprawa przekierowań nie ma sensu!)', //fix button if no dabs
	fixButton:		'Popraw', //fix button

	fixDabs:		'Popraw ujednoznacznienia:', //before list of dabs
	viewDabPage:		'Zobacz stronę ujedn.', //title
	scrollToLink:		'Przewiń do pozycji linku w tekście', //title
	delink:			'odlinkuj', //last element in every list

	fixRedirsCheckbox:      'popraw przekierowania',

	otherTarget:		'inny cel...',
	setNewLinkTarget:       'Dokąd ma prowadzić link?'
};

//domyślne ustawienia
if (typeof disFixIfRedirsOnly == 'undefined') disFixIfRedirsOnly = false;
if (typeof disMarkAsMinor == 'undefined') disMarkAsMinor = false;
if (typeof disCodeCleanup == 'undefined') disCodeCleanup = false;
if (typeof useOldRedirFixing == 'undefined') useOldRedirFixing = false;
if (typeof disEnforceCookies == 'undefined') disEnforceCookies = false;


if(disCodeCleanup && typeof wp_sk == 'undefined')
{
	importScript('Wikipedysta:Nux/wp sk.js');
}

function disCallApi(query) // z ]
{
	var url = mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?';
	query = 'json';
	url += $.param(query);
	mw.loader.load(url);
}

function disScrollToLink(target)
{
	if (typeof disHighlightedLinkTimeout != 'undefined' && typeof disHighlightedLink != 'undefined') {
		clearTimeout(disHighlightedLinkTimeout);
		disHighlightedLink.css('background', '');
	}
	window.disHighlightedLink = $(dis).filter('').first();
	disHighlightedLink.css('background', 'red');

	window.disHighlightedLinkTimeout = setTimeout(function() {
		disHighlightedLink.css('background', '');
	}, 3000);
	disHighlightedLink.get(0).scrollIntoView();
}

function disLoadFixer()
{
	window.dis = $('a.mw-disambig').get();
	window.disRedirs = $('a.mw-redirect').get();

	//nie ma disambigów, na pewno - nic do roboty
	if (dis.length  ==  0) {
		if (!disFixIfRedirsOnly || disRedirs.length  ==  0) {
			return //możliwość wymuszenia sprawdzania mimo braku disambigów, ale tylko, gdy są rediry
		}
	}

	var txt = disStr.fixLinks;
	if (dis.length == 0) {
		txt = disStr.fixLinksRedir;
	}
	else if (disRedirs.length == 0) {
		txt = disStr.fixLinksDisam;
	}
	var el = '<input id="disBeginButton" type="submit" class="disFixerButton" value="' + txt + '" />';

	$('h1:first').before(el);
	$('#disBeginButton').click(function() {
		try {
			$('#disBeginButton').val(disStr.wait);
		} catch(er){}
	});
	$('#disBeginButton').click(disBegin);
}

function disBegin()
{
	var el = '<div id="disRedirsStatus"></div>';
	$('h1:first').before(el);

	$('#disRedirsStatus').append('<input type="checkbox" id="disFixRedirsCheckbox" style="display:none" />');
	if (window.disRedirs.length == 0) {
		$('#disRedirsStatus').append(disStr.noRedirLinks);
	}
	else {
		$('#disRedirsStatus').append(disStr.fixingInProgress);
	}

	var titles = ;
	for (var i = 0; i < dis.length; i++) {
		titles.push(dis.title);
	}

	disCallApi({
		action:'query',
		prop:'links',
		titles:titles.join('|'),
		plnamespace:0,
		pllimit:500,
		callback:'disCallback'
	});

	if (window.disRedirs.length > 0) {
		var titles2 = ;
		for (var i = 0; i < disRedirs.length; i++) {
			titles2.push(disRedirs.title);
		}

		if (useOldRedirFixing) {
			disCallApi({
				action:'query',
				redirects:'',
				titles:titles2.join('|'),
				callback:'disRedirCallback'
			});
		}
		else {
			disCallApi({
				action:'query',
				prop:'revisions',
				rvprop:'content',
				titles:titles2.join('|'),
				callback:'disRedirCallback2'
			});
		}
	}
}

function disCallback(res)
{
	if (typeof res.query == 'undefined' && disFixIfRedirsOnly) {
		var el = '<div id="disContainer"><input type="submit" class="disFixerButton" value="' + disStr.fixRedirsOnly
			+ '" style="font-weight:bold;color:red" /></div>';

		$('#disBeginButton').replaceWith(el);
		$('#disContainer input').click(disSend);
	}
	else {
		var addScrollToLink = $('#content').get(0).scrollIntoView;
		var pages = res.query.pages;

		var str = disStr.fixDabs + '<br />';
		for (var i in pages) {
			if (isNaN(+i)) continue; //prototypes, damn
			var page = pages;

			str +=
				'<label>' + page.title + ' '
				+ '<a href="/w/index.php?title=' +encodeURIComponent(page.title) + '" title="' + disStr.viewDabPage
				+ '" target="_new">&#8663;</a>'
				+ (addScrollToLink ? '<a href="javascript:disScrollToLink(' + '\'' + page.title
					+ '\'' + ')" title="' + disStr.scrollToLink + '">&#8659;</a>'
					: '')
				+ ': <select id="input-dislink' + page.title + '">';
			str += '<option>' + page.title + '</option>';

			if (typeof page.links == 'undefined') {
				page.links = ;
			}
			for (var i = 0; i < page.links.length; i++) {
				str += '<option>' + page.links.title + '</option>';
			}

			str += '<option style="color:grey"></option>';
			str += '</select> <input type="submit" class="disFixerButton" onclick="disSetLinkTarget(this,'
				+ '\'' + page.title + '\'' + ')" value="' + disStr.otherTarget + '" /></label><br />';
		}

		var el = '<div id="disContainer">' + str
			+ '<input type="submit" class="disFixerButton" value="' + disStr.fixButton + '" /></div>';
		$('#disBeginButton').replaceWith(el);
		$('#disContainer input:last').click(disSend);
	}
}

function disRedirCallback(res)
{
	window.disResolvedRedirs = res.query.redirects;

	var el = '<input type="checkbox" id="disFixRedirsCheckbox" checked="checked" /> '
		+ '<label for="disFixRedirsCheckbox">' + disStr.fixRedirsCheckbox
		+ ' (' + disResolvedRedirs.length + ')</label>';
	$('#disRedirsStatus').html(el);
	$('#disRedirsStatus').css('color', 'green');
}

function disRedirCallback2(res)
{
	var pages = res.query.pages;
	window.disResolvedRedirs = ;

	for (var i in pages) {
		if (isNaN(i)) continue;

		var f = pages.title;
		var t = pages.revisions.replace(/^#(?:REDIRECT|TAM|PATRZ|PRZEKIERUJ)\s*\]+)\]\]*$/i, '$1');

		if (t.match(/|{}\r\n]/)) {
			//coś się pomieszało - tych znaków nie powinno być w tytule strony
			continue;
		}

		window.disResolvedRedirs.push({from:f, to:t});
	}

	var el = '<input type="checkbox" id="disFixRedirsCheckbox" checked="checked" /> '
		+ '<label for="disFixRedirsCheckbox">' + disStr.fixRedirsCheckbox
		+ ' (' + disResolvedRedirs.length + ')</label>';
	$('#disRedirsStatus').html(el);
	$('#disRedirsStatus').css('color', 'green');
}

function disSend()
{
	var inputs = $('#disContainer select');
	var toFix = ;
	for (var i = 0; i < inputs.length; i++) {
		var from = inputs.options.value;
		var to = inputs.value;
		if (from == to) continue;
		toFix.push(from + '~' + to);
	}
	createCookie('disFixDis' + mw.config.get('wgPageName'), toFix.join('|'), 0);

	if (typeof disResolvedRedirs != 'undefined' && $('#disFixRedirsCheckbox').attr('checked')) {
		var toFix = ;
		for (var i = 0; i < disResolvedRedirs.length; i++) {
			var from = disResolvedRedirs.from;
			var to = disResolvedRedirs.to;
			toFix.push(from + '~' + to);
		}
		createCookie('disFixRedirs' + mw.config.get('wgPageName'), toFix.join('|'), 0);
	}
	window.location = $('#ca-edit a:first').attr('href');
}

function disOnloadEdit()
{
	var whatIsFixed = ;
	var str = $('#wpTextbox1').val();

	str = str.replace(/\r\n/g,'\n').replace(/\s*$/, '');

	if (disCodeCleanup && typeof wp_sk != 'undefined') {
		str = wp_sk.cleaner(str);
	}
	else {
		str = disCleanLinks(str);
	}

	var linksDisam = readCookie('disFixDis' + mw.config.get('wgPageName'));
	var linksRedir = readCookie('disFixRedirs' + mw.config.get('wgPageName'));

	var links = new Array();
	if (linksDisam != null && linksDisam != 'undefined' && linksDisam != '') {
		links = linksDisam.split('|');
		whatIsFixed.push(disStr.dabsShort);
	}
	if (linksRedir != null && linksRedir != 'undefined' && linksRedir != '') {
		links = $.merge(links, linksRedir.split('|'));
		whatIsFixed.push(disStr.redirsShort);
	}

	if (links.length > 0) {
		for (var i = 0; i < links.length; i++) {
			var l = links.split('~');
			var from = l.replace(/(\{\}\\])/g, '\\$1') //regex escape
			var to = l;

			if (to == '') {
				str = str.replace(new RegExp('\\\\|]+|)\\]\\]', 'gi'), '$1');
				str = str.replace(new RegExp('\\\\|]+|)\\|(]+)\\]\\]', 'gi'), '$1');
				continue;
			}
			var sh = to.indexOf('#') != -1;
			str = str.replace(new RegExp('\\\\|]+|)\\]\\]', 'gi'), ']');
			str = str.replace(new RegExp('\\\\|]+|)\\|(]+)\\]\\]', 'gi'), ']');
		}
	}
	str = disCleanLinks(str);

	eraseCookie('disFixDis' + mw.config.get('wgPageName'));
	eraseCookie('disFixRedirs' + mw.config.get('wgPageName'));

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

	$('#wpTextbox1').val(str);
	var newval = $('#wpSummary').val() + '[[WP:Narzędzia/disFixer|' + disStr.autosummaryBegin
		+ ' ' + whatIsFixed.join(disStr.and) + ']]' + (disCodeCleanup ? ', ]' : '');
	$('#wpSummary').val(newval);
	if (disMarkAsMinor) {
		$('#wpMinoredit').prop('checked', true);
	}
	$('#wpDiff').click();
}

function disSetLinkTarget(el, disName) //helper - for buttons
{
	el = $(el); // to jquery object
	var target = prompt(disStr.setNewLinkTarget, disName);
	if (typeof target == 'undefined' || target == '') {
		return;
	}

	var opt = '<option value="' + target + '">' + target + '</option>';
	var sel = el.parent().find('select:first');
	sel.append(opt);
	sel.find('option:last').prop('selected', true);
}

// based on Nux's code cleanup
// http://pl.wikipedia.orghttps://wikines.com/pl/Wikipedysta:Nux/wp_sk.js
function disCleanLinks(str)
{
	//najprostszy cleanup, głównie po to, żeby regeksy do poprawy linków mogły być prostsze

	// ]›]
	str = str.replace(/\]*)(]*)(\||\]\])/g, function(a, name, anchor, end)
	{
		try {
			var name = decodeURIComponent(name);
			var anchor = decodeURIComponent(anchor.replace(/\.({2})\.({2})/g, '%$1%$2'));
			a = '[[' + name + anchor + end;
		} catch(err){} // błąd na linkach typu ]

		return a.replace(/_/g, ' ');
	});

	// ] > ]
	str = str.replace(/\])(]*)\|(])\2\]\]/g, function (a, w1_1, w_rest, w2_1)
	{
		return (w1_1.toUpperCase() == w2_1.toUpperCase()) ? ']' : a;
	});

	// (ro)zwijanie wikilinków
	str = str.replace(/\]*)\|\1(*)\]\]/g, ']$2');
	str = str.replace(/\]+)\|(]+)\]\](+)/g, ']');

	// usuwanie spacji w wikilinkach
	str = str.replace(/\\|:]*\| ]) *\|/g, '[[$1|');
	str = str.replace(/()\[\[ +/g, '$1 [[');
	str = str.replace(/\[\[ +/g, '[[');
	str = str.replace(/()\\|:]+)\| +/g, '$1 [[$2|');
	str = str.replace(/\\|:]+)\| +/g, '[[$1|');
	str = str.replace(/() +\]\]()/g, '$1]] $2');
	str = str.replace(/() +\]\]()/g, '$1]]$2');

	return str;
}


// http://www.quirksmode.org/js/cookies.html
// modified to use globalStorage in Firefox
function createCookie(name, value, days)
{
	try {
		if (disEnforceCookies) throw('cookies enforced');

		if (days < 0) globalStorage.removeItem(name);
		else globalStorage = value;
	}
	catch(er) {
		//regular cookies
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
	}
}

function readCookie(name)
{
	try {
		if (disEnforceCookies) throw('cookies enforced');

		return (globalStorage) + '' //weird Firefox fix
	}
	catch(er) {
		var nameEQ = escape(name) + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca;
			while (c == ' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ)  ==  0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	}
}

function eraseCookie(name)
{
	createCookie(name, "", -1);
}



// borrowed from Beau's disambig marking tool
// http://pl.wikipedia.orghttps://wikines.com/pl/MediaWiki:Gadget-mark-disambigs.js
var dg$pageLoaded = false;
var dg$dataLoaded = false;
var dg$disambig = {};
var dg$uniqueLinks = 0;
var dg$links = 0;

function dg$request(clcontinue)
{
	var query = {
		action: 'query',
		titles: mw.config.get('wgPageName'),
		prop:   'categories',
		cllimit:	'max',
		gpllimit:       'max',
		generator:      'links',
		callback:       'dg_callback',
		requestid:      new Date().getTime()
	};
	if (clcontinue) {
		query = clcontinue;
	}
	disCallApi(query);
}

function dg$isDisambig(categories)
{
	for (var key in categories) {
		if (categories.title  ==  disStr.categoryDabPages)
			return true;
	}
	return false;
}

function dg_callback(data)
{
	if (! data.query)
		return;

	document.data = data;
	for (var pageid in data.query.pages) {
		var page = data.query.pages;
		if (page.categories && dg$isDisambig(page.categories)) {
			if (dg$disambig)
				continue;

			dg$disambig = true;
			dg$uniqueLinks++;
		}
	}

	if (data && data) {
		dg$request(data)
	}
	else if (dg$pageLoaded)
		dg$doColor();
	else
		dg$dataLoaded = true;
}

function dg$doColor() {
	if (! dg$uniqueLinks) {
		disLoadFixer();
		return;
	}

	var links = document.getElementsByTagName('a');
	dg$disambig = false;

	var prefix = mw.util.getUrl("");

	for (var i = 0; i < links.length; i++)
	{
		var link = links;

		if (link.href.substring(0, prefix.length) != prefix)
			continue;

		var title = decodeURIComponent(link.href.substring(prefix.length).replace("_", " "));
		link.title = title;

		if (dg$disambig) {
			dg$links++;
			if (link.text  ==  'inne znaczenia tego określenia')
				continue;

			if (link.parentNode && link.parentNode.className.match(/\bdisambig\b/))
				continue;

			link.className = 'mw-disambig';
		}
	}
	disLoadFixer();
}


function disMarkInit() {
	dg$pageLoaded = true;
	if (dg$dataLoaded)
		dg$doColor();
}


/*
AND FINALLY ONLOAD
*/

if((mw.config.get('wgAction') == 'view'|| mw.config.get('wgAction') == 'purge') && mw.config.get('wgNamespaceNumber') >= 0) {
	dg$request();
	$(document).ready(disMarkInit)
}
if(mw.config.get('wgAction') == 'edit') {
	$(document).ready(disOnloadEdit)
}