Jump to content

User:V111P/js/wikiTranslTools.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by V111P (talk | contribs) at 02:56, 1 December 2013 (v. 2.0. Can be used without preconfiguration). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
/* Wiki Translation Tools v. 2.0 - Nov 30 2013
 * home page: //en.wikipedia.org/wiki/User:V111P/js/Wiki_Translation_Tools
 * CC0 Public Domain Dedication:
 * http://creativecommons.org/publicdomain/zero/1.0/
 * If you use large parts of this code, please let me know.
 * You should also let others know where the code originates:
 * //en.wikipedia.org/wiki/User:V111P/js/wikiTranslTools.js
 * Thanks!
 */
window.wikiTranslTools = (function ()
{
	"use strict";
	var THIS_ARTICLE = mw.config.get('wgPageName').replace(/_/g, ' ');

	/*******
	 * Home-Wiki Constants - need to be set with init()
	 ******/
	var homeWiki = {
		lang: '',
		server: '',
		faLinkTemplate: 'Link FA',
		gaLinkTemplate: 'Link GA',
		translatedPageTemplate: '{{translated page|%sourceWiki%|%pageTitle%|version=%revisionId%}}'
	};

	var skin = { // values must be CSS/jQuery selectors
		interwikiDiv: '#p-lang',
		catLinks: '#mw-normal-catlinks' // the <div> with the non-hidden categories
		//  Leave empty to use the built-in wgCategories array (which includes hidden cats)
	};

	/*******
	 * Local-Wiki Constants
	 ******/
	var thisWiki = {
		lang: mw.config.get('wgContentLanguage'),

		// These strings are used to find out which articles have a 'Good' or 'Featured' status
		//  in this and in the other Wikipedias.
		featArticle: {
			tagIdBeginning: 'interwiki-',
			tagIdEnding:    '-fa',
			tagClass:       '',
			catName:        'Featured articles'
		},

		goodArticle: {
			tagIdBeginning: 'interwiki-',
			tagIdEnding:    '-ga',
			tagClass:       '',
			catName:        'Good articles'
		},

		catNS: mw.config.get('wgFormattedNamespaces')[14] // The local name of the Category namespace
	};

	/******
	 * Other customizable options
	 ******/
	var options = {
		helpUrl: '//en.wikipedia.org/wiki/User:V111P/js/Wiki_Translation_Tools',

		defaultWiki: 'en', // used if homeWiki.lang is not set

		// number of rows for the output textarea
		taRows: 10,

		// this has no effect in Monobook and other skins
		taCols: 80,

		// if the article has that many categories or less, they will be auto-expanded
		//   when the Category Browser is shown for the first time on the page.
		maxCatsToAutoExpand: 5,

		hook: void(0)
	};


	/*******
	 * The Messages
	 ******/
	var msgs = {
		error: 'error',
		okButtonLabel: 'OK',
		translatedPageOption: 'Translated page',
		commonsOption: 'Commons',
		faGaOption: 'FA/GA',
		interwikis: 'Interwikis',
		categories: 'Categories',
		trCatInterw: 'Cat/Tr/FA/Comm',
		trCatInterwTitle: 'Categories, {{Translated page}}, {{Link FA}}, {{Link GA}}, {{Commons}} ',
		alreadyListed: 'already listed',
		linksToLang: 'Links to %targetWiki%',
		enterTargetWiki: 'Please, enter the language code of the other Wikipedia:',
		targetWiki: 'target wiki: %targetWiki%'
	};


	/*******
	 * Other Constants
	 ******/


	// Home wiki links will be added only to these namespaces:
	// Namespases: main=0, user=2, wikipedia/wp=4, template=10, help=12, category=14, portal=100
	var NamespacesWithInterwikis = [0, 2, 4, 10, 12, 14, 100];

	var nl = ($.browser && $.browser.msie ? '\r\n' : '\n');  // new line


	/*******
	 * Private Variables
	 ******/
	var allCats; // used for the Category Browser


	// a shortcut for document.createTextNode()
	function textNode(str)
	{
		return document.createTextNode(str);
	}


	/*************************
	 ***  INTERWIKIS
	 ***
	 ***/


	// reads the interwikis from the element with the specified in SKIN.INTERWIKI_DIV id
	//  calls goodArticleLinks() to check for 'Good' and 'Featured' articles
	function getInterwikiCode(getFaGaTemplatesToo)
	{
		var interwikis = getInterwikis();
		var links = interwikis.links;
		var langs = interwikis.langs;

		/* adding this page's wikilink to the array */
		links[thisWiki.lang] = THIS_ARTICLE;
		langs.push(thisWiki.lang);
		langs.sort();

		var interwikisStr = '';
		for (var i = 0; i < langs.length; i++)
			interwikisStr += '[[' + langs[i] + ':' + links[langs[i]] + ']]' + nl;

		return (getFaGaTemplatesToo ? getFaGaTemplateCode(langs) : '') + interwikisStr;
	}


	function getInterwikis()
	{
		var links = [], langs = [];
		$(skin.interwikiDiv + ' a').each(function (){
			var result = $(this).attr('href').match(/\/\/([^\.]+)\.[^\/]+\/wiki\/(.+)/);
			if (!result || result[1] == 'www')
				return;
			var lang = result[1];
			var title = decodeURI(result[2]).replace(/_/g, ' ');
			if (lang != homeWiki.lang) {
				links[lang] = title;
				langs.push(lang);
			}
		});
		return {langs: langs, links: links};
	}


	/*************************
	 ***  FA/GA templates
	 ***
	 ***/


	// reads the interwikis from the element with the specified in skin.interwikiDiv id
	//  calls goodArticleLinks() to check for 'Good' and 'Featured' articles
	function getFaGaTemplateCode(langArr)
	{
		var langs = langArr || getInterwikis().langs;

		var featArticlesStr = goodArticleLinks(langs, thisWiki.featArticle, homeWiki.faLinkTemplate);
		var goodArticlesStr = goodArticleLinks(langs, thisWiki.goodArticle, homeWiki.gaLinkTemplate);

		return featArticlesStr + goodArticlesStr;
	}


	// this function is used to get both the "Good Articles" and the "Featured Articles"
	function goodArticleLinks(langArr, goodArticleStrings, homeGALinkTemplate)
	{
		var goodArticleArr = [];
		for (var i = 0; i < langArr.length; i++) {
			var goodTag = $('#' + goodArticleStrings.tagIdBeginning
				+ langArr[i]
				+ goodArticleStrings.tagIdEnding);

			if (goodTag[0])
				if (goodArticleStrings.tagClass)
					goodTag = goodTag.filter('.' + goodArticleStrings.tagClass);

			if (goodTag[0])
				goodArticleArr.push(langArr[i]);
		}

		// check and add this article
		var cats = mw.config.get('wgCategories');
		for (var i = cats.length - 1; i >= 0; i--) {
			if (cats[i] == goodArticleStrings.catName) {
				goodArticleArr.push(thisWiki.lang);
				break;
			}
		}

		goodArticleArr.sort();

		var goodArticleStr = '';
		for (var i = 0; i < goodArticleArr.length; i++) {
			goodArticleStr += '{{' + homeGALinkTemplate + '|' + goodArticleArr[i] + '}}' + nl;
		}

		if (goodArticleStr) goodArticleStr += nl;

		return goodArticleStr;
	} // goodArticleLinks


	/*************************
	 ***  COMMONS templates
	 ***
	 ***/


	function getCommonsTemplates() {
		var commonsStr = '', template;
		var $commonsLinks = $('a[href*="//commons.wikimedia.org/wiki/"]');
		var commonsLinksArr = [];
		$commonsLinks.each(function (i, el) {
			var href = $(this).attr('href');
			if (href.match(/wiki\/(file|image|media):/i) || href.match(/Special:UploadWizard/))
				return;
			href = href.replace(/_/g, ' ').replace(/\?.*$/, '');
			var title = decodeURIComponent(href.replace(/.+?\/wiki\//, ''));
			var page = title.replace(/^Category:/, '');
			if (title != href) { 
				if (title.match(/^Atlas of/))
					template = '* {{wikiatlas|' + title.replace(/^Atlas of./, '') + '}}';
				else
					template = '{{commons' + (page != title ? 'cat' : '')
						+ '|' + page + '}}';
				if ($.inArray(template, commonsLinksArr) == -1)
					commonsLinksArr.push(template);
			}
		});
		if (commonsStr = commonsLinksArr.join('\n'))
			commonsStr += '\n\n';

		return commonsStr;
	}


	/*************************
	 ***  OPTIONS PANEL
	 ***
	 ***/


	/* PUBLIC */
	// called when the user clicks on the "Cat/Tr/FA/Comm" portlet link
	function showPanel()
	{
		$('#wikiTranslToolsCodeBox').remove();

		if (!$('#wikiTranslToolsPanel').show()[0])
			createThePanel();
		$('html, body').scrollTop(0);
	}


	// Called from categories() to create the Category Browser
	function createThePanel()
	{
		if (!homeWiki.lang)
			setHomeWikiLang(prompt(msgs.enterTargetWiki, options.defaultWiki));

		var $wikiTranslToolsPanel = $('<div/>', {
			css: {color: '#000', backgroundColor: '#f4f4f4', fontSize: 'small', position: 'relative', marginBottom: '1em'},
			id: 'wikiTranslToolsPanel'
		}).append(
			$('<a/>', {
				text: msgs.targetWiki.replace(/%targetWiki%/, (homeWiki.lang || options.defaultWiki)),
				href: '#',
				'class': 'wtt_targetWikiLangLink',
				css: {
					marginRight: '1em',
					position: 'absolute',
					bottom: '2px',
					right: '2px'
				},
				click: function (e) {
					e.preventDefault();
					setHomeWikiLang(prompt(msgs.enterTargetWiki, (homeWiki.lang || options.defaultWiki)));
				}
			}),
			$('<div/>', {
				css: {position: 'absolute', right: '2px', top: '2px'}
			}).append(
				$('<a/>', {
					text: '[?]',
					target: '_blank',
					href: options.helpUrl
				}),
				$('<a/>', {
					text: '[X]',
					href: '#',
					click: function (e) {
						e.preventDefault();
						$wikiTranslToolsPanel.hide();
					}
				})
			)
		);

		var optionCheckboxes = [
			{val: 'translatedPage', checked: true, label: msgs.translatedPageOption},
			{val: 'commons', checked: true, label: msgs.commonsOption},
			{val: 'faGa', checked: true, label: msgs.faGaOption},
			{val: 'interwikis', checked: false, label: msgs.interwikis}
		];

		var $form = $('<form/>', {
			id: 'wikiTranslToolsForm',
			submit: function() {
				formOk(this);
				return false;
			}
		})
		.append('<input type="submit" value="' + msgs.okButtonLabel + '"/>');

		$.each(optionCheckboxes, function (i, val) {
			$form.append($('<label style="margin-left:0.5em;">').append($('<input type="checkbox">').attr({
				name: 'options',
				value: val.val,
				checked: (val.checked? 'checked' : null)
			}), textNode(val.label)))
		});

		$form.append('<div style="margin-top:1em;"><b>' + msgs.categories + '</b><div>',
			createTheCategoryBrowser(),
			'<input type="submit" value="' + msgs.okButtonLabel + '" style="margin-top:1em;"/>'
		);
		$wikiTranslToolsPanel.append($form)
		.prependTo(mw.util.$content);
	} // createThePanel()


	function formOk(frm)
	{
		var checkedOptions = {};
		var optionCheckboxes = $('input:checkbox[name=options]:checked', frm);

		$.each(optionCheckboxes, function (i, val) {
			checkedOptions[val.value] = true;
		});

		var catsStr = getCheckedCats(frm);
		$('#wikiTranslToolsPanel').hide();
		displayCode(
			  (checkedOptions.commons ? getCommonsTemplates() : '')
			+ (checkedOptions.translatedPage ? homeWiki.translatedPageTemplate + nl + nl : '')
			+ (catsStr ? catsStr + nl + nl : '')
			+ (checkedOptions.interwikis ? getInterwikiCode(checkedOptions.faGa) :
				(checkedOptions.faGa ? getFaGaTemplateCode() : '')
			  )
		);
	}


	/*************************
	 ***  CATEGORIES
	 ***
	 ***/


	function createTheCategoryBrowser() {
		var catArr = [];

		// if possible, fill catArr with the non-hidden cats only,
		//  otherwise use wgCategories
		if (skin.catLinks)
			catArr = $(skin.catLinks + ' a').map(function(i) {
				if (i == 0) return null; // skip the 'Categories:' link
				return $(this).text();
			}).toArray();
		else
			catArr = mw.config.get('wgCategories');

		if (catArr.length == 0)
			return $([]);

		allCats = {};

		// create the main UL and sub li's with the category names
		var $top_ul = $('<ul/>', {'class': 'wtt_catBrowser'});

		var $top_li;
		for (var i = 0; i < catArr.length; i++)
		{
			var expandLink = createExpandCatLink();

			$top_li = $('<li/>').append(expandLink, textNode(' '), '<span>' + catArr[i] + '</span>');
			allCats[catArr[i]] = {
				name: catArr[i],
				liElement: $top_li // the innermost <li> within which the category's name is shown
			};

			$top_ul.append($top_li);

			if (catArr.length <= options.maxCatsToAutoExpand)
				expandLink.click();
		}

		return $top_ul[0];
	} // createTheCategoryBrowser


	function createExpandCatLink()
	{
		return $('<a/>', {
			text: '[+]',
			href: '#',
			click: function() {
				expandCat(this);
				return false;
			},
			css: {textDecoration: 'none'}
		});
	}


	// Called when the user clicks on a [+] expand link in the Category Browser
	// It makes an AJAX request for the specified category page,
	//  and calls showCatParents() to display the obtained information
	// (the parent cats and (if there is one) the home-wiki cat)
	function expandCat(startCatExpandLinkEl)
	{
		var startCatLink = $(startCatExpandLinkEl);
		var catSpan = $('span', startCatLink.parent()); // it contains the name of the cat to be expanded

		startCatLink.off('click').text('...'); // replace "[+]" with "..."
		startCatLink.attr('class', 'waitingExpandLink');
		var cat = allCats[$(catSpan[0]).text()];

		$.ajax({
			url: '/w/api.php?action=query&prop=langlinks|categories&titles=' + thisWiki.catNS + ':'
				+ cat.name + '&lllang=' + (homeWiki.lang || options.defaultWiki) + '&cllimit=200&redirects&format=json',
			dataType: 'json',
			success: catInfoReceived(cat),
			error: function (XMLHttpRequest) {
				showCatParents(cat);
			}
		});
		
	}


	// creates and returns a function to be called when the requested Category page information is received
	function catInfoReceived(cat)
	{
		return function(data) {

			function parentCats(data) {
				var pages = data && data.query && data.query.pages;
				if (!pages)
					return;

				var pg;
				for (var p in pages) {
					if (pages.hasOwnProperty(p))
						pg = pages[p];
				}

				var catObjs = pg && pg.categories;
				if (!catObjs)
					return;

				var cats = [];
				for (var i = 0; i < catObjs.length; i++) {
					cats.push(catObjs[i].title.replace(/^[^:]+:/, ''));
				}
				return cats;
			}

			showCatParents(cat, parentCats(data), getHomewikiFromJson(data));
		};
	} // catInfoReceived


	// called by expandCat() to add the parent categories
	//  of the specified category to the displayed list.
	function showCatParents(cat, parents, homeWikiCat)
	{
		var top_li = cat.liElement;
		var server = mw.config.get('wgServer');

		$('.waitingExpandLink', top_li).remove();

		if (homeWikiCat) {
			var homeWikiLink = $('<a/>', {
				text: homeWikiCat,
				href: homeWiki.server + '/wiki/' + homeWikiCat,
				target: '_blank'
			});

			top_li.append(textNode(' – '),
				'<input type="checkbox" name="homecats" value="' + homeWikiCat + '"/>',
				textNode(' ' + (homeWiki.lang || options.defaultWiki) + ':'),
				homeWikiLink);
		}
		else if (parents && parents.length > 0) {
			var new_ul = $('<ul/>');

			var new_li;
			var alreadyListed;
			for (var i = 0; i < parents.length; i++) {
				new_li = $('<li/>');

				alreadyListed = false;

				if (allCats[parents[i]])
					alreadyListed = $('<em>(' + msgs.alreadyListed + ')</em>');
				else {
					new_li.append(createExpandCatLink(), textNode(' '));
					allCats[parents[i]] = {
						name: parents[i],
						liElement: new_li // the innermost <li> within which the category's name is shown
					};
				}

				new_li.append('<span>' + parents[i] + '</span>');
				if (alreadyListed)
					new_li.append(textNode(' '), alreadyListed);
				new_ul.append(new_li);
			}

			top_li.append(new_ul);
		} // if (parents.length > 0)
		else { // if no home-wiki cat and no parent cats found, create a link to the cat,
			//  so the user can check manually
			var catSpan = $('span', top_li).empty();
			catSpan.append($('<a/>', {
				href: server + '/wiki/'
					+ thisWiki.catNS + ':' + cat.name,
				target: '_blank',
				text: cat.name
			}))
			.append(textNode(' '),
				// no parents arr is passed if the cat doesn't exist (404 or other error received)
				$('<em>(' + msgs.error + ')</em>')
			);
		}
	} // showCatParents


	// called when the user press the OK button in the "Category Browser"
	function getCheckedCats(frm)
	{
		var homeCats = $('input:checkbox[name=homecats]:checked', frm).map(function(){
			return this.value;
		}).toArray();

		if (homeCats.length == 0)
			return '';
		else
			return '[[' + homeCats.join(']]' + nl + '[[') + ']]';
	}


	/*************************
	 ***  HOME-WIKI LINKS
	 ***
	 ***/


	/* PUBLIC */
	// called when the user clicks on the "Links to (language code)" portlet link
	function homeWikiLinks()
	{
		var namespaceIds = mw.config.get('wgNamespaceIds');
		var hWLs = $('.homeWikiLink');
		if (hWLs.length > 0) {
			if (hWLs.find('a').text().indexOf(homeWiki.lang + ':') != 0) //' ugly
				hWLs.remove(); // previously shown, but not for the current language
			else {
				hWLs.toggle(); // previously shown for the current language
				return;
			}
		}

		if (!homeWiki.lang) {
			setHomeWikiLang(prompt(msgs.enterTargetWiki, options.defaultWiki));
			if (!homeWiki.lang)
				return;
		}

		$($('#mw-content-text')[0] || $('body')).find('a')
		.not('#wikiTranslToolsPanel a').not(skin.catLinks + ' a').not('a.external')
		.filter('[href^="/wiki/"]').after(function () {
			var article = this.href.match(/wiki\/([^#?]+)/);

			if (!article)
				return null;
			article = article[1];

			// Check if the namespace is in the array of approved namespaces: NamespacesWithInterwikis
			var ns = article.match(/[^:]+(?=:)/);
			if (ns) {
				var nsNum = namespaceIds[ns[0].toLowerCase()];
				if (nsNum && ($.inArray(nsNum, NamespacesWithInterwikis) == -1))
					return null;
			}

			var span = $('<sup/>', {
				text: ' [[',
				'class': 'homeWikiLink reference'
			}).append($('<a/>', {
				text: homeWiki.lang + ':?',
				href: '#',
				data: {articleName: article},
				click: function () {
					findHomeWikiLink($(this));
					return false;
				}
			})).append(textNode(']]'));

			return span;
		});
	}


	// This function is called when the user clicks on one of the [[lang:?]] links
	function findHomeWikiLink($clickedLink)
	{
		var articleName = $clickedLink.data('articleName');
		$.ajax({
			url: '/w/api.php?action=query&prop=langlinks&titles=' + articleName
				+ '&lllang=' + homeWiki.lang + '&redirects&format=json',
			dataType: 'json',
			success: function (data) {
				interwikiReceived(data, $clickedLink);
			}
		});
	}


	// called when the HTML page
	//  (which is going to be searched for a link to the Home Wiki article) is received
	function interwikiReceived(data, $clickedLink)
	{
		var homeWikiPage = getHomewikiFromJson(data);
		if (!homeWikiPage) {
			$clickedLink.replaceWith($('<span/>', {
				text: homeWiki.lang,
				css: {textDecoration: 'line-through'}
			}));
			return;
		}

		var newLink = $('<a/>', {
			href: homeWiki.server + '/wiki/' + homeWikiPage,
			target: '_blank',
			text: homeWiki.lang + ':'
		});

		var input = $('<input type="text" style="vertical-align: bottom; direction: ltr;">').attr({
			value: homeWikiPage,
			size: Math.floor(homeWikiPage.length * 4/3),
			readonly: 'readonly'
		});

		var redirects = data && data.query && data.query.redirects;
		if (redirects)
			for (var i = 0; i < redirects.length; i++) {
				$clickedLink.before($('<span title="' + redirects[i].to + '">&gt;</span>'));
			}
		$clickedLink.after(input);
		$clickedLink.replaceWith(newLink);
		input.select();
	}


	/*************************
	 ***  Other Functions
	 ***
	 ***/


	function getHomewikiFromJson(data) {
		//{"query":{"pages":{"5152":{"pageid":5152,"ns":0,"title":"2007","langlinks":[{"lang":"bg","*":"2007"}]}}}}
		var pages = data && data.query && data.query.pages;
		if (!pages)
			return;

		var pg;
		for (var p in pages) {
			if (pages.hasOwnProperty(p))
				pg = pages[p];
		}

		return pg && pg.langlinks && pg.langlinks[0] && pg.langlinks[0]['*'];
	}


	function displayCode(str)
	{
		if ($.isFunction(options.hook))
			str = options.hook(str);
		var $codeBoxDiv = $('<div/>', {
			id: 'wikiTranslToolsCodeBox',
			css: {width: '80%', marginBottom: '1em', position: 'relative'}
		}).append($('<textarea/>', {
				//id: 'wikiTranslToolsCodeBox',
				text: str,
				css: {direction: 'ltr'},
				cols: options.taCols,
				rows: options.taRows
			}).select().focus().scrollTop(0),
			$('<div/>')
			.css({position: 'absolute', top: 0, right: '-4em', fontSize: 'small'})
			.append(
				$('<a/>', {
					href: '#',
					text: '[<]',
					click: function (e) {
						e.preventDefault();
						$codeBoxDiv.remove();
						showPanel();
					}
				}),
				$('<a/>', {
					href: options.helpUrl,
					target: '_blank',
					text: '[?]'
				}),
				$('<a/>', {
					href: '#',
					text: '[X]',
					click: function (e) {
						e.preventDefault();
						$codeBoxDiv.remove();
					}
				})
			)
		)
		.prependTo(mw.util.$content);
		
		$('html, body').scrollTop(0); // to element: ($(el).offset().top);
	}


	function addPortletLinks()
	{
		var ns = mw.config.get('wgCanonicalNamespace');
		var linksToLang = msgs.linksToLang.replace(/%targetWiki%/, '?');

		if (ns != 'Special' && ns != 'MediaWiki') {
			if (!$('#catTranslInterwLink')[0])
				addPortletLink('p-tb', 'javascript:wikiTranslTools.showPanel(); void(0);',
					msgs.trCatInterw,
					'catTranslInterwLink',
					msgs.trCatInterwTitle
				);
		}
		if (!$('#homeWikiLinksLink')[0])
			addPortletLink('p-tb', 'javascript:wikiTranslTools.homeWikiLinks(); void(0);',
				linksToLang,
				'homeWikiLinksLink',
				linksToLang
			);
	}


	/* PUBLIC */
	// call after updating window.wikiTranslToolsConfig
	function init(noPortletLinks)
	{
		//$('#catTranslInterwLink').remove();
		//$('#homeWikiLinksLink').remove();
		//$('#wikiTranslToolsPanel').remove();

		var wttC = window.wikiTranslToolsConfig;
		if (wttC) {
			$.extend(homeWiki, wttC.homeWiki || {});
			$.extend(true, thisWiki, wttC.thisWiki || {});
			$.extend(skin, wttC.skin || {});
			$.extend(msgs, wttC.msgs || {});
			$.extend(options, wttC.options || {});
			if (wttC.msgs && !wttC.msgs.linksToLang && wttC.msgs.linksTo) //' This will be removed soon...
				msgs.linksToLang = msgs.linksTo + ' %targetWiki%';
			if (homeWiki.translatedPageTemplate == 'Превод от') //' This will be removed soon...
				homeWiki.translatedPageTemplate = '{{Превод от|%sourceWiki%|%pageTitle%|%revisionId%}}';
		}

		homeWiki.translatedPageTemplate = homeWiki.translatedPageTemplate
		.replace(/%sourceWiki%/g, thisWiki.lang)
		.replace(/%pageTitle%/g, THIS_ARTICLE)
		.replace(/%revisionId%/g, mw.config.get('wgRevisionId'));

		if (homeWiki.lang && (!wttC || !wttC.homeWiki || !wttC.homeWiki.server))
			setHomeWikiLang(homeWiki.lang);

		if (!noPortletLinks && mw.config.get('wgAction') == 'view')
			$(addPortletLinks);
	}


	function setHomeWikiLang(homeWikiLangCode)
	{
		homeWikiLangCode = $.trim(homeWikiLangCode);
		if (!homeWikiLangCode || homeWikiLangCode == homeWiki.lang)
			return;
		homeWiki.lang = homeWikiLangCode;
		homeWiki.server = mw.config.get('wgServer').replace(thisWiki.lang, homeWikiLangCode);
		var newLinksToLangPortletText = msgs.linksToLang.replace(/%targetWiki%/, homeWiki.lang);
		$('#homeWikiLinksLink a').attr('title', newLinksToLangPortletText).text(newLinksToLangPortletText);
		var $panel = $('#wikiTranslToolsPanel');
		if ($panel[0]) {
			$panel.find('.wtt_targetWikiLangLink').text(msgs.targetWiki.replace(/%targetWiki%/, homeWiki.lang));
			$panel.find('.wtt_catBrowser').replaceWith(createTheCategoryBrowser());
		}
	}


	init();


	/* All public member functions */
	return {
		init:              init,
		catsTranslInterw:  showPanel, // To be removed soon...
		showPanel:         showPanel,
		homeWikiLinks:     homeWikiLinks
	};
}());