Clanker / Kingdom CL

// ==UserScript==
// @name         Kingdom CL
// @version      1.02
// @description  Some tools and improvements for the Kingdom game.
// @author       Clanker
// @copyright    2019, Clanker
// @license		 MIT
// @grant        GM_getValue
// @grant        GM_setValue
// @supportURL	 http://kingdom.muxxu.com/tid/forum
// @match        http://kingdom.muxxu.com/*
// @require	     http://code.jquery.com/jquery-1.7.2.min.js
// @require	     http://code.jquery.com/ui/1.11.4/jquery-ui.min.js
// ==/UserScript==

/*
	Extension Kingdom CL ou KCL pour le jeu Kingdom, appartenant à Motion Twin

	Cette extension a été écrite par un joueur qui n'a aucune relation avec les équipes de développement de Motion Twin.
	En dehors des logos de l'extension, les images et styles utilisés par ce script sont propriétés de Motion Twin.
	2019. Joueur Clanker TID 4490783. Tous droits réservés.

	https://openuserjs.org/scripts/Clanker/Kingdom_CL
*/

if (window.top != window.self) return; // Don't run on frames or iframes, and avoid loading jQuery twice
$("head").append(
    '<link '
  + 'href="https://code.jquery.com/ui/1.11.4/themes/eggplant/jquery-ui.css" '
  + 'rel="stylesheet" type="text/css">'
);

// Global variables
var KCL_Version = "1.02";
const pages = {
  Management: "Management",
  Map: "Map",
  City: "City",
  Help: "Help",
  Forum: "Forum",
  Battle: "Battle",
  UnitTransfer: "UnitTransfer",
  Ranking: "Ranking",
  Pantheon: "Pantheon",
  User: "User",
  GeneralCreation: "GeneralCreation"
};
var currentPage;
var baseUrl = "http://kingdom.muxxu.com/";
var unitTypes = ["sold", "arch", "cav", "pal", "piq", "chev", "caa", "bal", "cat"];
var battleSimUrl = "http://citadelle.byethost22.com/index.php"; // POST : http://kingdom.muxxu.com/tid/forum#!view/481|thread/45213376?p=1
var CL_Functions = unsafeWindow.CL_Functions = { CL_AddUnitButtons, CL_AddAll, CL_RemoveAll, switchToEcoSim, Terre, commerce, aggregate, asHtml, getremaindcompt, plus, moins, initEcoSim, CL_SwitchToInfoPage };
// ! DEV Note : unsafeWindow functions working in Tampermonkey but not in Greasemonkey. So all events like click should not but defined as inline attributes.
// ! GM is blocking (or not offering easy way to) call page functions from GM script (e.g. tooltips) or the opposite (inline attributes), so people are switching to TM.
// https://github.com/greasemonkey/greasemonkey/issues/2700
var descMovePlan = "Si le trajet proposé par défaut pour déplacer un général ne vous convient pas, vous pouvez planifier un trajet point par point. <br />" +
				   "Attention, chaque point devra être accessible depuis le précédent, sans interruption. " +
				   "Sinon le déplacement ne sera pas lancé.<br />";

