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.
/* jshint maxerr: 999 */
/* <nowiki> */
$.when(
	mw.loader.using(['mediawiki.Title', 'ext.gadget.morebits']),
	$.ready
).then(function() {

// hide on special pages and talk pages
if (mw.config.get('wgNamespaceNumber') < 0 || mw.config.get('wgNamespaceNumber') % 2 === 1 || !mw.config.get('wgRevisionId')) {
	return;
}

var advert = ' ([[User:SD0001/easy-merge|easy-merge]])';

var menu = mw.util.addPortletLink('p-cactions', '#', 'easy-merge', 'p-easy-merge', 'Redirect to another article and add merge templates to talk pages');
menu.addEventListener('click', callback);

function callback(e) {
	if (e) e.preventDefault();
	var Window = new Morebits.simpleWindow(600, 500);
	Window.setScriptName('easy-merge');
	Window.setTitle("Redirect and add merge templates to talk pages");
	Window.addFooterLink('Merging articles', 'Wikipedia:Merging');

	var form = new Morebits.quickForm(evaluate);

	form.append({
		type: 'input',
		label: 'Target page: ',
		name: 'target',
		value: (mw.config.get('wgIsRedirect') && $('div.redirectMsg a').length) ? $('div.redirectMsg a').text() : ''
	});

	form.append({
		type: 'input', // changed to 'date' after render
		name: 'date',
		label: 'Date of merger: ',
		value: new Date().toISOString().slice(0, 10),
		tooltip: 'This date is used in the {{merged-from}} and {{merged-to}} templates'
	});

	form.append({
		type: 'checkbox',
		name: 'actions',
		list: [
			{
				label: 'Redirect this page to the target page',
				name: 'redirect',
				checked: !mw.config.get('wgIsRedirect'),
				tooltip: 'Replace contents with redirect to target page. {{R from merge}} will be applied to the redirect. ' +
					'{{R to section}} will also be applied if applicable',
				subgroup: {
					type: 'input',
					label: 'Edit summary: ',
					value: 'Merged content to [[###]], redirecting',
					name: 'summary',
					tooltip: '### will be automatically replaced by name of target page',
					size: '60px'
				}
			},
			{
				label: 'Remove merge tag from target page (if it exists)',
				name: 'removemerge',
				checked: true
			},
			{
				label: 'Add {{merged-from}} to talk page of target page',
				name: 'addmergedfrom',
				checked: true
			},
			{
				label: 'Add {{merged-to}} to talk page of this page',
				name: 'addmergedto',
				checked: true
			},
			{
				label: 'Adjust WikiProject banners and templates',
				tooltip: 'For WikiProject banners, class is set to redirect and importance is removed. Any media needed templates are also removed',
				name: 'adjusttalktemplates',
				checked: true
			},
			{
				label: 'Retain categories on redirect',
				tooltip: 'Do not remove the categories on the page while redirecting',
				name: 'retaincats',
				checked: false
			}
		]
	});

	form.append({ type: 'submit', label: 'Submit' });

	var result = form.render();
	result.date.type = 'date';
	result.date.required = true;

	Window.setContent(result);
	Window.display();

}

function evaluate(e) {
	var form = e.target;

	var params = {};
	params.target = form.target.value;
	if (!params.target.trim()) {
		alert('Please enter the target page of merge');
		return;
	}
	params.current = Morebits.pageNameNorm;

	params.redirect = form.redirect.checked;
	params.summary = form['redirect.summary'] && form['redirect.summary'].value.replace('###', params.target);
	params.removemerge = form.removemerge.checked;
	params.addmergedfrom = form.addmergedfrom.checked;
	params.addmergedto = form.addmergedto.checked;
	params.adjusttalktemplates = form.adjusttalktemplates.checked;
	params.retaincats = form.retaincats.checked;

	var dateobj = new Morebits.date(form.date.value);
	if (isNaN(dateobj.getTime())) {
		alert('Invalid date. Please enter in YYYY-MM-DD format'); // should arise only for browsers w/o datepicker
		return;
	}
	params.date = dateobj.getUTCDate() + ' ' + dateobj.getUTCMonthName() + ' ' + dateobj.getUTCFullYear();

	Morebits.simpleWindow.setButtonsEnabled(false);
	Morebits.status.init(form);
	Morebits.wiki.api.setApiUserAgent('[[w:User:SD0001/easy-merge.js]]');

	if (params.redirect) {
		var page = new Morebits.wiki.page(params.current, 'Redirecting');
		page.load(function(page) {
			var pageText = '#REDIRECT [[' + params.target + ']]\n\n{{R from merge}}';
			if (params.target.indexOf('#') !== -1) {
				pageText += '\n{{R to section}}';
			}
			if (params.retaincats) {
				var cats = page.getPageText().match(/\[\[[Cc]ategory:.*?\]\]/g);
				if (cats) {
					pageText += '\n\n' + cats.join('\n');
				}
			}
			page.setPageText(pageText);
			page.setEditSummary(params.summary + advert);
			page.setCreateOption('nocreate');
			page.save();
		});
	}

	if (params.removemerge) {
		var targetpage = new Morebits.wiki.page(params.target, 'Removing {{merge from}} from target page');
		targetpage.load(function(e) {
			var text = e.getPageText();
			var rgx1 = new RegExp('\\{\\{[mM]erge[- ]?[fF]rom\\s*\\|' + Morebits.pageNameRegex(params.current) + '[^}]*\\}\\}\\n?');
			var rgx2 = new RegExp('\\{\\{[bB]eing merged\\s*\\|' + Morebits.pageNameRegex(params.current) + '[^}]*\\}\\}\\n?');
			var newtext = text.replace(rgx1, '').replace(rgx2, '');
			if (text !== newtext) {
				targetpage.setPageText(newtext);
				targetpage.setEditSummary('Removing merge template after merging' + advert);
				targetpage.setCreateOption('nocreate');
				targetpage.save();
			} else {
				targetpage.getStatusElement().info('Not found');
			}
		});
	}

	if (params.addmergedfrom) {
		var targettalkpage = new mw.Title(params.target).getTalkPage().toText();
		var targettalk = new Morebits.wiki.page(targettalkpage, 'Adding {{merged-from}} to target talk page');
		targettalk.setPrependText('{{merged-from|' + params.current + '|' + params.date + '}}\n');
		targettalk.setEditSummary('Adding {{merged-from|' + params.current + '}}' + advert);
		targettalk.prepend();
	}

	if (params.addmergedto || params.adjusttalktemplates) {
		var curentalkpage = new mw.Title(params.current).getTalkPage().toText();
		var sttext;
		if (params.addmergedto) {
			sttext = 'Adding {{merged-to}} to talk page';
		} else {
			sttext = 'Adjusting  WikiProject banners';
		}
		var curentalk = new Morebits.wiki.page(curentalkpage, sttext);
		curentalk.setPageSection(0);
		curentalk.load(function(e) {
			var text = e.getPageText();
			if (params.addmergedto) {
				var mergedto = '{{merged-to|' + params.target + '|' + params.date + '}}\n';
				text = mergedto + text;
			}
			if (params.adjusttalktemplates) {
				text = text
					.replace(/\|\s*class\s*=[^}|]*/g, '|class=redirect')  // set class to redirect
					.replace(/\|[^|}]*?importance\s*=[^}|]*/g, '')  // remove importance param
					.replace(/\|(?:[^|}]*-needed|needs-[^|}]*)\s*=[^|}]*/g, '')  // remove any media-needed or needs-media params
					.replace(/\{\{[^|}]* (?:requested|needed)[^}]*\}\}\n?/g, ''); // remove any {{media requeseted}} templates
			}
			if (text === '' && e.getPageText() === '') {
				return; // otherwise in this case, page is created as empty. Morebits bug.
			}
 			curentalk.setPageText(text);
			var summary;
			if (params.addmergedto && params.adjusttalktemplates) {
				summary = 'Adding {{merged-to|' + params.target + '}} and adjusting WikiProject banners';
			} else if (params.addmergedto) {
				summary = 'Adding {{merged-to|' + params.target + '}}';
			} else if (params.adjusttalktemplates) {
				summary = 'Adjusting WikiProject banners';
			}
			curentalk.setEditSummary(summary + advert);
			curentalk.save();
		});
	}

}

});
/* </nowiki> */