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.

/**

 * THE ИƎTTIЯWƎЯ RATER

 */

/*jshint shadow:true, latedef:true, boss:true, scripturl:true, loopfunc:true, undef:true */

/*global $, mw, importStylesheet, wgScript, wgNamespaceIds, wgFormattedNamespaces, wgNamespaceNumber, wgPageName, wgTitle, wgAction */

mw.loader.using(['mediawiki.api', 'mediawiki.Title', 'jquery.ui'], function () {

	"use strict";

	

	if (mw.config.get('wgNamespaceNumber') < 0)

		return;

	

	importStylesheet('User:Kephir/gadgets/rater.css');

	

	/*

	== Code ==

	 */

	var api = new mw.Api();

	

	/*

	=== Template data ===

	 */

	var raterData = {};

		

	function getRaterData(kind) {

		var ext = 'projects'].indexOf(kind) > -1 ? '.json' : '.js';

		if (raterDatakind === void(null)) {

			try {

				$.ajax({

					'url': mw.config.get('wgScript') + '?action=raw&ctype=application/json&maxage=86400&title=User:Kephir/gadgets/rater/' + kind + ext,

					'dataType': 'json',

					'async': false,

					'success': function (data) {

						raterDatakind = data;

					},

					'error': function (xhr, message) {

						//alert('Error retrieving Rater "' + kind + '" data: ' + message + '. Rater will probably fail to work.');

						raterDatakind = null;

					}

				});

			}  catch (e) {

			}

		}

		return raterDatakind];

	}

	

	var projectKeywords = null;

	

	function getKeywordsMapping() {

		if (projectKeywords === null) {

			var projects = getRaterData('projects');

			projectKeywords = {};

			for (var key in projects) {

				for (var i = 0; i < projectskey].length; ++i) {

					projectKeywordsprojectskey][i].toLowerCase()] = key;

				}

			}

		}

		return projectKeywords;

	}

	

	function cloneInto(what, target) {

		if (typeof what === 'object') {

			if (what === null)

				return what;

			if ((target === null) || (typeof target !== 'object'))

				target = {};

			for (var key in what) {

				targetkey = cloneInto(whatkey], targetkey]);

			}

			return target;

		} else

			return what;

	}

	

	function clone(what) {

		return cloneInto(what, null);

	}

	

	var projectData = {};

	function getTemplateInfo(name) {

		if (projectDataname === void(null)) {

			try {

				$.ajax({

					'url': mw.config.get('wgScript') + '?action=raw&ctype=application/json&maxage=86400&title=Template:' + name + '/rater-data.js',

					'dataType': 'json',

					'async': false,

					'success': function (data) {

						projectDataname = data;

					},

					'error': function (xhr, message) {

						if (xhr.status === 404) { // just pretend nothing happened.

							projectDataname = null;

							return;

						}

						//alert('Error retrieving template data for "' + name + '": ' + e.message + '. Please fix it if you can. Falling back to default data, which may be inaccurate.');

						projectDataname = null;

					}

				});

			}  catch (e) {

			}

		}

		return projectDataname];

	}

		

	function wantedTemplate(name) {

		var projects = getRaterData('projects');

		return name in projects;

	}

	

	function normaliseTitle(name) {

		var aliases = getRaterData('aliases');

		name = (new mw.Title(name)).getMainText();

		if (aliasesname])

			name = aliasesname];

		return name;

	}

	

	/*

	=== Template object ===

	 */

	function ProjectTemplate(name, params, postws) {

		var sumtrack = {};

		var isnew = (params === null);

		var dropped = false;

		var tpinfo = getTemplateInfo(name);

		var defdata = getRaterData('default');

		var fallback;

	

		if (tpinfo === null || typeof(tpinfo) === 'undefined') {

			tpinfo = {};

			fallback = true;

		}

		tpinfo = cloneInto(tpinfo, clone(defdata));

	

		// make data nice

		if (tpinfo.taskforces) {

			if (tpinfo.taskforces.items) {

				var newtf = [];

				for (var key in tpinfo.taskforces.items) {

					var tfe = {

						'name': tpinfo.taskforces.itemskey],

						'part': (typeof tpinfo.taskforces.partsuf === 'string') ? key + tpinfo.taskforces.partsuf : null,

						'prio': (typeof tpinfo.taskforces.priosuf === 'string') ? key + tpinfo.taskforces.priosuf : null

					};

					newtfnewtf.length = tfe;

				}

				tpinfo.taskforces = newtf;

			}

		} else

			tpinfo.taskforces = [];

	

		for (var key in tpinfo.params)

			if (tpinfo.paramskey === null)

				delete tpinfo.paramskey];

	

		for (var i = 0; i < tpinfo.taskforces.length; ++i) {

			var tf = tpinfo.taskforcesi];

			if (tf.part) {

				tpinfo.paramstf.part = cloneInto(tpinfo.paramstf.part || {}, {

					'group': 'task'

				});

			}

			if (tf.prio) {

				tpinfo.paramstf.prio = cloneInto(tpinfo.paramstf.prio || {}, {

					'group': 'task'

				});

			}

			if (tf.prio && tf.part) {

				tpinfo.paramstf.prio].implies = tf.part;

			}

		}

	

		params = params || {};

	

		// process params

		for (var key in params) {

			if ((key in tpinfo.params) && (tpinfo.paramskey].alias)) {

				paramstpinfo.paramskey].alias = paramskey];

				delete paramskey];

			}

		}

	

		this.isFallback = function () {

			return fallback;

		};

	

		this.getParam = function (key) {

			return key in params ? paramskey : null;

		};

		

		this.setParam = function (key, value) {

			if ((value === null) || (value === void(null)))

				return this.delParam(key);

			paramskey = String(value);

			sumtrackkey = String(value);

			return value;

		};

		

		this.delParam = function (key) {

			delete paramskey];

			sumtrackkey = false;

			return void(null);

		};

	

		this.serialise = function () {

			if (dropped)

				return '';

			var result = '{{' + name;

			for (var key in params) {

				result += ' |' + key + '=' + paramskey];

			}

			return result + '}}' + postws;

		};

		

		this.getChanges = function () {

			if (dropped)

				return isnew ? '' : '-' + this.getProjectName();

			var result = [];

			for (var key in sumtrack) {

				if (sumtrackkey !== false)

					resultresult.length = key + '=' + sumtrackkey];

				else

					resultresult.length = '-' + key;

			}

			if (!result.length) {

				if (isnew)

					return '+' + this.getProjectName();

				return void(null);

			}

			return (isnew ? '+' : '') + this.getProjectName() + ': ' + result.join(", ");

		};

		

		this.getProjectName = function () {

			if (tpinfo.name)

				return tpinfo.name;

			return name.replace(/^WikiProject /, '');

		};

		

		this.getTemplateName = function () {

			return name;

		};

		

		this.getParamData = function (key) {

			var defParamData = {

				'desc': key,

				'group': (key in tpinfo.params) ? 'main' : 'unk',

				'mandatory': false,

				'obsolete': false,

				'values': 'string',

				'defvalue': (key in tpinfo.params) ?

					( (tpinfo.paramskey].values === 'flag-temp') ? 'y'

					: (tpinfo.paramskey].values === 'flag-perm') ? 'n'

					: ''

				) : ''

			};

			return cloneInto(tpinfo.paramskey || {}, defParamData);

		};

		

		this.drop = function () {

			return dropped = !dropped;

		};

	

		this.forEachParam = function (walker) {

			for (var key in tpinfo.params) {

				if (tpinfo.paramskey].alias)

					continue;

				if (walker(key, key in params ? paramskey : null, this.getParamData(key)))

					return;

			}

			for (var key in params) {

				if (!(key in tpinfo.params))

					if (walker(key, paramskey], this.getParamData(key)))

						return;

			}

		};

		

		this.forEachTaskForce = function (walker) {

			for (var i = 0; i < tpinfo.taskforces.length; ++i) {

				var tf = tpinfo.taskforcesi];

				if (walker(tf.name, this.getParam(tf.part), this.getParam(tf.prio), tf.part, tf.prio))

					return;

			}

		};

	}

	

	/*

	=== Interface ===

	 */

	function UserInterface() {

		if (this === window)

			return new UserInterface();

	

		var self = this;

	

		function el(tag, child, attr, events) {

			var node = document.createElement(tag);

	

			if (child) {

				if (typeof child !== 'object')

					child = child];

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

					var ch = childi];

					if ((ch === void(null)) || (ch === null))

						continue;

					else if (typeof ch !== 'object')

						ch = document.createTextNode(String(ch));

					node.appendChild(ch);

				}

			}

	

			if (attr) for (var key in attr) {

				node.setAttribute(key, String(attrkey]));

			}

	

			if (events) for (var key in events) {

				node.addEventListener(key, eventskey], false);

			}

	

			return node;

		}

	

		function link(child, href, attr, ev) {

			attr = attr || {};

			ev = ev || {};

			if (typeof href === 'string')

				attr.href = href;

			else {

				attr.href = 'javascript:void(null);';

				ev.click = href;

			}

			return el('a', child, attr, ev);

		}

	

		function pform(child, handler, attr) {

			attr = attr || {};

			attr.action = 'javascript:void(null);';

			return el('form', child, attr, { 'submit': handler });

		}

		

		var pluckedData = [];

		var tab = null, null, null];

		

		var tabIsFresh = false, false, false];

		var uiSource, uiPreview, uiStatus, uiTemplates, uiSummary, uiAddTemplName;

		var dirtySummary = false;

		

		var curTab = 0;

		function setTab(target) {

			tabcurTab].style.display = 'none';

			tabcurTab = target].style.display = '';

		}

		

		function switchTab(target) {

			if (!tabIsFreshtarget]) {

				if (target === 2) { // preview

					var source = tabIsFresh1 ? uiSource.value : serialise();

					api.post({

						'action': 'parse',

						'title': talkpage,

						'text': source,

						'pst': '1',

						'prop': 'text'

					}, {

						success: function (result) {

							uiPreview.innerHTML = result.parse.text'*']; // XXX

							setTab(target);

							tabIsFresh2 = true;

						},

						error: function () {

							self.setStatus('Rendering error.');

						}

					});

					return;

				} else if (target === 1) { // source

					if (tabIsFresh0]) {

						uiSource.value = serialise();

					}

				} else if (target === 0) { // editor

					try {

						self.extract(uiSource.value);

					} catch (e) {

						self.setStatus(e.message + ' — edit the source and try again.');

						return;

					}

				}

				tabIsFreshtarget = true;

			}

			

			setTab(target);

		}

		

		function tabSwitcher(target) {

			return function (ev) {

				switchTab(target);

			};

		}

		

		function serialise() {

			var result = '';

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

				if (typeof pluckedDatai === 'string')

					result += pluckedDatai];

				else if (pluckedDatai].serialise)

					result += pluckedDatai].serialise();

			}

			return result;

		}

		

		function gatherSummary() {

			var sums = [];

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

				if (pluckedDatai].getChanges) {

					var ch = pluckedDatai].getChanges();

					if (ch) sumssums.length = ch;

				}

			}

			return 'Assessment: ' + sums.join('; ') + ' ([[User:Kephir/gadgets/rater|assisted]])';

		}

	

		var lastTemplate;

		var contig;

	

		var uiProjList = el('datalist');

		(function () {

			var projects = getRaterData('projects');

			for (var key in projects) {

				var pname = projectskey][0 || key.replace(/^WikiProject /, '');

				uiProjList.appendChild(el('option', pname], { 'value': pname }));

			}

		})();

		

		var uiBox = el('div', 

			// header

			el('h2', 'Assessment',

				el('span', '\u00a0[', link('close', function (ev) {

					ev.preventDefault();

					self.show(false);

				}), ']'], { 'class': 'editsection' }),

				el('span', '\u00a0[',

					'β (2012-11-11) | ',

					link('about', mw.util.getUrl('User:Kephir/gadgets/rater'), { 'title': 'About this tool' }), ' | ',

					link('feedback', '/wiki/User_talk:Kephir/gadgets/rater?action=edit&section=new&preloadtitle=Feedback', { 'title': 'Feedback' }),

				']'], { 'class': 'editsection' })

			]),

				

			// tabs

			el('ul', 

				el('li', link('Editor' , tabSwitcher(0))]),

				el('li', link('Source' , tabSwitcher(1))]),

				el('li', link('Preview', tabSwitcher(2))])

			], { 'class': 'tabs' }),

				

			// body: main

			tab0 = el('div', 

				uiTemplates = el('ul'),

				el('div', 

					'Notes',

					el('ul', 

						el('li', 

							'Some WikiProject templates (marked ', el('span', 'like this', { 'class': 'fallback' }),

							') lack Rater data. Because of this, default data is used, which sometimes does not reflect actual parameters recognised by the template. For example, some project banners do not use the importance or request for image/infobox fields, or use atypical names for them. Please use the preview to check if the parameters are recognised, the source editor to make corrections or follow the [ed] link to fill in template data. ', link('Flush your browser cache', mw.util.getUrl('WP:BYPASS')), ' to make sure Rater uses fresh template data.'

						])

					])

				], { 'class': 'notes' }),

				el('form', 

					uiAddTemplName = el('input', null, {

						'type': 'text',

						'size': '30',

						'placeholder': 'keyword, project or template name',

						'class': 'name'

					}),

					el('input', null, {

						'type': 'submit',

						'value': 'add'

					})

				], { 'action': 'javascript:void(0);', 'class': 'new-template' }, {

					'submit': function (ev) {

						var name = uiAddTemplName.value;

						if (!name)

							return;

						var keywords = getKeywordsMapping();

						if (keywordsname.toLowerCase()])

							name = keywordsname.toLowerCase()];

						name = normaliseTitle(name);

						if (!wantedTemplate(name))

							name = 'WikiProject ' + name;

						if (!wantedTemplate(name)) {

							if (!confirm('"' + uiAddTemplName.value + '" does not refer to a known WikiProject (see /info/en/?search=User:Kephir/gadgets/rater/projects.js). Add anyway?'))

								return;

						}

						var ptpl = new ProjectTemplate(name, null, '\n');

						pluckedData.splice(++lastTemplate, 0, ptpl);

						uiTemplates.appendChild(createUIForProjectTemplate(ptpl, true));

						tabIsFresh1 = tabIsFresh2 = false;

						uiAddTemplName.value = '';

						if (!dirtySummary) {

							uiSummary.value = gatherSummary();

						}

					}

				})

			]),

				

			// body: source

			tab1 = el('div', 

				uiSource = el('textarea', null, {

					'rows': 15,

					'cols': 70

				}, {

					'keypress': function () {

						tabIsFresh0 = tabIsFresh2 = false;

						if (!dirtySummary) {

							dirtySummary = true;

							uiSummary.classList.add('dirty');

							uiSummary.value = 'Talk page header changes ([[User:Kephir/gadgets/rater|assisted]])';

						}

					},

					'change': function () {

						tabIsFresh0 = tabIsFresh2 = false;

						if (!dirtySummary) {

							dirtySummary = true;

							uiSummary.classList.add('dirty');

							uiSummary.value = 'Talk page header changes ([[User:Kephir/gadgets/rater|assisted]])';

						}

					}

				})

			]),

	

			// body: preview

			tab2 = el('div', 

				uiPreview = el('div')

			]),

	

			el('br', null, { 'class': 'before-footer' }),

	

			// footer

			el('div', 

				el('div', 

					el('label', 'Summary: '),

					uiSummary = el('input', null, {

						'type': 'text',

						'size': '60'

					}, { 'keypress': function (ev) {

						if (!dirtySummary) {

							dirtySummary = true;

							this.classList.add('dirty');

						}

					}})

				]),

				el('span', uiStatus = document.createTextNode('')], { 'class': 'status-line' }),

				el('input', null, {

					'type': 'button',

					'value': 'Save',

					'class': 'save-button'

				}, { 'click': function (ev) {

					var summary = uiSummary.value;

					var markup = (curTab === 0) ? serialise() : uiSource.value;

					self.setStatus('Submitting…');

					self.save(markup, summary, {

						success: function () {

							self.setStatus('Updated.');

							setTimeout(function () {

								self.show(false);

							}, 1500);

						},

						error: function () {

							console.error(arguments);

							self.setStatus('Error.');

						}

					});

				} }),

				el('br')

			], { 'class': 'bottom' }),

				

			// nothing

			null

		], { 'class': 'kephir-rater' });

		

		$(uiBox).draggable().resizable(); // XXX: jQuery sucks

		tab0].style.display = tab1].style.display = tab2].style.display = 'none';

	

		function createUIForProjectTemplate(tp, expanded) {

			var paramWidget = {};

			

			function normaliseBool(value) {

				if (typeof value === 'boolean')

					return value;

				if ((value === '1') || (value === 'Y') || (value === 'y') || (value.toLowerCase() === 'yes'))

					return true;

				if ((value === '0') || (value === 'N') || (value === 'n') || (value.toLowerCase() === 'no'))

					return false;

				throw new Error("cannot normalise boolean value");

			}

			

			function updateValue(param, value) {

				tabIsFresh1 = tabIsFresh2 = false;

				tp.setParam(param, value);

				if (!dirtySummary) {

					uiSummary.value = gatherSummary();

				}

			}

	

			var grph = { };

			function createWidget(name, value, data) {

				var widget;

				

				var dataTypes = {

					'flag-temp': function () {

						widget = el('input', null, { 'type': 'checkbox' });

						widget.checked = normaliseBool(value);

						widget.addEventListener('change', function () {

							updateValue(name, this.checked ? 'yes' : null);

						}, false);

					},

					'flag-perm': function () {

						widget = el('input', null, { 'type': 'checkbox' });

						widget.checked = normaliseBool(value);

						widget.addEventListener('change', function () {

							updateValue(name, this.checked ? 'yes' : 'no');

						}, false);

					},

					'flag-inv': function () {

						widget = el('input', null, { 'type': 'checkbox' });

						widget.checked = !normaliseBool(value);

						widget.addEventListener('change', function () {

							updateValue(name, this.checked ? 'no' : 'yes');

						}, false);

					},

					'string': function () {

						widget = el('input', null, { 'type': 'text' });

						widget.value = value;

						widget.addEventListener('change', function () {

							updateValue(name, this.value);

						}, false);

						widget.addEventListener('keypress', function () {

							updateValue(name, this.value);

						}, false);

					},

					'class-std': {

						'list': '', 'Stub', 'Start', 'C', 'B', 'GA', 'A', 'FA', 'List', 'FL', 'NA'],

						'normalise': 'mlc'

					},

					'class-ext': {

						'list': '', 'Stub', 'Start', 'C', 'B', 'GA', 'A', 'FA', 'List', 'FL', 'NA', 'Category', 'Disambig', 'File', 'Portal', 'Project', 'Template', 'Redirect', 'Draft'],

						'normalise': 'mlc'

					},

					'importance-std': {

						'list': '', 'Top', 'High', 'Mid', 'Low', 'Bottom', 'NA', 'Unknown'],

						'normalise': 'mlc'

					}

				};

				var uiName = el('span', data.desc]);

				var uiHelp = null;

				

				if (typeof data.values === 'string') {

					try {

						if (typeof dataTypesdata.values === 'function')

							dataTypesdata.values]();

						else if (dataTypesdata.values])

							data.values = dataTypesdata.values];

						else

							dataTypes.string();

					} catch (e) {

						dataTypes.string();

					}

				}

	

				if (data.values.list) {

					widget = el('select');

					

					var vlist;

					if (data.values.list instanceof Array) {

						vlist = data.values.list;

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

							widget.appendChild(el('option', vlisti]], { 'value': vlisti }));

						}

					} else {

						vlist = Object.keys(data.values.list);

						for (var key in data.values.list) {

							widget.appendChild(el('option', data.values.listkey]], { 'value': key }));

						}

					}

					

					if (data.values.normalise) {

						value = value || '';

						switch (data.values.normalise) {

						case 'lc':

							value = value.toLowerCase();

							break;

						case 'mlc':

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

								if (vlisti].toLowerCase() === value.toLowerCase()) {

									value = vlisti];

									break;

								}

							}

							break;

						}

					}

	

					if (data.values.aliases) {

						if (value in data.values.aliases) {

							value = data.values.aliasesvalue];

						}

					}

	

					if (vlist.indexOf(value) === -1) {

						dataTypes.string();

						// TODO: datalist

					} else {

						widget.value = value;

						widget.addEventListener('change', function () {

							updateValue(name, this.value);

						}, false);

					}

				}

	

				// TODO: datalist

	

				if (data.obsolete) {

					uiName.classList.add('obsolete');

					uiName.title = 'This parameter is obsolete.';

				}

				

				if (data.helplink) {

					uiHelp = el('span', '[', link('?', mw.util.getUrl(data.helplink)), ']']);

				}

	

				paramWidgetname = widget;

				return el('li', uiName, uiHelp && ' ', uiHelp, ': ', widget]);

			}

			

			function createPlaceholder(name, data) {

				var pholder = el('li', paramWidgetname = link(data.desc, function (ev) {

					tabIsFresh1 = tabIsFresh2 = false;

					tp.setParam(name, data.defvalue);

					if (grphdata.group])

						grphdata.group].classList.remove('absent');

					var widget = createWidget(name, data.defvalue, data);

					pholder.parentNode.insertBefore(widget, pholder);

					pholder.parentNode.removeChild(pholder);

					if (!dirtySummary) {

						uiSummary.value = gatherSummary();

					}

				})], { 'class': 'absent' });

				return pholder;

			}

			

			function createWidgetTF(tfname, part, prio, partpname, priopname, prioscale) {

				var uiCheck = null, uiCombo = null;

	

				if (partpname !== null) {

					uiCheck = el('input', null, { 'type': 'checkbox' });

					try {

						uiCheck.checked = normaliseBool(part);

					} catch (e) {

						uiCheck.checked = true;

					}

					uiCheck.addEventListener('change', function (w) {

						updateValue(partpname, this.checked ? 'yes' : null);

					}, false);

					paramWidgetpartpname = uiCheck;

				}

	

				if (priopname !== null) {

					var items = prioscale || "", "Top", "High", "Mid", "Low", "Unknown"]; // XXX

					uiCombo = el('select');

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

						uiCombo.appendChild(el('option', itemsi]], { 'value': itemsi }));

					}

					uiCombo.value = prio;

					uiCombo.addEventListener('change', function () {

						updateValue(priopname, this.value);

					}, false);

					paramWidgetpriopname = uiCombo;

				}

	

				return el('li', uiCheck, tfname, uiCombo && ': ', uiCombo]);

			}

	

			function createPlaceholderTF(tfname, partpname, priopname) {

				var pholder = el('li',  paramWidgetpriopname = paramWidgetpartpname = link(tfname, function (ev) {

					if (partpname) tp.setParam(partpname, 'y');

					if (priopname) tp.setParam(priopname, '');

					var widget = createWidgetTF(tfname, true, '', partpname, priopname);

					grph.task.classList.remove('absent');

					pholder.parentNode.insertBefore(widget, pholder);

					pholder.parentNode.removeChild(pholder);

					if (!dirtySummary) {

						uiSummary.value = gatherSummary();

					}

				})], { 'class': 'absent' });

				return pholder;

			}

	

			var uiParams, uiGroups, uiDel;

			var ui = el('li', 

				uiDel = link('(delete)', function () {

					if (tp.drop())

						ui.classList.add('dropped');

					else

						ui.classList.remove('dropped');

					tabIsFresh1 = tabIsFresh2 = false;

					if (!dirtySummary)

						uiSummary.value = gatherSummary();

				}, { 'class': 'delete-template' }),

				el('b', link(tp.getProjectName(), mw.util.getUrl('Template:' + tp.getTemplateName()))]),

				el('small', ' [', link('ed', '/wiki/Template:' + tp.getTemplateName() + '/rater-data.js?action=edit&editintro=User:Kephir/gadgets/rater/data-editnotice&preload=User:Kephir/gadgets/rater/data-preload'), ']'], { 'class': 'absent', 'title': 'Edit data' }), ': ',

				uiParams = el('ul', [], { 'class': 'params' }),

				uiGroups = el('dl', [], { 'class': 'p-groups' })

			], { 'class': 'template-entry' });

			var grpNames = {

				'vis' : 'Appearance',

				'req' : 'Requests',

				'task': 'Task forces',

				'misc': 'Miscellaneous',

				'unk' : 'Unrecognised'

			};

			var grps = {

				'main': uiParams

			};

			var grpl = {

				'main': null

			};

			

			function addGroup(tag) {

				uiGroups.appendChild(grphtag = el('dt', grpNamestag || tag, { 'class': 'absent' }));

				uiGroups.appendChild(el('dd', grpstag = el('ul', null, { 'class': 'params' })]));

				return grpstag];

			}

	

			if (!expanded) {

				ui.classList.add('hide-absent');

			}

	

			if (tp.isFallback()) {

				ui.classList.add('fallback');

			}

			

			tp.forEachParam(function (name, value, data) {

				if (data.group === 'task')

					return;

				if (!grpsdata.group])

					addGroup(data.group);

				if ((value === null) && !data.mandatory)

					if (!data.obsolete)

						grpsdata.group].appendChild(createPlaceholder(name, data));

					else;

				else {

					grpsdata.group].appendChild(createWidget(name, value, data));

					if (grphdata.group])

						grphdata.group].classList.remove('absent');

				}

			});

			

			tp.forEachTaskForce(function (tfname, part, prio, partpname, priopname) {

				var item;

				if (!grps.task) addGroup('task');

				if (partpname && (part === null))

					item = createPlaceholderTF(tfname, partpname, priopname);

				else {

					item = createWidgetTF(tfname, part, prio, partpname, priopname);

					grph.task.classList.remove('absent');

				}

				grps.task.appendChild(item);

			});

			

			var uiNewCustParmName;

			ui.appendChild(el('div', 

				el('form', 

					uiNewCustParmName = el('input', null, { 'type': 'text', 'placeholder': 'new custom parameter', 'size': 20 }),

					el('input', null, { 'type': 'submit', 'value': 'add' })

				], { 'action': 'javascript:void(0);', 'class': 'new-custom-param' }, {

					'submit': function (ev) {

						var nname = uiNewCustParmName.value;

						tabIsFresh1 = tabIsFresh2 = false;

						if (paramWidgetnname]) {

							if (paramWidgetnname].tagName === 'A') { // XXX - placeholder

								paramWidgetnname].click();

							} else {

								// reactivate if deleted (deleting not implemented yet)

								paramWidgetnname].focus();

							}

						} else {

							var pd = tp.getParamData(nname);

							tp.setParam(nname, '');

							(grpspd.group || addGroup(pd.group)).appendChild(createWidget(nname, '', pd));

							if (!dirtySummary) {

								uiSummary.value = gatherSummary();

							}

						}

						uiNewCustParmName.value = '';

					}

				})

			], { 'class': 'absent' }));

	

			var hidelink, hltext;

			uiParams.appendChild(hidelink = link([hltext = document.createTextNode('[+]')], function () {

				if (!ui.classList.contains('hide-absent')) {	

					ui.classList.add('hide-absent');

					hltext.data = '[+]';

				} else {

					ui.classList.remove('hide-absent');

					hltext.data = '[–]';

				}

			}));

	

			return ui;

		}

		

		this.clear = function () {

			dirtySummary = false;

			uiSummary.value = '';

			uiSummary.classList.remove('dirty');

		};

	

		this.extract = function (markup) {

			var m;

	

			pluckedData = [];

			lastTemplate = -1;

			contig = true;

	

			while (uiTemplates.hasChildNodes())

				uiTemplates.removeChild(uiTemplates.firstChild);

			

			uiSource.value = markup;

			tabIsFresh1 = true;

	

			try {

				// TODO: Parsoid?

				while (markup !== '') {

					if (!(m = /^([^]*?)\{\{\s*((?:\}[^\}\|]|[^\}\|])+?)\s*(?=\||}})/.exec(markup))) {

						pluckedDatapluckedData.length = markup;

						break;

					}

					var name = normaliseTitle(m2]);

					if (!wantedTemplate(name)) {

						pluckedDatapluckedData.length = markup.substr(0, m0].length);

						markup = markup.substr(m0].length);

						continue;

					}

					pluckedDatapluckedData.length = m1];

					var params = {};

					var postws = '';

					markup = markup.substr(m0].length);

					var ppid = 1;

	

					for (;;) {

						if (m = /^\s*}}(\s*)/.exec(markup)) {

							postws = m1];

							markup = markup.substr(m0].length);

							break;

						} else if (m = /^\s*\|\s*([^=\|]+?)\s*=\s*(.*?)\s*(?=\||}})/.exec(markup)) {

							markup = markup.substr(m0].length);

							paramsm1]] = m2];

						} else if (m = /^\s*\|\s*(.*?)\s*(?=\||}})/.exec(markup)) {

							markup = markup.substr(m0].length);

							paramsppid++ = m1];

						} else {

							throw new Error('Broken template invocation for "' + name + '"');

						}

					}

					

					if (lastTemplate !== (pluckedData.length - 1))

						contig = false;

	

					var ptpl = new ProjectTemplate(name, params, postws);

					pluckedDatalastTemplate = pluckedData.length = ptpl;

					uiTemplates.appendChild(createUIForProjectTemplate(ptpl));

				}

	

				tabIsFresh0 = true;

				setTab(0);

			} catch (e) {

				this.setStatus('Error while parsing: ' + e.message + '. Fix the source code and try again.');

				setTab(1);

			}

		};

			

		this.save = function (markup, summary, handlers) {

			alert('@!#?@!\n' + summary + '\n' + markup);

		};

	

		this.show = function (value) {

			uiBox.style.display = value ? '' : 'none';

			if (value) {

				if (curTab === 0)

					uiAddTemplName.focus();

				else if (curTab === 1)

					uiSource.focus();

			}

		};

		

		this.install = function (where) {

			function uniqid() {

				var s = '', cs = 'QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890.-';

				for (var i = 0; i < 24; ++i) {

					s += cs.charAt(Math.floor(Math.random() * cs.length));

				}

				return s;

			}

			where.appendChild(uiBox);

			where.appendChild(uiProjList);

			uiProjList.id = 'kephir-rater-' + uniqid();

			uiAddTemplName.setAttribute('list', uiProjList.id);

		};

		

		this.setStatus = function (message, level) {

			uiStatus.data = message;

		};

		

		return this;

	}

	

	/*

	=== Glue ===

	 */

	var api = new mw.Api();

	

	var ui = new UserInterface();

	ui.show(false);

	ui.install(document.body);

	

	var talkpage = mw.config.get('wgFormattedNamespaces')[mw.config.get('wgNamespaceNumber') - (mw.config.get('wgNamespaceNumber') % 2) + 1 + ':' + mw.config.get('wgTitle');

	

	var link = mw.util.addPortletLink(mw.config.get('skin') === 'vector' ? 'p-views' : 'p-cactions',

		'javascript:void(0);', 'Rater', 'p-kephir-rater', 'Assess article using Rater', '5', '#ca-view'

	);

	if (link)link.addEventListener('click', function (ev) {

		ev.preventDefault();

		api.get({

			action: 'query',

			prop: 'revisions',

			rvprop: 'timestamp|content',

			rvsection: 0,

			rvlimit: 1,

			rvdir: 'older',

			meta: 'tokens',

			type: 'csrf',

			titles: talkpage

		}, {

			success: function (result) {

				var tpgpid = Object.keys(result.query.pages)[0];

				var tpg = result.query.pagestpgpid];

				var tpgstart = tpg.starttimestamp;

				var tpgtoken = result.query.tokens.csrftoken;

				var tpgbase = tpg.revisions ? tpg.revisions0].timestamp : void(0);

				var tpgrev = tpg.lastrevid;

				ui.save = function (markup, summary, handlers) {

					api.post({

						action: 'edit',

						section: 0,

						title: talkpage,

						basetimestamp: tpgbase,

						starttimestamp: tpgstart,

						token: tpgtoken,

						notminor: true,

						summary: summary,

						watchlist: 'nochange',

						text: markup

					}, handlers);

				};

				ui.clear();

				ui.extract(tpg.revisions ? tpg.revisions0]['*' : '');

				ui.show(true);

			},

			error: function () {

				console.error(arguments);

				alert('Error. See console.');

			}

		});

	}, false);

	

	if (/^Category:(Unassessed|Unknown-importance)_.*?_articles$/.test(mw.config.get('wgPageName'))) {

		var pages = document.getElementById('mw-pages');

		if(!pages)return;

		var links = pages.getElementsByTagName('a');

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

			linksi].href = linksi].href.replace(/\/wiki\/Talk:/, '/wiki/');

	}

	

	if ((mw.config.get('wgNamespaceNumber') === mw.config.get('wgNamespaceIds').template) && /\/rater-data\.js$/.test(mw.config.get('wgPageName'))) {

		mw.config.set('wgCodeEditorCurrentLanguage', 'json');

		mw.loader.load('ext.codeEditor');

		if (Object.defineProperty)

			Object.defineProperty(window, 'syntaxHighlighterConfig', {

				'set': function () { }

			});

		else if (window.__defineSetter__)

			window.__defineSetter__('syntaxHighlighterConfig', function () { });

	}

	

	});