$(document).ready(function() {
	console.log("Kingdom CL loading ...");

	{ /* Detect current page */
		var currentUrl = window.location.href;
		if(currentUrl.includes("/user/")) currentPage = pages.User;
		else if($('.userh1_intabl').length > 0) currentPage = pages.Management;
		else if($('table.city').length > 0) currentPage = pages.City;
		else if($('.punits').length > 0) currentPage = pages.UnitTransfer;
		else if(currentUrl.includes("/map?")) currentPage = pages.Map;
		else if(currentUrl.includes("/help")) currentPage = pages.Help;
		else if(currentUrl.includes("/tid/forum")) currentPage = pages.Forum;
		else if(currentUrl.includes("/battle/")) currentPage = pages.Battle;
		else if(currentUrl.includes("/ranks")) currentPage = pages.Ranking;
		else if(currentUrl.includes("/pantheon")) currentPage = pages.Pantheon;
	}

	{ // Global styles
		$('body').prepend('<style>'
			+ '#historyFilters { float:right;margin-right:64px;  } '
			+ '#historyFilters > h3 { display: inline; position:relative; top: -6px; } '
			+ '#historyFilters > img { cursor: pointer; margin-left: 2px; max-width: 16px; padding: 2px; border-radius: 4px; } '
			+ '#historyFilters > img:hover { background: rgba(0,0,0,0.1); } '
			+ '#historyFilters > img.selected { background: rgba(0,0,0,0.2); } '
			+ '.log ul > li:hover { background: rgba(255,255,255,0.15); } '
			+ '#logTextArea { width: 350px; margin: auto; margin-top: -24px; } '
			+ '#logTextFilter { padding-left: 8px; } '
			+ '#logTextFilterBtn { display: inline-block; } '
			+ '#mapInfo { cursor:pointer; } '
			+ '#generals .actions { display: none; margin: 4px 16px; } '
			+ '#generals .actions > img { cursor: pointer; margin-right: 2px; } '
			+ '#MoveList { width: 253px; margin-left: 20px; margin-bottom: 10px; }  '
			+ '#btnConfirmMovePrep { display:inline-block; margin: 12px 0px 0px 32px; white-space: nowrap; height: 32px; line-height: 32px; cursor:pointer;  } '
			+ '#btnConfirmMovePrep:hover { background: rgba(255,255,255,0.18);  } '
			+ '#btnConfirmMovePrep > img { vertical-align:middle; } '
			+ '#btnConfirmMovePrep > span { vertical-align:middle; display:inline-block; } '
			+ '#btnCancelMovePrep { display:inline-block; margin-top: 12px; margin-left: 16px;  } '
			+ '#MoveList > [locationId] { border-top: 1px groove #bbb; padding: 2px 0px 2px 0px; } '
			+ '#MoveList > [locationId].last { font-weight: bold; } '
			+ "img.KCL { width: 32px; height: 16px; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAQCAMAAABA3o1rAAAABGdBTUEAALGPC/xhBQAAAwBQTFRFa0Mrc0wxfFU4hF4+jmhGlnFMn3tTxHsjp4RZr4xftpRlvpxrxaNwzKt10rF62bh/4MCF6suNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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o4WZccb6gNRZcrMF4zgRR4oTbAMf7Ze/TqUIEgyYKQAdKi+E2csKRWuwSd4vwG2zePMLX3rV3xlyRzysTsf3pybXjmNeLll6/WTuRtFjArmBoTXhcPH+9TcCd0KB43hUpZE1IvEBYmEbMAn9NzXH9GGx7422pxSMwUB6r1Xnp544HP96xN2TGcibYHmNh1wEvqOD2lhQfm5HtSvwApP4k9IKPuO7mjANx1JdKUC5BCE2WYhAnOKwB6ybakTR7LavFqoFPN9c1f+Ts0b/UBjNIji+j3cfdtA0/lvA8u4bcqu//HAzLD4rGsRWHkogIL8j3AwIjskqJuQH2ANdklVbqA22oDj8ep1AnsOHeY7Us3tSyo0OhqsS/x8+O7E454Tm++dObaJNU90Nb5t2VCvmtG6gUuHsjgcqIXkLl1HMDAf1Wt/gNfcewlI9HT7gAAAABJRU5ErkJggg=='); } "
			+ ".KCLTransfer { display:block; width:24px !important; height:16px !important; border:1px solid transparent; padding:3px 0px 0px 1px; font-size:11px; color:white; text-decoration:none; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABsAAAAUCAMAAABLXLayAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAMAUExURZFbM7hpLrlpL7hqLrlqL/9tAP9vAP9xAP9zAP91AP92AP95AP96AP98AP9+AP+AAP+CAP+EAP+GAP+IAP+KAP+NAP+PAP+RAP+SAP+VAP+WAP+YAP+aAP+cAP+gAP+iAP+kAP+pAP+vAP+zAP+1AP+3AP+4AP+9AP+/AP/AAP/CAP/EAP/GAP/IAP/KAP/MAP/OAP/QAP/TAP/UAP/XAP/YAP/aAP/cAP/eAP/gAP/jAP/nAP/pAP/qAP/sAP/vAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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img.KCLPlanMove { width: 32px; height: 32px; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAFBhaW50Lk5FVCB2My41LjVJivzgAAAGTElEQVRIS7WWeVBTVxTGM+NMa1tHLdWCWLSAERgoVnFBHKvIuEsBYxGpMErrSl0LbhQRRCpWlE2IEShGQUiBSkABQYkEEFEsi1QWM1SIURalU7cQsPZ7nuczi/Y/33xzc9/Ny/c799xzXy7veKjAz2XYOxLMefi4Vez1qPm7WqngxllBTc5SbV3L8qiWuL9N+JYeqMpwKz/lCl1KWkhqLWT6MGcAcH/Re6jn8tfdpUu6ShZpq7NoAXSvYB7armK3zsJ5hsK3yvy5kCLb5VaGc514dqVwZn3+N2hZAKKA1687HZMDpxkqZYfjrhXT7cfNHjzI2Z6/Mtpf/zEb/hKfJQLuVrR9SqSvXemhKdFrJrAAZAYAGPU3xQ80s+pvTtS0nNC0Jv/8YyCsi2TyZwOP94clWpovjwvdp7mT3deWoWlL1yjEAPBGH4Py0k4zP2yKj/C2LftlEloWgOkgOQBw7gMtx/tvp+DHcDF6f+Fl+bXn//bfU7e29TTFSPeCdzohtk95rq9dChImx7Np543cxrOqX+Ynu10Wv9/TGgC0LOBmgScASBE7A3JHdAizXQo7xK54WG82aikn5Ep9r1R9t0QqOuBk5cCz1zAAfhVDMg6e7+hWdVQL0Fjo2S1zZQHa7spzjxXZAPT1P7tUc17V00HuPgEemJa666q6s4LJj1U9I+NgFoB0jTq4akVYqMDKANCcqO2OGCsKJPCSytPK6y6SZiyavCtuHTOtB3V/K6uZ/CB8WANgUcSz7R5udcRp8mpx0OIQj/GvAahRAJhVVYg591Oik4h3lCOTHFNLVw4ApKmRi6pJBjzy81OUipkBUvQSMMJeHOzGR4reBGhNxqoi70juH7Ic+JpMqhluJRxqHoa4OI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cJZirH3taBDu4uIodCB4wdfrwzM+vBACoEAlG8a9BvxZIqjM8MgKckj3t2G0np+x1gLK3mAOkQuE/tkfLKDcreNopDjEDiIAJ9xiExTHOKR6vSpTnFLhjuiwA3cvsgyY+zlC2DTjMxQyo+mv2umjMQht+cpsu/NYTngeptyFb6H0783ZGbzb43uo4D9qgJo6QF7dDgAAAABJRU5ErkJggg=='); } "
			+ ".KCLTransfer:hover { border-color: white; } "
			+ " img.KCLTransferDown { width: 34px; height: 34px; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAWlSURBVFhHxZd/TFZVGMdva1OkmjpXxtIFFD8MCpVEMyuNWZiZ0lvMrbW5fpgk1cwBo9aM9YdlVmpuxowfQrEX9oKUNEkgjRiDnC1YRiD42mZrWVtr9Ue8sD093+f8uPfC+8JfzT++O889P57nc55z7rnnOhXlAXomd+5VEWI7MAbbt9LfQ8/S958H6LuWAJ1rfnyKzoby6dvGLTMK/Uzf3uBm6q7bJPrq4w1WF9rUM2ILAILTn/voj67H6PfTj9KVzo0+/XYqT6ntIfr1pBLs6YQ+l1vXi0abcmkwuI76a9dS70draKD1Seo+cp8LAGIEqi5dRZXFK/83Hd2dQ+88nUmn962gA89nuQBIOwCqSlbR+E+HaWLI1fjQEYqMVFHkUh2XtTR2sZ7Gwg2sJhq7FHKFZ9Rze2TkmBozUinjrS/2vfepDOp6d7mUFgApQeoB4AvODsTJhSoWSo9Qr9sikA4IW/XhkuugieEK6/OtgnQBQGkBfjhZIABYApuB4aPWMZyI7ZEBUIHNswmqQKQt/KnUAQK+Ebj3g0kA59sK6MqZTS4AdxanEkhJnIlTpNekGH0qaZszS2SebZt5Dtcre6iC9uSn0rnDd1N5IC0GAK+ZCqpT7HXEpZq9q93zF/aFcjdQRf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O0f9udcluFcG+PJvxYQOiLEnXoj/cbtxxsMqwzBBvCzodQhyXAJvQB/NgRoJ5gPoVez6b6nUuUdqQIKdRcmBRVLUXJohOvpohwwrXvUcKtB4KNehw+eP+h9oPZVLPV8xriRxHBMRvMpOwRRYt0Fd27SN7ZaEIbhH6YmVcmCyYTqEM/swdsBq7u73mA/gOVOdOmBHWquAAAAABJRU5ErkJggg=='); } "
			+ " img.KCLTransferUp { width: 34px; height: 34px; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAAABl0RVh0U29mdHdhcmUAUGFpbnQuTkVUIHYzLjUuNUmK/OAAAAXOSURBVFhHxZd9TJdVFMeZujZm6Qrb1FBehMAB6bJIMRUyGmhE9DNiS5uTZBgvaolmrTnWymUvZrAZQ14t+sUQKNhkAcIca5SzkmUG8mKbq0Vt1NpY/GQ7ne+59z4v8AP+av7x3T3Pveee87nnuc/z3CegrNhDe7Yuvi1C7gAY19qz6J/+bPrhSw991+yhy43PTNOlhgz6tv7pOQU/49vrTaees2miC2dSLV1vU9fILQBITmMn6M+LT9EfXU/SaOd2l37/KkWp7Qn67bwS7NkEn5utyaKhc1vpmjeJrtQmUu/Hj1Jf67PUc3qTDQBiJKo6sp4qih7531T+Sjy9syuWuk48TB/uXWMDoOwAqDy8nm79XEqT/bZu9Z8m32Al+W6c5baWJobraGLkc9Y5mrjRYAvX6Odx32CNmjNYIfOtWBz7+PMxdPHdB6W1AFASlB4AruQcQIJcr2ShdQj9eswH6YSwlQ+33AdNDpRZMd/MjBYAtBbAj+czBQC3wKrAQLkVGEHEdsgAqMTm2iRVIDI28qn0AQKxkbj35BSAq22ZNNqdZgOwswSVREoSTIKivKbE8NGr5dZcW2PmeqRO2f1ldCzjfrpc+hAVe6JmAOB7ppKqFRoAKzAnm58a8D0L7VSNwdf4SaUAiIpwJXxsv5EeKQAAcQHgEQ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g5KRnh2iHeRzIPe4rjmJgAQAVy1i21AfAL9U31Y/Te7jg5rUI4t/sTfiwg+KJFH/zxfOOUg02G+wzBhrDzIfThFmATugB+6vDQ194Manh9HdXlrVbKjRRSqHFfmF8154eLWl6OFOEN135MCaceCDb68fLB8w+1n1pH1VmOxxA/ikiO1WAlR7cpWpQrf2OwPLP+hDEIfliZU6YKphLog5/ZA1YFbu/vuYf+A6R48fag3xa8AAAAAElFTkSuQmCC'); } "
			+ '</style> ');
	}

	/* Main links */
	var mainMenu = $('.mxmainmenu').children('ul:first');
	if (mainMenu.length > 0){
		$(mainMenu).append('<li><a id="btnEcoSim" href="javascript:;"><img src="/img/icons/res_gold.png" /> Eco Sim</a></li>');
		$('#btnEcoSim').click(function() { switchToEcoSim(); });
		//$(mainMenu).append('<li><a id="btnBattleSim" target="__blank" href="'+battleSimUrl+'"><img src="http://kingdom.muxxu.com/img/icons/gold_army.gif" /> Combat Sim</a></li>');
		$(mainMenu).append('<li><a id="btnKCLInfo" href="javascript:;"><img class="KCLL" /> Informations</a></li>');
		$('#btnKCLInfo').click(function() { CL_SwitchToInfoPage(); });

		var links = $(mainMenu).children('li');
		links.css('marginRight', '15px');
		links.css('marginLeft', '20px');
		links.css('paddingRight', '25px');
		links.css('paddingLeft', '8px');

		CL_InitTooltip($('#btnEcoSim'), "Simulateur de commerce", "Accéder au simulateur d'évolution du commerce en fonction de la garnison (local).");
		//CL_InitTooltip($('#btnBattleSim'), "Simulateur de bataille", "Accéder au simulateur de bataille conçu par 'Reddit' (site externe).");
		CL_InitTooltip($('#btnKCLInfo'), "Extension", "Afficher la description et les informations de l\'extension KCL.");
	}

	/* Management page */
	if(currentPage == pages.Management){
		var population = 0;
		var populationExp2 = 0;

		// Buttons custom colors
		// $('a[href$="/ranks"]').css('filter', 'hue-rotate(120deg)');
		$('a[href^="/pantheon"]').css('filter', 'hue-rotate(335deg)');

		// Fix realm "doubling" lines layout bug
		$('#kingdom').find('table:first').find('tr:not(.first)').each( function () { $(this).children(':eq(2)').css('whiteSpace', 'noWrap'); } );

		{ // F titles
			var convertedLinks = CL_ConvertAllFTitles();
			for(var i = 0; i<convertedLinks.length; i++){
				var link = convertedLinks[i];
				var linkParent = $(link).parent();
				if($(linkParent).is('li')){
					var icon = $(linkParent).children('img:first');
					if($(icon).is('[src="/img/icons/l_up.png"]')){ // Proclamations nouveaux titres
						// TO BE tested
						/*var titleElem = $(linkParent).children('b:last');
						var title = $(titleElem).text();
						var newTitle = CL_ConvertTitleToF(title);
						$(titleElem).html(newTitle);
						$(titleElem).prev()[0].nextSibling.data = ' été proclamée ';/**/
					} else if($(icon).is('[src="/img/icons/l_conquest.png"]')
								|| $(icon).is('[src="/img/icons/l_death.png"]')){ // Conquêtes et morts
						$(linkParent).contents().filter(function() {
							return this.nodeType == 3
						}).each(function(){
							this.textContent = this.textContent.replace('Votre vassal le ','Votre vassale la ');
							this.textContent = this.textContent.replace('Votre vassal ','Votre vassale ');
							this.textContent = this.textContent.replace(' est mort ',' est morte ');
						});
					} else if($(icon).is('[src="/img/icons/l_new.png"]')){ // Nouveaux occupants
						$(linkParent).contents().filter(function() {
							return this.nodeType == 3
						}).each(function(){
							this.textContent = this.textContent.replace(' : le ',' : la ');
						});
					} else if($(icon).is('[src="/img/icons/l_pass.png"]')
								|| $(icon).is('[src="/img/icons/l_revolt.png"]')
								|| $(icon).is('[src="/img/icons/l_enemy.png"]')
								|| $(icon).is('[src="/img/icons/l_neutral.png"]')
								|| $(icon).is('[src="/img/icons/l_friend.png"]')){ // Diplomatie (TODO à compléter)
						$(linkParent).contents().filter(function() {
							return this.nodeType == 3
						}).each(function(){
							this.textContent = this.textContent.replace('Le ','La ');
							this.textContent = this.textContent.replace(' du ',' de la ');
						});
					} else if($(icon).is('[src="/img/icons/l_battle.png"]')){ // Batailles
						$(linkParent).contents().filter(function() {
							return this.nodeType == 3
						}).each(function(){
							this.textContent = this.textContent.replace(' a attaqué le ',' a attaqué la ');
						});
					} else if($(icon).is('[src="/img/icons/l_gottax.png"]')){ // Taxes
						$(linkParent).contents().filter(function() {
							return this.nodeType == 3
						}).each(function(){
							this.textContent = this.textContent.replace(' auprès de votre vassal le ',' auprès de votre vassale la ');
						});
					}
				} else if($(linkParent).is('td')){
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						this.textContent = this.textContent.replace('Capitale du ','Capitale de la '); // Kingdom tab
						this.textContent = this.textContent.replace('Le ','La '); // Diplomacy tab
					});
				}
			}
		}

		{ // Collect action returns to vassals tab
			$('#vassals').find('table:first').find('a[href^="/diplo/"]').each(function(){ // On the collect link
				$(this).attr('href', $(this).attr('href') + '&tab=vassals');
			});

			$('#notification a.button[href="/"]').each(function(){ // Add redirection in the dialog following the action
				var tab = qs("tab");
				if(tab !== null && tab == "vassals")
					$(this).attr('href', '/?tab=vassals');
			});
		}

		{ // Map info
			var mapLevel = 1;
			var mapTitle = '';
			var mapId = parseInt($('.buttons > a[href^="/map/"]').attr('href').split('/')[2]);
			for(var mi = 0; mi < mapList.length; mi++){
				if(mapList[mi].id == mapId){
					mapLevel = mapList[mi].level;
					mapTitle = mapList[mi].title;
				}
			}
			var mapLevelTitle = CL_GetMapLevelTitle(mapLevel);
			var mapLevelImg = CL_GetMapLevelImage(mapLevel);
			var buttonsArea = $('td.right > div.buttons');
			buttonsArea.children('a').css('float','none');
			buttonsArea.children('a').css('display','inline-block');
			if(mapTitle.length > 0)
				buttonsArea.append('<div id="mapInfo" style="margin-top: 12px;text-align:center;">Carte '
					+ mapTitle +' de niveau '+ mapLevelTitle +' <img src="'+mapLevelImg+'" /></div>');
			else
				buttonsArea.append('<div id="mapInfo" style="margin-top: 12px;text-align:center;">Carte '+mapLevelTitle+' inconnue</div>');
			$('#mapInfo').click(function() { window.open('https://twinoid.com/g/ipk#niveau-de-carte-choix'); });
			CL_InitTooltip($('#mapInfo'), "Cartes", "Cliquez pour accéder à la liste des cartes compilée sur IPK.");
		}

		{ // Food status & tooltip update
			var foodDiffArea = $('.homeres').find('.homegest:eq(0)');
			var foodDiffElem = $(foodDiffArea).find('p.number:last');
			var foodDiff = parseInt($(foodDiffElem).text().replace('/tour', ''));
			population = foodDiff * -1;
			populationExp2 = population * population;
			var foodStockElem = $('.homeres:first').find('.homegest').find('img[src="/img/icons/res_food.png"]').parent();
			var foodStock = parseInt(foodStockElem.find('.n:first').text());
			if(foodDiff<0){
				var tipElem = $(foodDiffElem).parent().children('img:first');
				var tipCode = $(tipElem).attr('onmouseover');
				var turnsLeft = parseInt(-1 * foodStock / foodDiff);
				tipCode = tipCode.replace('Capitale.','capitale.<br /><img class="KCL" /> Il vous reste ' + turnsLeft + ' tours de réserve. ');
				$(tipElem).attr('onmouseover', tipCode);
			}
			console.log('population: '+population);
			console.log('food: '+foodStock);
			if(foodStock>populationExp2 && population<100){
				CL_ActivateFoodAbundance(foodStockElem, populationExp2);
			}
		}

		{ // Economy status & tooltip update
			var ecoDiffArea = $('.homeres').find('.homegest:eq(1)');
			var ecoDiffElem = $(ecoDiffArea).find('p.number:last');
			var ecoDiff = parseInt($(ecoDiffElem).text().replace('/tour', ''));
			var totalArmyCost = parseInt($(ecoDiffArea).find('ul:first').children('li:first').children('span').text().replace('/tour','').replace('-',''));
			var ecoStockElem = $('.homeres:first').find('.homegest').find('img[src="/img/icons/res_gold.png"]').parent();
			var ecoStock = parseInt(ecoStockElem.find('.n:first').text());
			if(ecoDiff<0){
				var tipElem = $(ecoDiffElem).parent().children('img:first');
				var tipCode = $(tipElem).attr('onmouseover');
				var turnsLeft = parseInt(-1 * ecoStock / ecoDiff);
				tipCode = tipCode.replace('capitale.','capitale. <br /><img class="KCL" /> Il vous reste ' + turnsLeft + ' tours de réserve. ');
				$(tipElem).attr('onmouseover', tipCode);
			}
			console.log('gold: '+ecoStock);
			if(ecoStock>populationExp2/2){
				CL_ActivateGoldAge(ecoStockElem, populationExp2/2);
			}
		}

		{ // Initializations
			var infoList = $('table.infos').find('tr:first').children('td:eq(1)').find('ul:first');
			$(infoList).css('margin-top', '-16px');
			var gloire = parseInt($(infoList).children('li:eq(3)').children('b:last').text());
			var capitalId = parseInt($('.mxmainmenu > ul > li > a > img[src="/img/menu/map.gif"]').parent().attr('href').split('=')[1]);
			var titleName = $(infoList).children('li:first').children('b:last').text();
		}

		{ // Main title gendering
			CL_ConvertPageTitleToF(infoList);
			/*var titleName = $(infoList).children('li:first').children('b:last').text();
			var tryCount = 0;
			setTimeout(function(){
				UpdateTitleGender();
			}, 100);
			function UpdateTitleGender(){
				tryCount++;
				if(tryCount > 50) return;
				if($('.tid_age:first').length == 0) setTimeout(function(){ UpdateTitleGender(); }, 100);
				var isF = $('.tid_age:first').children('img:first').attr('src') == '//data.twinoid.com/img/icons/female.png';
				if(isF) $(infoList).children('li:first').children('b:last').html(CL_ConvertTitleToF(titleName));
			}/**/
		}

		{ // Glory by locations, cities, vassals
			var gloryElem = $(infoList).find('img[src="/img/icons/l_up.png"]:first').parent().parent();
			var gloryHelpElem = $(gloryElem).children('img:first');
			var cityCount = 0, marketCount = 0;
			$('#kingdom .tablevb > tbody > tr').each(function(){
				var lastCell = $(this).children('td:eq(2)');
				if(lastCell.length > 0){
					if(lastCell.children('span:first').text()=="--") cityCount++;
					else marketCount++;
				}
			});
			var vassalsGlory = gloire - cityCount - marketCount;
			var gloryCode = $(gloryHelpElem).attr('onmouseover');
			var gloryInfo = "";
			gloryInfo += "<br />"+cityCount+" ville"+(cityCount>1?"s":"");
			gloryInfo += "<br />"+marketCount+" zone"+(marketCount>1?"s":"")+" de commerce";
			gloryInfo += "<br />"+vassalsGlory+" territoire"+(vassalsGlory>1?"s":"")+" de vos vassaux";
			gloryCode = gloryCode.replace('aux.<','aux.<br /><img class="KCL" /> Votre royaume s\\\'étend sur : '+gloryInfo+'<');
			$(gloryHelpElem).attr('onmouseover', gloryCode);
		}

		{ // Economy min/max/average
			var economyElem = $(infoList).find('img[src="/img/icons/small/res_gold.gif"]:first').parent().parent();
			var economyHelpElem = $(economyElem).children('img:first');
			var maxEco = 0, minEco = 10000, totalEco = 0, countEco = 0;
			$('#kingdom .tablevb > tbody > tr').each(function(){
				var ecoCell = $(this).children('td:eq(2)');
				if(ecoCell.length > 0){
					var cellContent = ecoCell.children('span:first').text();
					if(cellContent!="--"){
						var ecoValue = parseInt(cellContent);
						if(ecoValue>maxEco)maxEco=ecoValue;
						if(ecoValue<minEco)minEco=ecoValue;
						totalEco+=ecoValue;
						countEco++;
					}
				}
			});
			var averageEco = countEco == 0 ? 0 : parseInt(totalEco / countEco);
			var economyCode = $(economyHelpElem).attr('onmouseover');
			var ecoInfo = "";
			ecoInfo += "<br />Minimum: "+minEco+" <img src=\\\'/img/icons/small/res_gold.gif\\\' />";
			ecoInfo += "<br />Moyenne: "+averageEco+" <img src=\\\'/img/icons/small/res_gold.gif\\\' />";
			ecoInfo += "<br />Maximum: "+maxEco+" <img src=\\\'/img/icons/small/res_gold.gif\\\' />";
			economyCode = economyCode.replace('tion.<','tion.<br /><img class="KCL" /> Zones de commerce :'+ecoInfo+' <');
			$(economyHelpElem).attr('onmouseover', economyCode);
		}

		{ // Stat : Army size
			var keepersUnitCount = 0;
			$('#kingdom .tablevb').find('tr:gt(0)').each(function(){
				keepersUnitCount += parseInt($(this).children('td:last').text());
			});
			var armiesUnitCount = 0;
			$('#generals').find('ul.ismall').children('li').each(function(){
				armiesUnitCount += parseInt($(this).find('.number:first').text());
			});
			var totalUnits = keepersUnitCount + armiesUnitCount;

			$(infoList).append('<li><img src="/img/help.gif" id="armyHelp" class="help" /> <span class="dt">Armée : </span><b><strong>' +
						totalUnits + '</strong> <img src="/img/icons/small/unit_sold.gif"></b></li>');
			// Show unit count by type and usage
			function generateArmyHtml(countArray){
				var result = "<div style='height: 32px;'><ul class='ismall'>"; // Height is to force the div to take space and represent a line.
				for(var ai = 0; ai < unitTypes.length; ai++){
					if(countArray[ai]>0 || ai == 0)
						result += "<li><div><img src='/img/icons/small/unit_"+unitTypes[ai]+".gif' /><span class='number'>"+countArray[ai]+"</span></div></li>";
				}
				return result + "</ul></div> ";
			}
			var armyComposition = "";
			var gArmyList = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
			$('#generals').find('ul.ismall').children('li').each(function(){
				CL_GetListItemSoldiers(this, gArmyList);
			});
			armyComposition += "<h3 style='margin-top: 4px;'>Généraux - "+sumArray(gArmyList)+"</h3>";
			armyComposition += generateArmyHtml(gArmyList);

			var keepersList = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
			$('#kingdom .tablevb > tbody > tr').each(function(){
				CL_GetRowKeepers(this, keepersList);
			});
			armyComposition += "<h3 style='margin-top: 8px;'>Garnisons - "+sumArray(keepersList)+"</h3>";
			armyComposition += generateArmyHtml(keepersList);

			var totalArmyList = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
			for(var ti = 0; ti < unitTypes.length; ti++){ totalArmyList[ti] = gArmyList[ti] + keepersList[ti]; }
			armyComposition += "<h3 style='margin-top: 8px;'>Toute l'armée - "+sumArray(totalArmyList)+"</h3>";
			armyComposition += generateArmyHtml(totalArmyList);
			armyComposition += "<br />";

			CL_InitTooltip($('#armyHelp'), "Composition de l'armée", armyComposition);
		}

		{ // Stat : Réputation
			var reputation = 0;
			$('#generals').find('.blocks_top').children('.blocks_bg').children('.blocks_bottom').each(function(){
				$(this).children('p:first').children('strong').each(function(){
					reputation += parseInt($(this).text());
				});
			});
			$(infoList).append('<li><img src="/img/help.gif" id="repHelp" class="help" /> <span class="dt">Réputation : </span><b><strong>' +
						reputation + '</strong> <img src="/img/icons/l_rep.png"></b></li>');
			CL_InitTooltip($('#repHelp'), "Réputation", "Votre réputation grandit quand vos généraux remportent des batailles. Chaque point de réputation gagné par un général lui permet de réduire le coût en or des unités qui l'accompagnent.");
		}

		{ // Stat : Score
			var titre = CL_GetTitleLevel(titleName);
			var score_Titre = 100 * titre * mapLevel;
			var score_Gloire = gloire * 2;
			var score_Army = parseInt(totalUnits / 3);
			var score_Rep = reputation * 3;
			var score = score_Titre + score_Gloire + score_Army + score_Rep;
			$(infoList).append('<li><img src="/img/help.gif" id="scoreHelp" class="help" /> <span class="dt">Score : </span><b><strong>' +
						score + '</strong> <img src="/img/icons/capitale.png"></b></li>');
			CL_InitTooltip($('#scoreHelp'), "Calcul du score", "<p>Votre score déterminera la place que vous occuperez dans le panthéon.</p>"
				+ "<p><small>= 100 * titre * carte + 2 * gloire + armée / 3 + rép * 3</small></p>"
				+ "<p> = 100 * "+titre+" * "+mapLevel+" + 2 * "+gloire+" + "+totalUnits+" / 3 + "+reputation+" * 3</p>"
				+ "<p>Votre titre vous rapporte <strong>"+score_Titre+"</strong> points.</p>"
				+ "<p>Votre gloire vous rapporte <strong>"+score_Gloire+"</strong> points.</p>"
				+ "<p>Votre armée vous rapporte <strong>"+score_Army+"</strong> points.</p>"
				+ "<p>Votre réputation vous rapporte <strong>"+score_Rep+"</strong> points.</p>");

			$(infoList).children('li').css('minHeight', '21px');
		}

		{ // Generals actions
			$('#generals .blocks_top').each(function(){
				var contentBlock = $(this).find('.blocks_bottom:first');
				var generalId = parseInt($(this).find('a:first').attr('href').split('=')[1]);
				var statusText = $(this).find('div.p:first').text();
				var isMoving = statusText.indexOf('Se déplace entre') > 0;
				var isWaiting = !isMoving && statusText.indexOf('En attente à') > 0;
				var isFortified = !isMoving && !isWaiting && statusText.indexOf('Fortifié à') > 0;
				var isFighting = !isMoving && !isWaiting && !isFortified;
				var troopsList = $(this).find('ul.ismall:first');

				$(contentBlock).append('<div class="actions"></div>');
				var actionsList = $(contentBlock).children('.actions:first');

				var ownedLocation = false;
				var localEco = 0;
				var ressources = "";
				var localKeepers = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
				var localKeepersHtml = "";
				var gArmy = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ];
				if(isWaiting || isFortified){
					var gLocationLink = $(contentBlock).find('a:first');
					var gLocationId = parseInt(gLocationLink.attr('href').split('=')[1]);
					CL_GetListSoldiers($(this).find('ul.ismall:first'), gArmy);
					$('#kingdom .tablevb > tbody > tr:gt(0)').each(function(){
						var cityId = parseInt($(this).children('td:eq(0)').find('a:first').attr('href').split('=')[1]);
						var ecoCell = $(this).children('td:eq(2)');
						var stCell = $(this).children('td:eq(1)');
						if(gLocationId == cityId){
							ownedLocation = true;
							// Local keepers
							CL_GetRowKeepers(this, localKeepers);
							localKeepersHtml = CL_GetRowKeepersHtml(this);
							// Show local information on tooltip
							var ecoText = ecoCell.children('span:first').text();
							localEco = parseInt(ecoText);
							if(ecoText!=="--") CL_InitTooltip($(gLocationLink), "Informations locales",
								"Commerce : " + ecoText + " <img src='/img/icons/small/res_gold.gif' /><br />"
								+ "Garnison : " + $(this).children('td:eq(4)').text() + " <img src='/img/icons/small/unit_sold.gif' />"
								+ "<br />"+localKeepersHtml);
							else CL_InitTooltip($(gLocationLink), "Informations locales", "Ville<br />"+localKeepersHtml);
							// Resources to harvest
							if(stCell.children('.sres').length>0) ressources = stCell.html();
						}
					});
				}

				if(isWaiting && ownedLocation){ // Unit transfer, fortification
					actionsList.append('<img class="generalAction_Transfer" src="/img/icons/a_transfer.png" />');
					CL_InitTooltip($(actionsList).children('.generalAction_Transfer:first').click(function(){
						document.location = '/general/'+generalId+'/units';
					}), "Transférer des unités", "Accéder à l'écran de transfert d'unités.");

					function CL_PostUnits(unitsArray){
						var unitsForm = new Object();
						for(var i=0;i<unitsArray.length;i++){
							unitsForm[unitTypes[i]] = unitsArray[i];
						}
						$.post("/general/"+generalId+"/units?submit=1", unitsForm)
							.done(function(data){
								document.location = document.location;
							});
					}
					// Transfer actions
					actionsList.append('<img class="generalAction_TransferToGen KCLTransferUp" />');
					CL_InitTooltip($(actionsList).children('.generalAction_TransferToGen:first').click(function(){
						var requiredSoldiers = 1;
						if(localEco > 2) requiredSoldiers = Math.round(localEco / 2);
						var totalCurrentKeepers = sumArray(localKeepers);
						var soldiersLeft = totalCurrentKeepers - requiredSoldiers;
						for(var i=localKeepers.length-1;i>=0;i--){
							var currentKeepers = localKeepers[i];
							if(currentKeepers < soldiersLeft) { localKeepers[i] = 0; soldiersLeft -= currentKeepers; }
							else if(currentKeepers == soldiersLeft) { localKeepers[i] = 0; soldiersLeft = 0; break; }
							else /*currentKeepers > soldiersLeft*/ { localKeepers[i] -= soldiersLeft; soldiersLeft = 0; break; }
						}

						CL_PostUnits(localKeepers);
					}), "Récupérer les unités", "Assigner les unités en garnison au <b>général</b>. Des unités resteront sur place pour défendre la zone.");
					actionsList.append('<img class="generalAction_TransferToLoc KCLTransferDown" />');
					CL_InitTooltip($(actionsList).children('.generalAction_TransferToLoc:first').click(function(){
						var generalMinOk = false;
						for(var i=0;i<localKeepers.length;i++){
							if(!generalMinOk && gArmy[i] > 0) { localKeepers[i] += gArmy[i] - 1; generalMinOk = true; }
							else { localKeepers[i] += gArmy[i]; }
						}

						CL_PostUnits(localKeepers);
					}), "Placer les unités en garnison", "Placer les unités du général en <b>garnison</b>. Le général conservera une unité pour sa garde personnelle.");

					actionsList.append('<img class="generalAction_Fort" src="/img/icons/a_forti.png" />');
					CL_InitTooltip($(actionsList).children('.generalAction_Fort:first').click(function(){
						document.location = '/general/'+generalId+'/fortify';
					}), "Fortifier", "");

					if(ressources.length>0){
						actionsList.append('<img class="generalAction_Harvest" src="/img/icons/a_res.png" />');
						CL_InitTooltip($(actionsList).children('.generalAction_Harvest:first').click(function(){
							document.location = '/general/'+generalId+'/recolt';
						}), "Récolter les ressources", ressources);
					}
				}
				else if(isFortified && ownedLocation){
					actionsList.append('<img class="generalAction_Unfort" src="/img/icons/a_noforti.png" />');
					CL_InitTooltip($(actionsList).children('.generalAction_Unfort:first').click(function(){
						document.location = '/general/'+generalId+'/fortify';
					}), "Désengager", "");
				}
				else if(isMoving){
					actionsList.append('<img class="generalAction_TurnBack" src="/img/icons/a_movegen.png" />');
					CL_InitTooltip($(actionsList).children('.generalAction_TurnBack:first').click(function(){
						document.location = '/general/'+generalId+'/cancelMove';
					}), "Faire demi-tour", "");
				}

				if(actionsList.children().length>0){
					$(this).mouseover(function(){
						troopsList.hide();
						actionsList.show();
					}).mouseout(function(){
						actionsList.hide();
						troopsList.show();
					});
				}
			});
		}

		{ // Realm table ordering without page refresh
			var index = 2;
			$('#kingdom .tablevb').find('tr:first').find('a').each(function(){
				$(this).attr('href', 'javascript:;');
				$(this).attr('order', 'desc');
				$(this).attr('onmouseover', $(this).attr('onmouseover')
					.replace('lieu</', 'lieu.</')
					.replace('production</', 'production.</')
					.replace('.<','. <br /><img class="KCL" /> Trier le tableau par cette colonne, dans les deux sens, sans recharger la page.<'));
				var orderIndex = index;
				$(this).click(function(){
					sortTable($('#kingdom .tablevb'), $(this).attr('order'), orderIndex);
					if($(this).attr('order') == "asc") $(this).attr('order', 'desc');
					else $(this).attr('order', 'asc');
				});
				index++;
			});
		}

		{ // Realm table icons link to eco sim
			$('#kingdom .tablevb > tbody > tr').each(function(){
				var row = $(this);
				var cell = row.children('td:eq(2)');
				if(cell.length > 0){
					var cellSpan = cell.children('span:first');
					var ecoDirectionIcon = $(cell).find('img[src="/img/icons/u_up.png"],img[src="/img/icons/u_down.png"]');
					if(ecoDirectionIcon.length>0){
						$(ecoDirectionIcon).css('cursor','pointer');
						cellSpan.attr('onmouseover', cellSpan.attr('onmouseover')
							.replace('.<','.<br /><img class="KCL" /> Cliquer pour simuler l\\\'évolution du commerce sur ce lieu.<'));
						cellSpan.click(function(){
							mt.js.Tip.hide(); //Close tooltip
							ecoSim_StartGold = parseInt(cellSpan.text());
							ecoSim_StartArmy = parseInt(row.children('td:last').text());
							switchToEcoSim();
						});
					}
				}
			});
		}

		{ // History
		CL_InitHistoryFilters([{ icon: "/img/icons/l_conquest.png;", description: "Afficher vos conquêtes et celles de vos vassaux" }
			, { icon: "/img/icons/l_death.png;", description: "Afficher les décès" }
			, { icon: "/img/icons/l_new.png;", description: "Afficher les nouveaux occupants" }, { icon: "/img/icons/l_up.png;", description: "Afficher les nouveaux titres" }
			, { icon: "/img/icons/l_badhp.png;/img/icons/l_verybadhp.png;",
				description: "Afficher les dégradations de santé <img src='/img/icons/l_badhp.png' /> et <img src='/img/icons/l_verybadhp.png' />" }
			, { icon: "/img/icons/l_friend.png;/img/icons/l_pass.png;/img/icons/l_neutral.png;/img/icons/l_enemy.png;/img/icons/l_resources.png;",
				description: "Afficher les événements diplomatiques comme les droits de passage <img src='/img/icons/l_pass.png' /> ou les changements d'attitude <img src='/img/icons/l_friend.png' /> <img src='/img/icons/l_neutral.png' /> <img src='/img/icons/l_enemy.png' />" }
			, { icon: "/img/icons/l_battle.png;/img/icons/l_battlewon.png;/img/icons/l_battlelost.png;",
				description: "Afficher les batailles <img src='/img/icons/l_battle.png' /> ainsi que les <img src='/img/icons/l_battlewon.png' /> victoires et les <img src='/img/icons/l_battlelost.png' /> défaites militaires" }
			, { icon: "/img/icons/l_gottax.png;", description: "Afficher les taxes" }
			, { icon: "/img/icons/l_revolt.png;", description: "Afficher les révoltes des vassaux" }
			, { icon: "/img/icons/l_repup.png;", description: "Afficher les gains de réputation" }]);
		}
	}

	/* User page */
	if(currentPage == pages.User){
		var tid = $('.tid_user').attr('tid_id');
		var actionHtml = '<li><div onclick="document.location = \'javascript:_tid.askDiscuss('+tid+')\'">' +
							'<img src="/img/icons/a_write.png"> <span style="padding-top: 8px;">Lui écrire</span>' +
						 '</div></li>';
		$('ul.actions').append(actionHtml);

		if($('.infosleft').length>0){
			CL_ConvertPageTitleToF($('.infos:first').find('tr:first').children('td:eq(0)').find('ul:first'));
		}

		var convertedLinks = CL_ConvertAllFTitles();
		for(var i = 0; i<convertedLinks.length; i++){
			var link = convertedLinks[i];
			var linkParent = $(link).parent();
			if($(linkParent).is('li')){
				$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						this.textContent = this.textContent.replace('Le ','La ');
					});
			}
		}
	}

	/* Map page */
	if(currentPage == pages.Map){
		// Fix bug of persisting map tooltip
		$('.mxcontent').mouseenter(function() { $('#tooltip').css('top', '-1000px'); } );
		$('.maptable .right').mouseenter(function() { $('#tooltip').css('top', '-1000px'); } );
		$('.log').mouseenter(function() { $('#tooltip').css('top', '-1000px'); } );

		// Move preparation
		var lastSelection = "";
		function CL_CheckMapSelection(){
			var infoBlock = $('#content');
			var selection = infoBlock.children('.h2g:first').html();
			if(selection !== lastSelection){
				lastSelection = selection;

				var selectionLink = infoBlock.children('.h2g:first').children('a:first');
				var selectionUrl = selectionLink.attr('href');
				var isGeneral = selectionUrl.indexOf('/map?g=') >= 0;
				var isLocation = selectionUrl.indexOf('/map?c=') >= 0;
				var selectionId = parseInt(selectionUrl.split('=')[1]);
				var actionsBlock = infoBlock.children('ul.actions:first');

				if(isGeneral){
					if(actionsBlock.find('span:contains("Déplacer le Général")').length > 0 && $('#btnPrepareMove').length == 0){
						// Insert prep block
						actionsBlock.children('li:eq(1)').after('<li><div id="btnPrepareMove"><img class="KCLPlanMove" /><span>Préparer un déplacement</span></div></li>');
						$('#btnPrepareMove').click(function(){
							if($('#MoveList').length==0){
								infoBlock.before('<h3 id="MoveListTitle">Déplacement</h3><div id="MoveList" generalId="'+selectionId+'"><div><i style="color:#416C00;">Sélectionnez une zone de la carte pour ajouter le prochain point du trajet.</i></div><br /></div>');

								// Start location and start button
								$('#MoveList').append('<div><img src="/img/icons/gdef.gif" style="width:16px;" /> Général '+selectionLink.text()+'</div>'
										+ '<div locationId="0">'+$('#content > .infos:first > li:last > a:last').text()+' - Position initiale</div>');
								$('#MoveList').append('<div id="btnConfirmMovePrep"><img src="/img/icons/a_movegen.png"> <span>Démarrer</span></div>');
								$('#btnConfirmMovePrep').click(function(){
									var generalId = $('#MoveList').attr('generalId');
									var moveUrl = baseUrl + "general/" + generalId + "/move?c=";
									var locations = $('#MoveList > [locationId]');
									if(locations.length<2) { alert('Veuillez sélectionner au moins une destination dans le trajet.'); return; }
									moveUrl += $(locations[1]).attr('locationId') + "&p=";
									for(var i = 2; i<locations.length; i++){
										if(i>2) moveUrl += ":";
										moveUrl += $(locations[i]).attr('locationId');
									}
									window.location.href = moveUrl;
								});

								// Cancel button
								$('#MoveList').append('<a id="btnCancelMovePrep" href="javascript:;">Annuler</a>');
								$('#btnCancelMovePrep').click(function(){
									$('#MoveList').remove();
									$('#MoveListTitle').remove();
								});
							}
						});
						CL_InitTooltip($('#btnPrepareMove'), "Préparation d'un déplacement", descMovePlan);
					}
				}
				else if(isLocation){
					if($('#MoveList').length>0){
						$('#MoveList > [locationId]').removeClass('last');
						$('#btnConfirmMovePrep').before('<div locationId="'+selectionId+'" class="last">'+selectionLink.text()+' &nbsp; <a href="javascript:;" onclick="$(this).parent().remove();" style="display:none;">Retirer</a></div>');
						$('#MoveList > [locationId="'+selectionId+'"]:first')
							.mouseover(function(){ $(this).children('a').show(); }).mouseout(function(){ $(this).children('a').hide(); });
					}
				}
			}
		};
		CL_CheckMapSelection();
		setInterval(CL_CheckMapSelection, 300);

		// Titles
		var convertedLinks = CL_ConvertAllFTitles();
		for(var i = 0; i<convertedLinks.length; i++){
			var link = convertedLinks[i];
			var linkParent = $(link).parent();
			if($(linkParent).is('li')){
				var icon = $(linkParent).children('img:first');
				var isFirst = $(linkParent).children('a[href^="/user/"]:first').attr('href') == $(link).attr('href');
				var isLast = $(linkParent).children('a[href^="/user/"]:last').attr('href') == $(link).attr('href');
				if($(icon).is('[src="/img/icons/l_up.png"]')){ // Proclamations nouveaux titres
					var titleElem = $(linkParent).children('b:last');
					var title = $(titleElem).text();
					var newTitle = CL_ConvertTitleToF(title);
					$(titleElem).html(newTitle);
					$(titleElem).prev()[0].nextSibling.data = ' a été proclamée ';
				} else if($(icon).is('[src="/img/icons/l_new.png"]')){ // Nouveaux arrivants
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						this.textContent = this.textContent.replace('Un jeune chevalier du nom','Une jeune chevaleresse du nom');
					});
				} else if($(icon).is('[src="/img/icons/l_conquest.png"]')){ // Conquêtes
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						this.textContent = this.textContent.replace(' sous les ordres du ',' sous les ordres de la ');
					});
				} else if($(icon).is('[src="/img/icons/l_destroy.png"]')){ // Effondrement de royaume (ou capture)
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						if(isFirst && isLast)
							this.textContent = this.textContent.replace('Le Royaume du ','Le Royaume de la ');
						if(isFirst)
							this.textContent = this.textContent.replace(' par le ',' par la ');
						if(isLast)
							this.textContent = this.textContent.replace('le Royaume du ','le Royaume de la ');
					});
				} else if($(icon).is('[src="/img/icons/l_death.png"]')){ // Décès
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						this.textContent = this.textContent.replace('Le ','La ');
						this.textContent = this.textContent.replace('est mort !','est morte !');
					});
				} else if($(icon).is('[src="/img/icons/l_revolt.png"]')){ // Révoltes contre suzerain TODO BUG 2 values !!!
					$(linkParent).contents().filter(function() {
						return this.nodeType == 3
					}).each(function(){
						if(isFirst){
							this.textContent = this.textContent.replace('Le ','La ');
							this.textContent = this.textContent.replace('s\'est révolté ','s\'est révoltée ');
						}
						if(isLast)
							this.textContent = this.textContent.replace('son suzerain le ','sa suzeraine la ');
					});
				}
			}
		}

		// History filters
		CL_InitHistoryFilters([{ icon: "/img/icons/small/res_metal.gif;", description: "Afficher les découvertes de nouvelles mines" }
			, { icon: "/img/icons/small/res_lin.gif;", description: "Afficher les découvertes de nouveaux champs de lin" }
			, { icon: "/img/icons/small/res_horse.gif;", description: "Afficher les découvertes de nouvelles prairies" }
			, { icon: "/img/icons/l_new.png;", description: "Afficher les apparitions de nouveaux chevaliers" }
			, { icon: "/img/icons/l_conquest.png;", description: "Afficher les conquêtes" }
			, { icon: "/img/icons/l_destroy.png;/img/icons/l_death.png;",
				description: "Afficher les décès <img src='/img/icons/l_death.png' /> et les effondrements de royaumes <img src='/img/icons/l_destroy.png' />" }
			, { icon: "/img/icons/l_revolt.png;/img/icons/l_revoltrefus.png;",
				description: "Afficher les révoltes <img src='/img/icons/l_revolt.png' /> <img src='/img/icons/l_revoltrefus.png' />" }
			, { icon: "/img/icons/l_up.png;", description: "Afficher les proclamations de nouveaux titres" }]);
	}

	/* City page */
	if(currentPage == pages.City){
		CL_LoadCityPage();

		setInterval(function(){
			if($('#KCL_TotalUnits').length==0) // Page updated after turn played
				CL_LoadCityPage();
		}, 600);
	}

	/* Unit transfer page */
	if(currentPage == pages.UnitTransfer){
	   var btnCancel = $('.punits:first').find('a:first');
	   var btnOk = $('.punits:first').find('input:first');
	   var btnTemplate = '<li><a href="#" class="KCLTransfer" onclick="return delta(\'{unitType}\',{value})">{text}</a></li>';

	   /* Add specific buttons */
	   for (var i = 0; i < unitTypes.length; i++) { CL_AddUnitButtons(unitTypes[i], btnTemplate);  }
	   CL_InitTooltip($('.KCLTransfer'), "Déplacement d'unités", "");

	   /* Add unit icon click action */
	   $('.unit').css('cursor', 'pointer');
	   $('.unit').click(function(){
		   var id = $(this).find('.n:first').attr('id');
		   var direction = id[0] == 'g' ? -1 : 1;
		   var unitType = id.substring(1);
		   delta(unitType, 10000 * direction);
	   });

	   /* Add global buttons */
	   $(btnOk).parent().prepend('<a href="javascript:;" id="btnRemoveAll" class="button" onclick="CL_Functions.CL_RemoveAll();">Retirer tout</a><br />');
	   $(btnCancel).parent().prepend('<a href="javascript:;" id="btnAddAll" class="button" onclick="CL_Functions.CL_AddAll();">Ajouter tout</a><br />');
	   CL_InitTooltip($('#btnRemoveAll'), "Déplacement d'unités", "Placer toutes les unités en garnison.");
	   CL_InitTooltip($('#btnAddAll'), "Déplacement d'unités", "Assigner toutes les unités sur le général.");

	   /* Fix table so buttons stay 2x2 */
	   $('select[name="units"]').css('maxWidth', '70px');
	   $('.units th').css('maxWidth', '68px');
	   $('.units th').css('overflow', 'hidden');

	   /* Buttons colors */
		$('a[href^="/map?"]').css('filter', 'grayscale(1)'); // Cancel
		$('#btnRemoveAll').css('filter', 'hue-rotate(315deg)');
		$('#btnAddAll').css('filter', 'hue-rotate(30deg)');
    }

	/* Pantheon page */
	if(currentPage == pages.Pantheon){
		var currentYear = (new Date().getFullYear()) - 600;
		var pantheonKCL = false;
		var pageSize = 30;
		var sScores = GetStoredScores();
		var cScores;
		var rankType = "Score";
		CL_ConvertAllFTitles(); // First, before recordings

		function GetStoredScores(){
			var result = GM_getValue('KCL_Scores');
			if(result == null || result === undefined)
				return [];
			return result;
		}
		function SetStoredScores(scoreArray){
			var today = new Date();
			var dd = today.getDate();
			var mm = today.getMonth()+1;
			var yyyy = today.getFullYear();
			if(dd<10) dd='0'+dd;
			if(mm<10) mm='0'+mm;

			GM_setValue('KCL_Scores',scoreArray);
			GM_setValue('KCL_ScoresDate',yyyy+'.'+mm+'.'+dd);
		}
		function CL_GetPantheonRowInfo(row){
			var result = new Object();
			var scoreInfoRaw = $(row).children('td:eq(3)').children('span:first').attr('onmouseover').replace(/(\\r\\n|\\n|\\r)/gm, '');
			var scoreInfoParts = scoreInfoRaw.split('<dd>');
			result.reignPeriodText = scoreInfoParts[1].split('</dd>')[0];
			result.ageText = scoreInfoParts[2].split('</dd>')[0];
			var maxGloryText = scoreInfoParts[3].split('</dd>')[0];
			var gloryText = scoreInfoParts[4].split('</dd>')[0];
			var armyText = scoreInfoParts[5].split('</dd>')[0];
			var ecoText = scoreInfoParts[6].split('</dd>')[0];
			var reputationText = scoreInfoParts[7].split('</dd>')[0];

			function getValue(text){ return parseInt(text.split('</')[0].split('>')[1]); }

			result.year = result.reignPeriodText.split(' ').pop();
			result.age = parseInt(result.ageText.split('ans')[0]);
			result.maxGlory = getValue(maxGloryText);
			result.glory = getValue(gloryText);
			result.army = getValue(armyText);
			result.eco = getValue(ecoText);
			result.reputation = getValue(reputationText);

			var playerLink = $(row).children('td:eq(1)').find('a:first');
			result.playerFullName = $(playerLink).text();
			result.playerUid = parseInt($(playerLink).attr('href').split('/user/')[1]);

			var worldCell = $(row).children('td:eq(2)');
			var levelImage = $(worldCell).children('img:first').attr('src').split('/small/')[1];
			result.worldLevel = 0;
			if(levelImage=='unit_sold.gif') result.worldLevel = 1;
			else if(levelImage=='unit_arch.gif') result.worldLevel = 2;
			else if(levelImage=='unit_bal.gif') result.worldLevel = 3;
			else if(levelImage=='unit_pal.gif') result.worldLevel = 4;
			var worldLink = $(worldCell).children('a:first');
			result.worldName = $(worldLink).text();
			result.worldCityId = parseInt($(worldLink).attr('href').split('c=')[1]);
			result.worldCityName = $(worldLink).attr('onmouseover').split('<b>')[1].split('</b>')[0];

			var scoreCell = $(row).children('td:eq(4)');
			result.score = parseInt(scoreCell.children('b:first').text());

			return result;
		}
		function CL_GetFilteredScores(rScores){
			var results = [];
			
			var filterYears = [];
			$('#KCL_Filters > span > input[id^="KCL_Filter_Y"]:checked').each(function(){
				filterYears.push(parseInt($(this).attr('id').replace('KCL_Filter_Y','')));
			});
			var filterAges = [];
			$('#KCL_Filters > span > input[id^="KCL_Filter_Age"]:checked').each(function(){
				var baseAge = parseInt($(this).attr('id').replace('KCL_Filter_Age','').split('-')[0]);
				var nbAges = baseAge < 100 ? 10 : 100;
				for(var i = 0; i<nbAges; i++)
					filterAges.push(baseAge+i);
			});
			
			for(var i = 0; i<rScores.length; i++){
				var iScore = rScores[i];
				if((iScore.eco > iScore.army/3 || iScore.army < 100) // If you don't pay your troops, you're not in KCL Pantheon :-)
					&& filterYears.indexOf(parseInt(iScore.year))>=0
					&& filterAges.indexOf(iScore.age)>=0){ 
					
					switch(rankType){
						case "Score": iScore.rankValue = iScore.score; break;
						case "Glory": iScore.rankValue = iScore.glory; break;
						case "MaxGlory": iScore.rankValue = iScore.maxGlory; break;
						case "Army": iScore.rankValue = iScore.army; break;
						case "Eco": iScore.rankValue = iScore.eco; break;
						case "Reputation": iScore.rankValue = iScore.reputation; break;
						case "Age": iScore.rankValue = iScore.age; break;
						default: iScore.rankValue = iScore.score; break;
					}
					
					if(rankType=="Age" && iScore.ageText.indexOf('et')>0) iScore.rankValue += parseInt(iScore.ageText.split('et')[1].replace('mois',''))/100;
					else if($('#KCL_Mode_ByYear').is(':checked') && rankType!="Age"){
						var months = (iScore.age-20)*12;
						if(iScore.ageText.indexOf('et')>0) months += parseInt(iScore.ageText.split('et')[1].replace('mois',''));
						iScore.rankValue = iScore.rankValue / months;
					}
					
					results.push(iScore);
				}
			}
			
			results=results.sort(function(a, b) {
				return b.rankValue - a.rankValue;
			});
			

			return results;
		}
		function CL_AppendYearDot(year, cell){
			// Year color
			var yearColor = 'black', desc = 'très ancien';
			if(year == currentYear) { yearColor = 'white'; desc = 'cette année'; }
			else if(year == currentYear-1) { yearColor = 'yellow'; desc = 'l\'an passé'; }
			else if(year == currentYear-2) { yearColor = 'orange'; desc = 'il y a deux ans'; }
			else if(year == currentYear-3) { yearColor = 'tomato'; desc = 'il y a trois ans'; }
			var yDot = '<b style="color:'+yearColor+';cursor:default;font-size:12pt;">•</b>';
			cell.append(' &nbsp; <b style="color:'+yearColor+';cursor:default;font-size:12pt;">•</b>');
			CL_InitTooltip(cell.children('b:last'), "Indicateur", "Ancienneté du score : "+desc+".");
		}
		function CL_Pantheon_BackPage(){
			var currentPage = parseInt($('.pages:first').attr('pageNo'));
			if(currentPage>1)
				CL_Pantheon_LoadPage(currentPage-1);
		}
		function CL_Pantheon_NextPage(){
			var currentPage = parseInt($('.pages:first').attr('pageNo'));
			CL_Pantheon_LoadPage(currentPage+1);
		}
		function CL_Pantheon_LoadPage(pageNo){
			var tableBody = $('.tablekingdom > tbody:first');
			$(tableBody).children('tr:gt(0):not(".lastr")').remove();
			var lastRow = $(tableBody).children('tr:last');
			var basePos = 1 + (pageNo-1)*pageSize;
			var nextPagePos = basePos + pageSize;
			for(var i = basePos - 1; i<cScores.length && i<nextPagePos-1; i++){
				var iScore = cScores[i];

				var worldUImg = '';
				if(iScore.worldLevel==1) worldUImg='sold';
				else if(iScore.worldLevel==2) worldUImg='arch';
				else if(iScore.worldLevel==3) worldUImg='bal';
				else if(iScore.worldLevel==4) worldUImg='pal';
				var playerColor = iScore.playerUid == uid ? "style='color:darkblue;'" : "";

				$(lastRow).before('<tr>'
								+'<td>'+basePos+'</td>'
								+'<td><a href="/user/'+iScore.playerUid+'" '+playerColor+'>'+iScore.playerFullName+'</a></td>'
								+'<td><img src="/img/icons/small/unit_'+worldUImg+'.gif" /> <a href="/map?c='+iScore.worldCityId+'">'+iScore.worldName+'</a></td>'
								+'<td>Voir</td>'
								+'<td>'+Math.round(iScore.rankValue*100)/100+'</td>'
								+'</tr>');
				var row = $(lastRow).prev();
				CL_InitTooltip($(row).children('td:eq(2)'), "Nom de la capitale", "<b>"+iScore.worldCityName+"</b>");
				var scoreToolTipContent =
				'<dl>'
				+'	<dt>Règne</dt> <dd>'+iScore.reignPeriodText+'</dd>'
				+'	<dt>Age</dt> <dd>'+iScore.ageText+'</dd>'
				+'	<dt>Apogée</dt> <dd><strong>'+iScore.maxGlory+'</strong> <img src="/img/icons/l_up.png"/></dd>'
				+'	<dt>Gloire (à sa mort)</dt> <dd><strong>'+iScore.glory+'</strong> <img src="/img/icons/l_up.png"/></dd>'
				+'	<dt>Plus grande armée</dt> <dd><b>'+iScore.army+'</b> <img src="/img/icons/l_battle.png"/></dd>'
				+'	<dt>Commerce max</dt> <dd><strong>'+iScore.eco+'</strong> <img src="/img/icons/l_tax.png"/></dd>'
				+'	<dt>Meilleure réputation</dt> <dd><strong>'+iScore.reputation+'</strong> <img src="/img/icons/l_rep.png"/></dd>'
				+'	<dt>Score final</dt> <dd><strong>'+iScore.score+'</strong> <img src="/img/icons/capitale.png"/></dd>'
				+'</dl>';
				CL_InitTooltip($(row).children('td:eq(3)'), "Détail du score", scoreToolTipContent);

				CL_AppendYearDot(iScore.year,$(row).children('td:last'));
				basePos++;
			}
			$('.pages:first').attr('pageNo',pageNo);
			$('.pages:first').html('Page '+pageNo+'');
		}

		var switchAddress = $('.buttonshall > a').length>0 ? $('.buttonshall > a').attr('href') : ""; 
		var isGlobalPantheon = switchAddress.indexOf('uid=') > 0;
		var uid = isGlobalPantheon ? parseInt(switchAddress.split('?uid=')[1]) : parseInt(window.location.href.split('?uid=')[1].split(';')[0]);

		{ // Player pantheon titles
			if(!isGlobalPantheon && CL_CheckF(uid)){
				$('.tablekingdom:first > tbody > tr:gt(0)').each(function(){
					var titleCell = $(this).children('td:first');
					$(titleCell).html(CL_ConvertTitleToF(titleCell.text()));
				});
			}
		}

		{ // Color dot + current player score + ensure record
			var scoresEnsured = 0;
			$('.tablekingdom > tbody > tr:gt(0)').each(function(){
				if($(this).children('td').length < 5) return;
				var ri = CL_GetPantheonRowInfo(this);
				var scoreCell = $(this).children('td:eq(4)');
				CL_AppendYearDot(ri.year,scoreCell);

				// Player color
				if(uid == ri.playerUid)
					$(this).children('td:eq(1)').find('a:first').css('color', 'darkblue');

				// Ensure record
				var recordFound = false;
				for(var i = 0; i<sScores.length; i++){
					if(ri.score==sScores[i].score && ri.reignPeriodText == sScores[i].reignPeriodText){
						recordFound = true;
						break;
					}
				}
				if(!recordFound){
					sScores.push(ri);
					scoresEnsured++;
				}
			});
			if(scoresEnsured>0) SetStoredScores(sScores);
			console.log('Nouveaux scores enregistrés : ' + scoresEnsured);
			if(scoresEnsured>0) $('#mxcontent').prepend(
				'<span id="newScoresInfo" style="float: right; margin-right: 64px; margin-top: 6px;">'+scoresEnsured+' nouveaux scores enregistrés</span> ');
			console.log('Total scores enregistrés : ' + GetStoredScores().length);
		}

		// Button switching to KCL pantheon
		if(currentUrl.endsWith('/pantheon') || currentUrl.endsWith('page=1')){
			$('#newScoresInfo').remove();
			$('#mxcontent').prepend('<div id="topRightInfo" style="float: right; margin-right: 64px; margin-top: 6px;"></div>');
			$('.pantheon').css('paddingTop', '24px');
			$('#topRightInfo').append('<a id="btnKCL" class="button" href="javascript:;" type="submit" style="filter:saturate(3);display:inline-block;margin-left: 12px;">Panthéon KCL</a>');
			$('#topRightInfo').append('<a id="btnKCLExit" class="button" href="javascript:window.location.href=\'/pantheon\';" style="filter:saturate(0.1);display:none;margin-left: 12px;">Retour au Panthéon</a>');
			$('#btnKCL').click(function(){
				$('.userh1:first').width('350px').css('textAlign','left').css('paddingLeft','35px').append(' <img class="KCL" />');
				$('#topRightInfo').prepend('<span>'+sScores.length+' scores enregistrés</span> ');
				$(this).hide();
				$('#btnKCLExit').css('display','inline-block');

				// Filters
				var filtersContainer = $('.buttonshall:first');
				var ageInputs = '';
				for(var i = 2; i<=9; i++){
					var s = i*10, e = s+9, def = s+'-'+e;
					ageInputs += '<input id="KCL_Filter_Age'+def+'" type="checkbox" /><label for="KCL_Filter_Age'+def+'">'+def+'</label><br />';
				}
				var yearInputs = '';
				for(var i = 1409; i<=currentYear; i++){
					yearInputs += '<input id="KCL_Filter_Y'+i+'" type="checkbox" /><label for="KCL_Filter_Y'+i+'">'+i+'</label><br />';
				}
				$(filtersContainer).prepend('<hr />' +
											'<div id="KCL_Filters" style="margin-top: 16px;">' + 											
											'	<div>' +
											'		<a href="javascript:;" class="button" rt="Score">Score <img src="/img/icons/capitale.png"></a>' +
											'		<a href="javascript:;" class="button" rt="Glory">Gloire <img src="/img/icons/l_up.png"/></a>' +
											'		<a href="javascript:;" class="button" rt="MaxGlory">Apogée <img src="/img/icons/l_up.png"/></a>' +
											'		<a href="javascript:;" class="button" rt="Army">Armée <img src="/img/icons/l_battle.png"/></a>' +
											'		<a href="javascript:;" class="button" rt="Eco">Commerce <img src="/img/icons/l_tax.png"/></a>' +
											'		<a href="javascript:;" class="button" rt="Reputation">Réputation <img src="/img/icons/l_rep.png"/></a>' +
											'		<a href="javascript:;" class="button" rt="Age">Âge <img src="/img/icons/l_badhp.png"></a>' +
											'	</div>' +											
											'<br /><input id="KCL_Mode_ByYear" type="checkbox" /><label for="KCL_Mode_ByYear">Classement en taux mensuel</label><br />' +
											'	<span style="display:inline-block;">' +
											'		<label>Âge</label><br />' +
													ageInputs +
											'		<input id="KCL_Filter_Age100Plus" type="checkbox" /><label for="KCL_Filter_Age100Plus">100+</label><br />' +
											'	</span>' +
											'	<span style="display:inline-block;">' +
											'		<label>Année</label><br />' +
													yearInputs +
											'	</span>' +
											'</div><hr style="margin-bottom:36px;" />');
				$('#KCL_Filters').find('span > input[type="checkbox"]').attr('checked','checked');
				$('#KCL_Filters').find('a').css('display','inline-block');
				$('#KCL_Filters').find('a > img').css('position','relative').css('top','5px');
				$('#KCL_Filters').find('a').click(function(){
					var rankValueHeaderCell = $('.tablekingdom > tbody:first > tr:first > th:last');
					$(rankValueHeaderCell).html($(this).html())
					$(rankValueHeaderCell).children('img').css('position','');
					rankType = $(this).attr('rt');
					
					cScores = CL_GetFilteredScores(sScores);
					CL_Pantheon_LoadPage(1);
				});				
				
				// Convert table (after filters are ready)
				//<a href="/pantheon?uid=;page=2"><img src="/img/next.gif" alt=""></a>
				$('.back:first').html('<a href="javascript:;"><img src="/img/back.gif" alt=""></a>').click(function(){ CL_Pantheon_BackPage(); });
				$('.next:first').html('<a href="javascript:;"><img src="/img/next.gif" alt=""></a>').click(function(){ CL_Pantheon_NextPage(); });
				$('.pages:first').html('Page 1').attr('pageNo', 1);
				cScores = CL_GetFilteredScores(sScores);
				CL_Pantheon_LoadPage(1);
				pantheonKCL=true;
			});
		}

		// Prev/next pages (standard Pantheon)
		$(document).keydown(function(e) {
			if(pantheonKCL){
				switch(e.which) {
					case 37: CL_Pantheon_BackPage(); break;// left
					//case 38: break;// up
					case 39: CL_Pantheon_NextPage(); break;// right
					//case 40: break;// down
					default: return;
				}
			}
			else{
				switch(e.which) {
					case 37: if($('div.back > a').length>0) window.location.href = $('div.back > a').attr('href'); break;// left
					//case 38: break;// up
					case 39: if($('div.next > a').length>0) window.location.href = $('div.next > a').attr('href'); break;// right
					//case 40: break;// down
					default: return;
				}
			}
			e.preventDefault();
		});

	}

	/* Ranking page */
	if(currentPage == pages.Ranking)
		CL_ConvertAllFTitles();

   console.log("Kingdom CL loaded");
});

function CL_LoadCityPage(){
	/* Units */
	var unitListTitle = $('h2.h2a').filter(function(index) { return $(this).text() === "Unités"; });
	var unitList = unitListTitle.parent().children('ul.items:first');
	var unitCount = 0;
	$(unitList).find('.number').each(function() { unitCount += parseInt($(this).html()); });
	unitListTitle.append('<span id="KCL_TotalUnits"> - ' + unitCount + '</span>');
	CL_InitTooltip($('#KCL_TotalUnits'), "Garnison totale", "");

	/* Units cost */
	var caserneLvl = CL_GetBuildingLevel("Caserne");
	var caserneCount = CL_GetCaserneCount(caserneLvl);
	var unitCost = unitCount - caserneCount;
	if(unitCost > 0){
		unitListTitle.append('<span id="KCL_UnitsCost"> - ' + unitCost + ' <img src="/img/icons/small/res_gold.gif" style="position:relative; top: 3px;"/></span>');
		CL_InitTooltip($('#KCL_UnitsCost'), "Coût de la garnison", "");
	}

	/* Citizens */
	var citizenListTitle = $('h2.h2e').filter(function(index) { return $(this).text() === "Population"; });
	var citizenList = citizenListTitle.parent().children('ul.items:first');
	var citizenCount = 0;
	$(citizenList).find('.number').each(function() { citizenCount += parseInt($(this).html()); });
	citizenListTitle.append('<span id="KCL_TotalCitizens"> - ' + citizenCount + '</span>');
	CL_InitTooltip($('#KCL_TotalCitizens'), "Tous les citoyens", "");

	/* Food abundance & golden age */
	var resElem = $('.resources:first'); //ul
	var foodElem = resElem.children(':eq(0)').children(':first'); // div with res class
	var foodStock = parseInt(foodElem.find('.n:first').text()); // + 1000;
	var goldElem = resElem.children(':eq(1)').children(':first');
	var goldStock = parseInt(goldElem.find('.n:first').text()); // + 1000;
	var populationExp2 = citizenCount * citizenCount;
	if(foodStock>populationExp2 && citizenCount<100)
		CL_ActivateFoodAbundance(foodElem, populationExp2);
	if(goldStock>populationExp2/2)
		CL_ActivateGoldAge(goldElem, populationExp2/2);

	/* History */
	CL_InitHistoryFilters([{ icon: "//data.twinoid.com/proxy/mush.vg/img/icons/ui/pa_cook.png;",
					description: "Afficher les consommations de nourriture et d'or", textFilter: " Vos habitants ont mangé " }
		, { icon: "/img/icons/small/res_gold.gif;", description: "Afficher les productions d'or", textFilter: "+Votre ville a produit" }
		, { icon: "/img/icons/small/res_food.gif;", description: "Afficher les productions de nourriture", textFilter: "+Votre ville a produit" }
		, { icon: "/img/icons/small/res_wood.gif;", description: "Afficher les productions de bois", textFilter: "+Votre ville a produit" }
		, { icon: "/img/icons/small/icon_hammer.gif;", description: "Afficher les constructions", textFilter: " construction" }
		, { icon: "/img/icons/small/res_rec.gif;", description: "Afficher les productions de tours", textFilter: "+Vous pouvez rejouer" }
		, { icon: "/img/icons/small/unit_sold.gif;", description: "Afficher les recrutements de soldats", textFilter: "+Vous avez recruté" }
		, { icon: "/img/icons/small/people_pend.gif;", description: "Afficher les nouveaux citoyens", textFilter: " citoyen" }
		, { icon: "//data.twinoid.com/proxy/www.hordes.fr/gfx/forum/smiley/h_warning.gif;",
			description: "Afficher les gaspillages", textFilter: " car vous n'avez pas de stock suffisant" }
		, { icon: "/img/icons/small/res_metal.gif;",  textFilter: " a ramassé",
			description: "Afficher les ramassages de <img src='/img/icons/small/res_metal.gif' /> <img src='/img/icons/small/res_lin.gif' /> <img src='/img/icons/small/res_horse.gif' /> " }]);
}

function CL_ActivateFoodAbundance(elem, limit){
	var title = "Abondance de nourriture";
	var description = "Vos citoyens sont si bien nourris que votre démographie augmente. Plus de citoyens apparaissent dans la grille de production.<br />Gardez un stock supérieur à "+limit+' <img src="/img/icons/small/res_food.gif" /> pour conserver cet avantage.';

	CL_ActivateThreshold(elem, title, description, 'hue-rotate(45deg)');
}
function CL_ActivateGoldAge(elem, limit){
	var title = "Âge d'or";
	var description = "Votre empire connait une période de pérennité économique, de quoi lever une grande armée. Plus de d'épées apparaissent dans la grille de production.<br />Gardez un stock supérieur à "+limit+' <img src="/img/icons/small/res_gold.gif" /> pour conserver cet avantage.';

	CL_ActivateThreshold(elem, title, description, 'saturate(2)');
}
function CL_ActivateThreshold(elem, title, description, filter){
	$(elem).css('filter', filter);

	var existingEvent = $(elem).attr('onmouseover');
	if(typeof existingEvent !== typeof undefined && existingEvent !== false){
		title = title.replace('\'', '\\\'');
		description = description.replace('\'', '\\\'');
		$(elem).attr('onmouseover', existingEvent.replace('.</div>', '.<br /><br /><h3>' + title + '</h3>' + description + '</div>'));		
	}
	else
		CL_InitTooltip(elem, title, description);
}

function CL_CheckF(uid){
	var filterList = [ // /*Test*/ 5366995, 5205738, 64233, //5297057,4961830, //208902, 428702,
	254, 3981, 8493, 35339, 47231, 47925, 60417, 60895, 90795,
	125646, 179600, 357447, 476707, 498008, 686001, 720708, 781272, 851314,
	1155559, 1803841, 1894762,
	2074113, 2203113, 2491324, 2924163,
	3300786, 3412666, 3599378, 3629265, 3664799, 3691814, 3866270, 3962653,
	4174705, 4271147, 4323453, 4330214, 4437677, 4476242, 4939939, 4953259,
	5017544, 5252621, 5364172, 5385944, 5423257, 5425646, 5427547, 5432668, 5433242 ];
	return filterList.indexOf(uid) >= 0;
}
function CL_ConvertAllFTitles(){
	function CL_ConvertTitle(link){
		if(CL_IsFLink(link)) {
			var title = $(link).text().split(' ')[0];
			var newTitle = CL_ConvertTitleToF(title);
			var username = $(link).text().substring(title.length+1);
			if(newTitle.length>0){
				$(link).html(newTitle+' '+username);
			}
			return link;
		}
		return null;
	}
	function CL_IsFLink(link){
		var userId = parseInt($(link).attr('href').replace('/user/',''));
		return CL_CheckF(userId);
	}

	// Update base links
	var results = [];
	$('a[href^="/user/"]').each(function(){
		var result = CL_ConvertTitle(this);
		if(result!=null) results.push(result);
	});
	// Update tooltips
	setInterval(function(){
		function CL_UpdateFInfo(link){
			var result = CL_ConvertTitle(link);
			if(result!=null) {
				$(result).parent().contents().filter(function() {
					return this.nodeType == 3
				}).each(function(){
					this.textContent = this.textContent.replace('Capitale du ','Capitale de la ');
					this.textContent = this.textContent.replace('royaume du ','royaume de la ');
				});
				$(result).parent().html($(result).parent().html().replace('> du <', '> de la <'));
			}
		}
		var t = $('#tipcontent');
		if($(t).children('.FTOk').length==0){
			$(t).find('a[href^="/user/"]').each(function(){ CL_UpdateFInfo(this); });
			$(t).append('<span class="FTOk"></span>');
		}
		var info = $('#content > .infos:first');
		if($(info).children('.FTOk').length==0){
			$(info).find('a[href^="/user/"]').each(function(){ CL_UpdateFInfo(this); });
			$(info).append('<span class="FTOk"></span>');
		}
	}, 100);
	// Update vassals
	$('#vassals > table.blocks > tbody > tr > td').each(function(){
		if(CL_IsFLink($(this).find('a:first'))){
			var titleElem = $(this).find('p:first');
			var title = $(titleElem).text().split(':')[1].replace(/ /g, '');
			var fTitle = CL_ConvertTitleToF(title);
			$(titleElem).html('<span class="dt">Titre</span> : '+fTitle+' ');
		}
	});

	//TODO : nouveaux titres de soi (à tester)
	//TODO : écran de fin de partie

	return results;
}

function CL_InitHistoryFilters(icons){
	$('.log > h3:first').css('textAlign', 'left');
	$('.log > h3:first').css('marginLeft', '12px');

	// Clear filters button
	$('.log').prepend('<span id="historyFilters"><h3>Filtres :</h3> <img src="//data.twinoid.com/proxy/mush.vg/img/icons/ui/status/mastered.png" icons="" desc="Retirer les filtres" /></span>');

	// Add filters buttons
	for(var i = 0; i<icons.length; i++)
	{
		var textFilter = "";
		if(icons[i].textFilter !== undefined) textFilter = "textFilter='"+icons[i].textFilter+"'";
		$('#historyFilters').append('<img src="'+icons[i].icon.split(';')[0]+'" icons="'+icons[i].icon+'" desc="'+icons[i].description+'" '+textFilter+' /> ');
	}

	// Filter actions
	$('#historyFilters > img').click(function()
	{
		$('#historyFilters > img').removeClass('selected');
		var src = $(this).attr('icons');
		if(src.length > 0) $(this).addClass('selected');
		var textFilter = $(this).attr('textFilter');
		if(textFilter === undefined && src.startsWith("//data")) src = "";

		$('.log ul:first > li').each(function()
		{
			var mainIcon = $(this).find('img:first').attr('src');
			var containsIcon = src == "" || src.includes(mainIcon+';');
			if(textFilter !== undefined)
			{
				if($(this).text().includes(textFilter.substr(1)) && (textFilter[0] != '+' || containsIcon))
					$(this).show();
				else $(this).hide();
			}
			else if(containsIcon)
				$(this).show();
			else $(this).hide();
		});
	});
	$('#historyFilters > img').each(function()
	{
		CL_InitTooltip(this, "Filtrer l'historique", $(this).attr('desc'));
	});

	// Search textbox
	if($('#logTextArea').length==0){
		function logSearch(){
			console.log('cherche : ' + $('#logTextFilter').val());
			$('#historyFilters > img').removeClass('selected');
			$('.log ul:first > li').each(function()
			{
				if($(this).text().toUpperCase().includes($('#logTextFilter').val().toUpperCase()))
					$(this).show();
				else $(this).hide();
			});
		}
		$('.mxbordermaincontent').append('<div id="logTextArea"><input id="logTextFilter" type="text" placeholder="Filtre textuel" class="inputtext" /> <a id="logTextFilterBtn" href="javascript:;" class="button">Chercher</a></div>');
		$('#logTextFilterBtn').click(function() { logSearch(); });
		$('#logTextFilter').on("keypress", function(e) { if(e.which == 13) logSearch(); });
		CL_InitTooltip($('#logTextArea'), "Filtrer avec un texte", "");
	}

	// Log background image is not really resizable ...
	// $('.log > ul').resizable();
}

function CL_GetBuildingLevel(buildingName){
	try
	{
		var imgName = $('h3').filter(function(index) { return $(this).text() === buildingName; }).parent().children('img:last').attr('src');
		switch(imgName)
		{
			case '/img/level1.png': return 1;
			case '/img/level2.png': return 2;
			case '/img/level3.png': return 3;
			case '/img/level4.png': return 4;
			case '/img/level5.png': return 5;
		}
	} catch (e) { return 0; }
}
function CL_GetTitleLevel(titleName){
	try
	{
		switch(titleName)
		{
			case 'Chevalier': return 0;
			case 'Seigneur': return 1;
			case 'Baron': return 2;
			case 'Vicomte': return 3;
			case 'Comte': return 4;
			case 'Marquis': return 5;
			case 'Duc': return 6;
			case 'Prince': return 7;
			case 'Roi': return 8;
			case 'Empereur': return 9;
		}
	} catch (e) { return 0; }
}
function CL_ConvertPageTitleToF(listRoot){
	var titleName = $(listRoot).children('li:first').children('b:last').text();
	var tryCount = 0;
	setTimeout(function(){
		UpdateTitleGender();
	}, 100);
	function UpdateTitleGender(){
		tryCount++;
		if(tryCount > 50) return;
		if($('.tid_age:first').length == 0) setTimeout(function(){ UpdateTitleGender(); }, 100);
		var isF = $('.tid_age:first').children('img:first').attr('src') == '//data.twinoid.com/img/icons/female.png';
		if(isF) $(listRoot).children('li:first').children('b:last').html(CL_ConvertTitleToF(titleName));
	}
}
function CL_ConvertTitleToF(titleName){
	try
	{
		switch(titleName)
		{
			case 'Chevalier': return "Chevaleresse";
			case 'Seigneur': return "Seigneuresse";
			case 'Baron': return "Baronne";
			case 'Vicomte': return "Vicomtesse";
			case 'Comte': return "Comtesse";
			case 'Marquis': return "Marquise";
			case 'Duc': return "Duchesse";
			case 'Prince': return "Princesse";
			case 'Roi': return "Reine";
			case 'Empereur': return "Impératrice";
			default: return "";
		}
	} catch (e) { return ""; }
}
function CL_GetMapLevelTitle(level){
	switch(level){
		case 1: return "Soldat";
		case 2: return "Archer";
		case 3: return "Baliste";
		case 4: return "Paladin";
	}
}
function CL_GetMapLevelImage(level){
	switch(level){
		case 1: return "/img/icons/small/unit_sold.gif";
		case 2: return "/img/icons/small/unit_arch.gif";
		case 3: return "/img/icons/small/unit_bal.gif";
		case 4: return "/img/icons/small/unit_pal.gif";
	}
}
function CL_GetCaserneCount(caserneLvl){
	switch(caserneLvl)
	{
		case 0: return 0;
		case 1: return 5;
		case 2: return 10;
		case 3: return 20;
		case 4: return 50;
		case 5: return 100;
	}
}
function CL_GetRowKeepers(row, kArray){
	var lastCell = $(row).children('td:last');
	if(lastCell.length > 0 && Number.isInteger(+lastCell.html())){
		var parts = lastCell.attr('onmouseover').split("class=\"number\">");
		for(var pi=1; pi<parts.length; pi++){
			var count = parseInt(parts[pi].split('</span>')[0]);
			var uType = parts[pi-1].split('/small/unit_')[1].split('.gif')[0];
			var uTypeIndex = unitTypes.indexOf(uType);
			kArray[uTypeIndex] += count;
		}
	}
}
function CL_GetRowKeepersHtml(row){
	var lastCell = $(row).children('td:last');
	if(lastCell.length > 0 && Number.isInteger(+lastCell.html())){
		var result = lastCell.attr('onmouseover')
			.replace("mt.js.Tip.show(this,'", "")
			.replace("</div></div></div>')", "</div></div></div>");

		result = result.replace(/(?:\\[rn]|[\r\n]+)+/g, "").replace('<h1>Garnison</h1>', '').replace('<h1>Défense</h1>', '');

		return result;
	}
	return "";
}
function CL_GetListSoldiers(list, sArray){
	$(list).children('li').each(function(){
		CL_GetListItemSoldiers(this, sArray);
	});
}
function CL_GetListItemSoldiers(listItem, sArray){
	var unitType = $(listItem).find('img:first').attr('src').split('_')[1].split('.')[0];
	var uTypeIndex = unitTypes.indexOf(unitType);
	sArray[uTypeIndex] += parseInt($(listItem).find('.number:first').text());
}

function CL_AddUnitButtons(unitType, template){
	var actionBlock = $('#p' + unitType).parent().parent();
	$(actionBlock).append(template.replace('{unitType}', unitType).replace('{value}', '100').replace('{text}', '+1C'));
	$(actionBlock).append(template.replace('{unitType}', unitType).replace('{value}', '-100').replace('{text}', '-1C'));
	$(actionBlock).append(template.replace('{unitType}', unitType).replace('{value}', '1000').replace('{text}', '+1K'));
	$(actionBlock).append(template.replace('{unitType}', unitType).replace('{value}', '-1000').replace('{text}', '-1K'));
}
function CL_AddAll(){
	for (var i = 0; i < unitTypes.length; i++) { delta(unitTypes[i], 10000); }
}
function CL_RemoveAll(){
	for (var i = 0; i < unitTypes.length; i++) { delta(unitTypes[i], -10000); }
}

function CL_InitTooltip(elem, title, description) {
	title = '<img class="KCL" style="position:relative;top:-1px;" /> ' + title;
	$(elem).mouseover(function()
	{
		//GM tests ... not working
		//location.href = "javascript:void(mt.js.Tip.show(this,'<div class=\'tiptop\'><div class=\'tipbottom\'><div class=\'tipbg\'><h1>'+title+'</h1>'+description+'</div></div></div>'));";
		//$('body').append("<script>mt.js.Tip.show(this,'<div class=\'tiptop\'><div class=\'tipbottom\'><div class=\'tipbg\'><h1>'+title+'</h1>'+description+'</div></div></div>');</script>");
		mt.js.Tip.show(this,'<div class=\'tiptop\'><div class=\'tipbottom\'><div class=\'tipbg\'><h1>'+title+'</h1>'+description+'</div></div></div>');
	});
	$(elem).mouseout(function()
	{
		mt.js.Tip.hide();
	});
}
function CL_SwitchToInfoPage(){
	$('#logTextArea').remove();
	document.title = 'Kingdom CL - Informations';
	$('#mxcontent').html('<style>'
	  + '#mxcontent { background: transparent url("/img/h1user.png") no-repeat 10px 0px; padding-top: 54px; padding-left: 54px;  } '
	  + '#mxcontent p { margin: 8px 0px;  } '
	  + '#mxcontent h2 { margin: 18px 0px 4px 0px; font-size: 18px; } '
	  + '#mxcontent h3 { margin: 8px 0px 4px 0px; font-size: 16px; } '
	  + '#mxcontent ul { list-style-type: square; margin-left: 16px; } '
	  + '#mxcontent ul ul { list-style-type: disc; margin-left: 32px; } '
	  + '</style> '
	  + '<h1 class="userh1_intabl" style="margin-top: -52px; margin-left: -28px;">Kingdom CL</h1>'
	  + '<div style="height: 32px; font-weight: bold; margin-bottom: 12px;"><img class="KCLL" style="vertical-align:middle;" /> Version '+KCL_Version+'</div>'
	  + '<p>Cette extension a été développée par <a href="http://kingdom.muxxu.com/user/5297057">Clanker</a> pour améliorer l\'expérience et le confort du jeu Kingdom.</p>'
	  + '<p>Le jeu est modifié avec les fonctionnalités suivantes : </p>'
	  + '<h2>Description</h2>'
	  + '<h3>Barre principale</h3>'
	  + '<ul>'
	  + '<li>Intégration d\'un simulateur d\'évolution du commerce.</li>'
	  + '<li>Page d\'informations de l\'extension KCL.</li>'
	  + '</ul>'
	  + '<h3>Page de gestion</h3>'
	  + '<ul>'
	  + '	<li>Cadre "Mes infos" :'
	  + '		<ul>'
	  + '			<li>Ajout de la répartition des territoires dans l\'infobulle de la gloire.</li>'
	  + '			<li>Ajout des niveaux mimnimum, moyen et maximum de commerce dans les territoires dans l\'infobulle du commerce.</li>'
	  + '			<li>Ajout de l\'armée totale, et de sa composition en infobulle.</li>'
	  + '			<li>Ajout de la réputation totale.</li>'
	  + '			<li>Ajout du score actuel, et de son détail en infobulle.</li>'
	  + '		</ul>'
	  + '	</li>'
	  + '	<li>Cadre de la capitale :'
	  + '		<ul>'
	  + '			<li>Affichage du nombre de tours restants de nourriture en réserve, dans l\'infobulle.</li>'
	  + '			<li>Coloration de l\'icône du stock de nourriture en cas de situation d\'abondance.</li>'
	  + '			<li>Affichage du nombre de tours restants d\'or en réserve, dans l\'infobulle.</li>'
	  + '			<li>Coloration de l\'icône du stock d\'or en cas d\'âge d\'or.</li>'
	  + '		</ul>'
	  + '	</li>'
	  + '	<li>Onglet "Généraux" :'
	  + '		<ul>'
	  + '			<li>Lorsque le général est stationné, ajout d\'une infobulle sur le lieu (commerce, garnison).</li>'
	  + '			<li>Ajout des actions standards au passage de la souris : Fortifier, Se désengager, Faire demi-tour, Récolter (les ressources disponibles sont affichées dans l\'infobulle), Transférer des unités.</li>'
	  + '			<li>Ajout de la nouvelle action "Récupérer les unités".</li>'
	  + '			<li>Ajout de la nouvelle action "Placer les unités en garnison".</li>'
	  + '		</ul>'
	  + '	</li>'
	  + '	<li>Onglet "Vassaux" :'
	  + '		<ul>'
	  + '			<li>[V1.02] Collecter des taxes rouvrira cet onglet après le rechargement de la page.</li>'
	  + '		</ul>'
	  + '	</li>'
	  + '	<li>Onglet "Royaume" :'
	  + '		<ul>'
	  + '			<li>Le tableau peut à présent être trié dans les deux sens sans recharger la page.</li>'
	  + '			<li>Lorsqu\'un commerce est en croissance ou en décroissance, l\'icône peut être cliquée pour générer une simulation d\'évolution.</li>'
	  + '			<li>Adaptation du style pour éviter la déformation du tableau (qui double toutes les lignes) dans certains cas.</li>'
	  + '		</ul>'
	  + '	</li>'
	  + '	<li>Affichage de la carte actuelle et de son niveau, avec un lien pointant vers la liste d\'IPK.</li>'
	  + '	<li>Filtrage des entrées de l\'historique par type ou par texte.</li>'
	  + '	<li>[V1.02] Correction du bug affichant "NaN" dans les scores si le tableau de diplomatie est présent dans la page.</li>'
	  + '</ul>'
	  + '<h3>La carte</h3>'
	  + '<ul>'
	  + '	<li>Ajout d\'une nouvelle action sur les généraux "Préparer un déplacement" qui permet de définir un trajet point par point.</li>'
	  + '	<li>En mode stratégie, il arrive souvent que l\'infobulle reste affichée lorsque le curseur sort de la carte. Ce problème a été atténué.</li>'
	  + '	<li>Filtrage des entrées de l\'historique par type ou par texte.</li>'
	  + '</ul>'
	  + '<h3>La capitale</h3>'
	  + '<ul>'
	  + '	<li>[V1.02] Coloration de l\'icône du stock de nourriture en cas de situation d\'abondance.</li>'
	  + '	<li>[V1.02] Coloration de l\'icône du stock d\'or en cas d\'âge d\'or.</li>'
	  + '	<li>[V1.02] Extension réappliquée lorsqu\'un tour a été joué.</li>'
	  + '	<li>Affichage du nombre total de soldats en garnison, et de leur coût éventuel.</li>'
	  + '	<li>Affichage du nombre total de citoyens.</li>'
	  + '	<li>Filtrage des entrées de l\'historique par type ou par texte.</li>'
	  + '</ul>'
	  + '<h3>Page de transfert d\'unités</h3>'
	  + '<ul>'
	  + '	<li>[V1.02] Cliquer sur l\'icône d\'un type d\'unités les déplacera toutes de l\'autre côté.</li>'
	  + '	<li>Ajout de boutons pour transférer des unités d\'un type par 100 ou par 1000.</li>'
	  + '	<li>Ajout de deux boutons qui déplacent l\'ensemble des unités disponibles d\'un côté ou de l\'autre.</li>'
	  + '	<li>Adaptation du style du tableau pour en éviter la déformation (qui double toutes les lignes) dans certains cas.</li>'
	  + '</ul>'
	  + '<h3>[V1.02] Panthéon des rois</h3>'
	  + '<ul>'
	  + '	<li>Affichage d\'une pastille de couleur pour indiquer l\'ancienneté du score.</li>'
	  + '	<li>Mise en évidence du lien du joueur (en bleu) s\'il s\'agit du joueur actuel.</li>'
	  + '	<li>Les pages peuvent être parcourues à l\'aide des flèches gauche/droite du clavier.</li>'
	  + '	<li>Parcourir une page du panthéon enregistrera les scores dans l\'extension.</li>'
	  + '	<li>Nouveau "Panthéon KCL" : les scores enregistrés seront affichés avec de nouvelles options de filtrage (année, âge) et de classement (gloire, commerce, armée, âge, ...). Étant donné que les données sont locales, parcourir ce panthéon est beaucoup plus rapide. </li>'
	  + '</ul>'
	  + '<h3>Autres</h3>'
	  + '<ul>'
	  + '	<li>[V1.02] Adaptation des titres pour les joueuses (page de gestion, carte, classement, pantheon, ...).</li>'
	  + '	<li>Ajout d\'un bouton "Lui écrire" sur les pages de joueurs.</li>'
	  + '</ul>'
	  + '<h2>Contact</h2>'
	  + '<p>Avant toute chose, Twinoid demande à ne pas être dérangé pour des problèmes relatifs à des extensions. Merci de respecter cela.</p>'
	  + '<p>C\'est avec plaisir que je lirai vos commentaires et vos suggestions sur le <a href="http://kingdom.muxxu.com/tid/forum">Forum</a>, sur lequel vous pourrez en cas de problème trouver de l\'aide de ma part ou de celle de la communauté.</p>'
	  + '<p>Si besoin, vous pouvez aussi <a href="javascript:_tid.askDiscuss(4490783);">me contacter</a> directement.</p>'
	  + '<h2>Remerciements</h2>'
	  + '<p>Les premiers remerciements vont à Twinoid pour les bons moments passés sur Kingdom !</p>'
	  + '<p>Merci de façon générale à la communauté, qui a investigué et accumulé de nombreuses informations sur les mécaniques du jeu. C\'est grâce à ces informations, glanées sur les forums et les différents wiki (comme <a href="https://twinoid.com/g/ipk">https://twinoid.com/g/ipk</a> et <a href="http://twin.tithom.fr/muxxu/kingdom/">http://twin.tithom.fr/muxxu/kingdom/</a>), que j\'ai pu comprendre Kingdom et ensuite écrire cette extension.</p>'
	  + '<p>Merci à simoons et basicbrute qui ont préparé et rendu disponible le simulateur de commerce (<a href="https://twinoid.com/g/ipk#simulateur-de-commerce">https://twinoid.com/g/ipk#simulateur-de-commerce</a>) qui est intégré à KCL.</p>'
	  + '<p>Un tout grand merci à simoons pour la liste des cartes de Kingdom (<a href="https://twinoid.com/g/ipk#niveau-de-carte-choix">https://twinoid.com/g/ipk#niveau-de-carte-choix</a>).</p>'
	  + '');
}

/* Utilities */
function sortTable(table, order, colIndex) {
	// https://stackoverflow.com/questions/22906760/jquery-sort-table-data
    var asc   = order === 'asc',
        tbody = table.find('tbody');

    tbody.find('tr:gt(0)').sort(function(a, b) {
		var valA = parseInt($('td:eq('+colIndex+')', a).text());
		if(isNaN(valA)) valA = -10000;
		var valB = parseInt($('td:eq('+colIndex+')', b).text());
		if(isNaN(valB)) valB = -10000;

        if (asc) {
            return valA - valB;
        } else {
            return valB - valA;
        }
    }).appendTo(tbody);

	var evenClass = false;
	tbody.find('tr:gt(0)').each(function(){
		if(evenClass) $(this).addClass('even');
		else $(this).removeClass('even');
		evenClass = !evenClass;
	});
}
function sumArray(a){
	var sum = 0;
	for (var i = 0; i < a.length; i++)
		sum += a[i];
	return sum;
}
function qs(key) {
	// https://stackoverflow.com/questions/7731778/get-query-string-parameters-url-values-with-jquery-javascript-querystring
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

/* Eco Sim * Base code from https://twinoid.com/g/ipk#simulateur-de-commerce */
var ecoSim_StartGold = 0, ecoSim_StartArmy = -1;
function switchToEcoSim(){
	$('#logTextArea').remove();
	document.title = 'Kingdom - Simulateur';
  	$('#mxcontent').html('<style>'
	  + '#mxcontent { background: transparent url("/img/h1user.png") no-repeat 10px 0px; padding-top: 54px; padding-left: 54px;  } '
	  + '#credits { float: right; margin-right: 12px; margin-top: -48px; }'
	  + '#RESULT { margin-top: 24px; margin-left: -24px; overflow: hidden; height:100%; }'
	  + '#RESULT table{border-collapse:collapse}'
	  + '#RESULT th{width:100px;overflow:hidden}'
	  + '#RESULT td{width:5px;padding:0px;margin:0px;vertical-align:bottom;overflow:hidden}'
	  + '#RESULT td.head{width:60px;}'
	  + '#RESULT div{width:5px;background:green;display:inline-block}'
	  + '#Lines > div{ height: 48px; margin-bottom: 12px; } '
	  + '#Line1 > .plusmoins{ visibility: hidden; } '
	  + '.fields { vertical-align: middle; margin-left: 8px; } '
	  + 'td{vertical-align:top;}'
	  + '.inputsmall { width: 54px; height: 32px; background-size: 70px 34px; padding-left: 12px; }'
	  + 'a.plusmoins { margin: 0px 8px 0px 8px; display:inline-block; filter: grayscale(1);  }'
	  + '#btnAddLine { filter: hue-rotate(30deg); }'
	  + '#btnResult { margin: 0px 8px 0px 8px; display:inline-block; }'
	  + '</style> '
	  + '<h1 class="userh1_intabl" style="margin-top: -52px; margin-left: -28px;">Simulateur</h1>'
	  + '<div id="credits">Code d\'origine par <span class="tid_user tid_userBg tid_userUnknown tid_parsed" tid_bg="1" tid_id="715" style="margin-left:0px;">basicbrute</span> - <a href="https://twinoid.com/g/ipk#simulateur-de-commerce" target="__blank">Source</a></div>'
	  + '<form id="FORM">'
	  + '	<div id="Lines">'
	  + '		<div id="Line1">'
	  + '			<span class="fields">'
	  + '				Commerce : <input name="commerce" class="inputsmall" type="number" value="0" /> '
	  + '				Garnison : <input name="garnison" class="inputsmall" type="number" value="10" min="0"> '
	  + '			</span>'
	  + '			<a class="button plusmoins" href="javascript:;" onclick="CL_Functions.moins(this);" tabindex="2" title="Retirer la dernière ligne">Retirer</a>'
	  + '		</div>'
	  + '	</div>'
	  + '	<a id="btnAddLine" class="button plusmoins" href="javascript:CL_Functions.plus()" tabindex="2">Ajouter une ligne</a> '
	  + '	<a id="btnResult" class="button" type="submit">Calcul</a>'
	  + '</form>'
	  + ''
	  + '<div id="RESULT"></div>');
	initEcoSim();

	if(ecoSim_StartArmy>=0){
		$('#Line1 > .fields > input:first').val(ecoSim_StartGold);
		$('#Line1 > .fields > input:last').val(ecoSim_StartArmy);
		calcEcoSim();
	}
}

function Terre(commerce,soldat){
	this.commerce = commerce;
	this.soldat = soldat;
	this.compteur = commerce*(Math.abs(commerce)+1)*5;
	this.gain = 0;
}
Terre.prototype.image = function(){
	return {commerce:this.commerce, soldat:this.soldat, gain:this.gain, compteur:this.compteur};
}
Terre.prototype.next = function(){
	//mouais... dans ce cas on connait pas la formule
	if(this.commerce<=0 && this.soldat===0){
		this.commerce = this.compteur = undefined;
		return;
	}
	var diffsoldat = this.commerce>0 ? Math.floor(this.soldat-this.commerce/2) : this.soldat;
	if(diffsoldat<0){
		//pas assez de soldat, la perte est le carré de la différence
		this.compteur -= diffsoldat*diffsoldat;
	}else if(diffsoldat>0){
		//le compteur augmente tranquillou
		this.compteur += diffsoldat;
	}else{
		//ben le delta compteur est à 0 on n'arrete pas pour avoir tjrs le meme nombre d'entrée, mais on pourrait ...
		//break;
	}
	//on recalcule le commerce à partir du compteur grace à la formule magique
	if(this.compteur>0){
		this.commerce = Math.floor(Math.sqrt((this.compteur/5+0.25)) -0.5);
	}else{
		//doute, ce serait pas un -0.25 vu que le reste est inversé
		this.commerce = Math.floor(-Math.sqrt((-this.compteur/5+0.25)) +0.5);
	}
	this.gain += (this.commerce - this.soldat);
}
//function de calcul
function commerce(commerce, soldat){
	var terre = new Terre(commerce, soldat);
	var result = [terre.image()];
	for(var i=0;i<145;i++){
		terre.next();
		result.push(terre.image());
	}
	return result;
}
//function d'aggregation de n commerce
function aggregate(datas){
 var result = [];
 var data = datas[0];
 //on duplique le premier
 for(var i=0;i<data.length;i++){
	result.push({commerce:data[i].commerce, gain:data[i].gain, soldat:data[i].soldat});
 }
 //et on ajoute les autres
 for(var d=1;d<datas.length;d++){
	data = datas[d]
	 for(var i=0;i<data.length;i++){
		 result[i].commerce = result[i].commerce+data[i].commerce;
		 result[i].gain = result[i].gain+data[i].gain;
		 result[i].soldat = result[i].soldat+data[i].soldat;
	 }
 }
 return result;
}
//function d'affichage
function asHtml(graphName, commerces){
	//pour uniformiser la taille du graphique
	var maxcommerce = 0,mincommerce = 0;
	for(var i=0;i<commerces.length;i++){
		maxcommerce = Math.max(maxcommerce,commerces[i].commerce);
		mincommerce = Math.min(mincommerce,commerces[i].commerce);
	}
	var coef = 300/(maxcommerce - mincommerce);
	var html = '<table>';
	html += '<tr><th>Tour<br>Commerce<br>Soldats' ;
	for(var i=0;i<commerces.length;i+=12){
		html +=('<td class="head">'+i+'<br>'+commerces[i].commerce+'<br>'+commerces[i].soldat+'</td>');
	}
	html +=('</tr></table>');
	html +=('<table style="height:300px;position:relative;top:'+(mincommerce*coef)+'px;"><tr><th>'+graphName+'</th>');

	for(var i=0;i<commerces.length;i++){
		var commerce = commerces[i].commerce;
		html +=('<td title="tour '+i+' commerce '+commerce+' compteur '+(getremaindcompt(commerce, commerces[i].compteur))+' ">');
		if(commerce>0){
			html += '<div style="height:'+commerce*coef+'px"></div>';
		}else{
			html += '<div style="position:absolute;background-color:red;height:'+(-commerce*coef)+'px"></div>';
		}
		html +=('</td>');
	}

	html +=('</tr></table>');
	return html;
}
function getremaindcompt(commerce, compteur){
 if (commerce < 0) return compteur + (commerce*(commerce-1))*5;
 else return compteur - (commerce*(commerce+1))*5; //IHM?
}
function plus(){
	var newdiv = document.createElement('div');
	newdiv.innerHTML = document.getElementById('Line1').innerHTML;
	document.getElementById('Lines').appendChild(newdiv);
}
function moins(tag){
	$(tag).parent().remove();
	// Remove last line code
	// var lastLine = $('#Lines').children(':last');
	// if(lastLine.attr('id') != "Line1") lastLine.remove();
}
function initEcoSim() {
	$('#btnResult').click( function(evt){
		calcEcoSim();
		evt.preventDefault();
	});
}
function calcEcoSim(){
	var frm = $('#FORM')[0];
	if(frm.commerce.length === undefined){
		document.getElementById('RESULT').innerHTML = asHtml("Évolution", commerce(parseInt(frm.commerce.value),parseInt(frm.garnison.value)));
	}else{
		//window.alert("error ?");
		var datas = [];
		for(var i=0;i<frm.commerce.length;i++){
			datas.push(commerce(parseInt(frm.commerce[i].value),parseInt(frm.garnison[i].value)));
		}
		var html = asHtml("Total", aggregate(datas))+"<hr>";
		for(var i=0;i<datas.length;i++){
			html += asHtml("G"+(i+1), datas[i]);
		}
		document.getElementById('RESULT').innerHTML = html;
	}
}

/* MapList * Based on https://twinoid.com/g/ipk#niveau-de-carte-choix */
var mapList = [
	/* Active */
	{ level: 1, title: 'Angileux', id:  65, status: 'Active' },
	{ level: 1, title: 'Azigues', id:  56, status: 'Active' },
	{ level: 1, title: 'Lulert', id:  21, status: 'Active' },
	{ level: 1, title: 'Parigues', id:  22, status: 'Active' },
	{ level: 2, title: 'Auxenay', id:  204, status: 'Active' },
	{ level: 2, title: 'Poissac', id:  194, status: 'Active' },
	{ level: 2, title: 'Rodeletz', id:  200, status: 'Active' },
	{ level: 2, title: 'Touleuille', id:  210, status: 'Active' },
	{ level: 3, title: 'Ermailoi', id:  189, status: 'Active' },
	{ level: 3, title: 'Genuchain', id:  236, status: 'Active' },
	{ level: 3, title: 'Iseraye', id:  245, status: 'Active' },
	{ level: 3, title: 'Poicolude', id:  233, status: 'Active' },
	{ level: 3, title: 'Toruchis', id:  241, status: 'Active' },
	{ level: 3, title: 'Vaumirain', id:  244, status: 'Active' },
	{ level: 3, title: 'Yerailoi', id:  225, status: 'Active' },
	{ level: 4, title: 'Agomeux', id:  1394, status: 'Active' },
	{ level: 4, title: 'Rachon', id:  265, status: 'Active' },
	/* Soldat */
	{ level: 1, title: 'Agereux', id:  109, status: '' },
	{ level: 1, title: 'Ageuille', id:  138, status: '' },
	{ level: 1, title: 'Agigny', id:  39, status: '' },
	{ level: 1, title: 'Agonnet', id:  165, status: '' },
	{ level: 1, title: 'Agovain', id:  47, status: '' },
	{ level: 1, title: 'Angenay', id:  76, status: '' },
	{ level: 1, title: 'Angillarde', id:  120, status: '' },
	{ level: 1, title: 'Angovain', id:  136, status: '' },
	{ level: 1, title: 'Angovette', id:  124, status: '' },
	{ level: 1, title: 'Anguchette', id:  173, status: '' },
	{ level: 1, title: 'Annarleux', id:  113, status: '' },
	{ level: 1, title: 'Annilald', id:  118, status: '' },
	{ level: 1, title: 'Annilir', id:  148, status: '' },
	{ level: 1, title: 'Auxarleux', id:  115, status: '' },
	{ level: 1, title: 'Auxerain', id:  149, status: '' },
	{ level: 1, title: 'Auxerand', id:  108, status: '' },
	{ level: 1, title: 'Auxignan', id:  177, status: '' },
	{ level: 1, title: 'Auxigny', id:  44, status: '' },
	{ level: 1, title: 'Auxoing', id:  80, status: '' },
	{ level: 1, title: 'Auxovur', id:  98, status: '' },
	{ level: 1, title: 'Azeigne', id:  101, status: '' },
	{ level: 1, title: 'Azillarde', id:  158, status: '' },
	{ level: 1, title: 'Azirette', id:  74, status: '' },
	{ level: 1, title: 'Azuchele', id:  33, status: '' },
	{ level: 1, title: 'Borillarde', id:  153, status: '' },
	{ level: 1, title: 'Borilude', id:  20, status: '' },
	{ level: 1, title: 'Boromald', id:  102, status: '' },
	{ level: 1, title: 'Boruchis', id:  178, status: '' },
	{ level: 1, title: 'Casailir', id:  70, status: '' },
	{ level: 1, title: 'Casillarde', id:  143, status: '' },
	{ level: 1, title: 'Echailele', id:  69, status: '' },
	{ level: 1, title: 'Echarde', id:  73, status: '' },
	{ level: 1, title: 'Echarlert', id:  23, status: '' },
	{ level: 1, title: 'Echarles', id:  106, status: '' },
	{ level: 1, title: 'Echarloi', id:  144, status: '' },
	{ level: 1, title: 'Echault', id:  92, status: '' },
	{ level: 1, title: 'Echillarde', id:  53, status: '' },
	{ level: 1, title: 'Echirand', id:  24, status: '' },
	{ level: 1, title: 'Echiris', id:  82, status: '' },
	{ level: 1, title: 'Ermaigues', id:  38, status: '' },
	{ level: 1, title: 'Ermarlur', id:  54, status: '' },
	{ level: 1, title: 'Ermenay', id:  174, status: '' },
	{ level: 1, title: 'Ermignan', id:  83, status: '' },
	{ level: 1, title: 'Ermiroi', id:  63, status: '' },
	{ level: 1, title: 'Ermiros', id:  164, status: '' },
	{ level: 1, title: 'Gasarland', id:  29, status: '' },
	{ level: 1, title: 'Gasomand', id:  104, status: '' },
	{ level: 1, title: 'Genuchuch', id:  45, status: '' },
	{ level: 1, title: 'Guichon', id:  95, status: '' },
	{ level: 1, title: 'Guidetz', id:  129, status: '' },
	{ level: 1, title: 'Guillier', id:  116, status: '' },
	{ level: 1, title: 'Guimois', id:  183, status: '' },
	{ level: 1, title: 'Guines', id:  31, status: '' },
	{ level: 1, title: 'Guineuve', id:  105, status: '' },
	{ level: 1, title: 'Isailand', id:  55, status: '' },
	{ level: 1, title: 'Isault', id:  141, status: '' },
	{ level: 1, title: 'Iseigne', id:  110, status: '' },
	{ level: 1, title: 'Isilald', id:  94, status: '' },
	{ level: 1, title: 'Isilas', id:  117, status: '' },
	{ level: 1, title: 'Isoing', id:  112, status: '' },
	{ level: 1, title: 'Isonnet', id:  89, status: '' },
	{ level: 1, title: 'Keriras', id:  84, status: '' },
	{ level: 1, title: 'Kerires', id:  91, status: '' },
	{ level: 1, title: 'Keromuch', id:  67, status: '' },
	{ level: 1, title: 'Keronnet', id:  58, status: '' },
	{ level: 1, title: 'Kerovur', id:  142, status: '' },
	{ level: 1, title: 'Lomaigues', id:  86, status: '' },
	{ level: 1, title: 'Lomigny', id:  60, status: '' },
	{ level: 1, title: 'Lomigues', id:  100, status: '' },
	{ level: 1, title: 'Lume', id:  139, status: '' },
	{ level: 1, title: 'Luniere', id:  162, status: '' },
	{ level: 1, title: 'Lunost', id:  157, status: '' },
	{ level: 1, title: 'Luscon', id:  114, status: '' },
	{ level: 1, title: 'Maraigues', id:  51, status: '' },
	{ level: 1, title: 'Mararde', id:  93, status: '' },
	{ level: 1, title: 'Marigues', id:  79, status: '' },
	{ level: 1, title: 'Maromain', id:  97, status: '' },
	{ level: 1, title: 'Maromert', id:  150, status: '' },
	{ level: 1, title: 'Maromoux', id:  146, status: '' },
	{ level: 1, title: 'Osailoi', id:  126, status: '' },
	{ level: 1, title: 'Osenay', id:  34, status: '' },
	{ level: 1, title: 'Parailette', id:  182, status: '' },
	{ level: 1, title: 'Parillarde', id:  88, status: '' },
	{ level: 1, title: 'Paroing', id:  133, status: '' },
	{ level: 1, title: 'Paroult', id:  52, status: '' },
	{ level: 1, title: 'Poideux', id:  36, status: '' },
	{ level: 1, title: 'Poidoux', id:  81, status: '' },
	{ level: 1, title: 'Poilour', id:  77, status: '' },
	{ level: 1, title: 'Poimild', id:  42, status: '' },
	{ level: 1, title: 'Poinurand', id:  27, status: '' },
	{ level: 1, title: 'Poinurette', id:  111, status: '' },
	{ level: 1, title: 'Rachus', id:  57, status: '' },
	{ level: 1, title: 'Racoloi', id:  156, status: '' },
	{ level: 1, title: 'Rafried', id:  123, status: '' },
	{ level: 1, title: 'Ragesnil', id:  41, status: '' },
	{ level: 1, title: 'Ralan', id:  37, status: '' },
	{ level: 1, title: 'Ramoulin', id:  25, status: '' },
	{ level: 1, title: 'Ramuys', id:  135, status: '' },
	{ level: 1, title: 'Rases', id:  75, status: '' },
	{ level: 1, title: 'Rochas', id:  99, status: '' },
	{ level: 1, title: 'Rochaye', id:  48, status: '' },
	{ level: 1, title: 'Rodain', id:  125, status: '' },
	{ level: 1, title: 'Rolan', id:  43, status: '' },
	{ level: 1, title: 'Rome', id:  172, status: '' },
	{ level: 1, title: 'Ronastoux', id:  50, status: '' },
	{ level: 1, title: 'Ronost', id:  140, status: '' },
	{ level: 1, title: 'Ronoy', id:  72, status: '' },
	{ level: 1, title: 'Rosailain', id:  66, status: '' },
	{ level: 1, title: 'Roseraye', id:  30, status: '' },
	{ level: 1, title: 'Rosovas', id:  132, status: '' },
	{ level: 1, title: 'Rotin', id:  176, status: '' },
	{ level: 1, title: 'Sigarlis', id:  137, status: '' },
	{ level: 1, title: 'Sigonne', id:  35, status: '' },
	{ level: 1, title: 'Thibarele', id:  64, status: '' },
	{ level: 1, title: 'Thichon', id:  119, status: '' },
	{ level: 1, title: 'Thicourt', id:  122, status: '' },
	{ level: 1, title: 'Thilir', id:  131, status: '' },
	{ level: 1, title: 'Thimois', id:  152, status: '' },
	{ level: 1, title: 'Thinoy', id:  145, status: '' },
	{ level: 1, title: 'Thinurour', id:  46, status: '' },
	{ level: 1, title: 'Thivaux', id:  26, status: '' },
	{ level: 1, title: 'Torailette', id:  121, status: '' },
	{ level: 1, title: 'Torarde', id:  107, status: '' },
	{ level: 1, title: 'Torerele', id:  103, status: '' },
	{ level: 1, title: 'Torignan', id:  90, status: '' },
	{ level: 1, title: 'Torillarde', id:  78, status: '' },
	{ level: 1, title: 'Toroult', id:  180, status: '' },
	{ level: 1, title: 'Toroute', id:  71, status: '' },
	{ level: 1, title: 'Toulaigues', id:  28, status: '' },
	{ level: 1, title: 'Touligues', id:  128, status: '' },
	{ level: 1, title: 'Tricoleux', id:  147, status: '' },
	{ level: 1, title: 'Tricoloux', id:  127, status: '' },
	{ level: 1, title: 'Tricourt', id:  154, status: '' },
	{ level: 1, title: 'Trifis', id:  87, status: '' },
	{ level: 1, title: 'Trifos', id:  19, status: '' },
	{ level: 1, title: 'Triric', id:  85, status: '' },
	{ level: 1, title: 'Tritos', id:  68, status: '' },
	{ level: 1, title: 'Vaubarir', id:  179, status: '' },
	{ level: 1, title: 'Vaulild', id:  49, status: '' },
	{ level: 1, title: 'Vaumirand', id:  32, status: '' },
	{ level: 1, title: 'Vaunureil', id:  62, status: '' },
	{ level: 1, title: 'Vauscon', id:  40, status: '' },
	{ level: 1, title: 'Vauviers', id:  96, status: '' },
	{ level: 1, title: 'Yerieres', id:  59, status: '' },
	{ level: 1, title: 'Yeromald', id:  61, status: '' },
	{ level: 1, title: 'Yeroute', id:  130, status: '' },
	/* Archer */
	{ level: 2, title: 'Anguchoux', id:  134, status: '' },
	{ level: 2, title: 'Annillarde', id:  202, status: '' },
	{ level: 2, title: 'Annonnet', id:  166, status: '' },
	{ level: 2, title: 'Azarleux', id:  201, status: '' },
	{ level: 2, title: 'Casarde', id:  193, status: '' },
	{ level: 2, title: 'Echilyac', id:  161, status: '' },
	{ level: 2, title: 'Ermelme', id:  235, status: '' },
	{ level: 2, title: 'Ermoute', id:  188, status: '' },
	{ level: 2, title: 'Ermuchert', id:  216, status: '' },
	{ level: 2, title: 'Guicheil', id:  187, status: '' },
	{ level: 2, title: 'Guifoux', id:  229, status: '' },
	{ level: 2, title: 'Guimald', id:  203, status: '' },
	{ level: 2, title: 'Kerarde', id:  196, status: '' },
	{ level: 2, title: 'Kerilette', id:  238, status: '' },
	{ level: 2, title: 'Keroveil', id:  167, status: '' },
	{ level: 2, title: 'Lomelme', id:  230, status: '' },
	{ level: 2, title: 'Lullier', id:  215, status: '' },
	{ level: 2, title: 'Lutin', id:  224, status: '' },
	{ level: 2, title: 'Luvaux', id:  208, status: '' },
	{ level: 2, title: 'Mareigne', id:  209, status: '' },
	{ level: 2, title: 'Maroult', id:  171, status: '' },
	{ level: 2, title: 'Osailuch', id:  163, status: '' },
	{ level: 2, title: 'Osiruch', id:  220, status: '' },
	{ level: 2, title: 'Osombes', id:  199, status: '' },
	{ level: 2, title: 'Osovir', id:  175, status: '' },
	{ level: 2, title: 'Parailur', id:  160, status: '' },
	{ level: 2, title: 'Parault', id:  219, status: '' },
	{ level: 2, title: 'Parignan', id:  191, status: '' },
	{ level: 2, title: 'Poimirert', id:  213, status: '' },
	{ level: 2, title: 'Rabette', id:  155, status: '' },
	{ level: 2, title: 'Racq', id:  211, status: '' },
	{ level: 2, title: 'Radeluys', id:  169, status: '' },
	{ level: 2, title: 'Rades', id:  237, status: '' },
	{ level: 2, title: 'Ragonnet', id:  207, status: '' },
	{ level: 2, title: 'Ravaux', id:  190, status: '' },
	{ level: 2, title: 'Rocheil', id:  214, status: '' },
	{ level: 2, title: 'Rodis', id:  170, status: '' },
	{ level: 2, title: 'Sigoult', id:  218, status: '' },
	{ level: 2, title: 'Thibeux', id:  168, status: '' },
	{ level: 2, title: 'Thideloi', id:  159, status: '' },
	{ level: 2, title: 'Thiduch', id:  184, status: '' },
	{ level: 2, title: 'Thigny', id:  228, status: '' },
	{ level: 2, title: 'Thinost', id:  151, status: '' },
	{ level: 2, title: 'Torereux', id:  212, status: '' },
	{ level: 2, title: 'Toroing', id:  181, status: '' },
	{ level: 2, title: 'Toulieres', id:  198, status: '' },
	{ level: 2, title: 'Touloute', id:  192, status: '' },
	{ level: 2, title: 'Tridaye', id:  195, status: '' },
	{ level: 2, title: 'Triduch', id:  197, status: '' },
	{ level: 2, title: 'Trilan', id:  205, status: '' },
	{ level: 2, title: 'Trissagne', id:  186, status: '' },
	{ level: 2, title: 'Vaumeux', id:  185, status: '' },
	{ level: 2, title: 'Yerilos', id:  222, status: '' },
	{ level: 2, title: 'Yerombes', id:  206, status: '' },
	/* Baliste */
	{ level: 3, title: 'Agovas', id:  227, status: '' },
	{ level: 3, title: 'Ermoing', id:  226, status: '' },
	{ level: 3, title: 'Kerarlus', id:  242, status: '' },
	{ level: 3, title: 'Lucolild', id:  239, status: '' },
	{ level: 3, title: 'Lutel', id:  1012, status: '' },
	{ level: 3, title: 'Luviers', id:  221, status: '' },
	{ level: 3, title: 'Paroute', id:  243, status: '' },
	{ level: 3, title: 'Poises', id:  223, status: '' },
	{ level: 3, title: 'Rosault', id:  231, status: '' },
	{ level: 3, title: 'Rosoing', id:  217, status: '' },
	{ level: 3, title: 'Thifried', id:  232, status: '' },
	{ level: 3, title: 'Thilan', id:  514, status: '' },
	{ level: 3, title: 'Thileux', id:  234, status: '' },
	{ level: 3, title: 'Vautoux', id:  240, status: '' },
	/* Paladin */
	/* Voir cartes actives */
];