try{
	/*Compatibility/Cleanup&co... remove that in future/release Versions*/
	document.cookie = "faarksErrorReporter_undefined=;expires="+new Date().toGMTString();//buggy first version
	document.cookie = "faarksErrorReporter_faarksGrepoTools=;expires="+new Date().toGMTString();//now use .grepolis.com
	window.faark_development = typeof window.faark_development === "undefined" ? false : window.faark_development;
}catch(err){
}

if( typeof faarksErrorReporter === "undefined" ){
	var faarksErrorReporter = {
		version: 1.0,
		config: {
			serverUrl: "http://grepo.faark.de/faarksErrorReporter/current/report.php",
			version: 1.0,
			product: "fgt"
		},
		current: {
			oldOnError: null,
			initiated: false,
			enabled: false,
			active: false
		},
		products: {
			//file: { name, version, author, info, shortName }
		},
		text: {
			langs: {
				"de": {
					fatalError: "Fehler in einer Userscript-Fehler-Funktion!\n\n\nJa das klingt lustig. Nein das ist es nicht!^^\nLeider gab es ein Fehler in FaarksErrorReporter, er wird bis zum nächsten Seitenaufruf abgeschaltet.\n\n\nWICHTIG: Es handelt sich hierbei um eines deiner Userscripts, also nicht den Support damit nerfen!^^\nBitte sei so nett und lass mir (Faark) folgende Infos zukommen:\n--------------------------------------------------------------------------------------------\n",
					config_reseted: "Fehler-Konfig zurückgesetzt...",
					
					guiFlag_product_name_name: "Script-Name",
					guiFlag_product_name_description: "Der Name des Scripts, in dem dieser Fehler aufgetreten ist",
					guiFlag_product_version_name: "Script-Version",
					guiFlag_product_version_description: "Die Version des Scripts, in dem dieser Fehler aufgetreten ist",
					guiFlag_error_message_name: "Fehler-Nachricht",
					guiFlag_error_message_description: "Die eigentliche Fehler-Information...",
					guiFlag_error_file_name: "Fehler-Script",
					guiFlag_error_file_description: "Das genau Script-File, in dem der Fehler aufgetreten ist",
					guiFlag_error_line_name: "Fehler-Zeile",
					guiFlag_error_line_description: "Die genau Zeile, in der der Fehler aufgetreten ist",
					guiFlag_error_stack_name: "Genau Fehler-Position",
					guiFlag_error_stack_description: "Die Funktionsaufrufe, die zu dem Fehler geführt haben...",
					guiFlag_web_location_name: "Web-Addresse",
					guiFlag_web_location_description: "Die URL der aktuellen Website",
					guiFlag_web_document_name: "Dokument-Inhalt",
					guiFlag_web_document_description: "Der komplette inhalt der akutellen Website. Er kann nötig sein, um den Fehler zu finden.",
					guiFlag_web_browser_name: "Browser- / OS-Version",
					guiFlag_web_browser_description: "Infos über Browser und Betriebsystem, incl. Version",
					guiFlag_errorTool_version_name: "Reporter-Version",
					guiFlag_errorTool_version_description: "Die Version des Error-Reporters",
					guiFlag_unknown_name: "[[FLAG]]",
					guiFlag_unknown_description: "Sonstige weitere Infos...",
					
					gui_headline: "Fehler in \"[[PRODUCT_NAME]]\":",
					gui_intro: "In [[PRODUCT_NAME]] (Version [[PRODUCT_VERSION]]; von [[PRODUCT_AUTHOR]]) wurde ein Fehler festgestellt. Bitte hilf ihn zu beseitigen, indem du dem Entwickler Informationen über dieses Problem bereit stellst.",
					gui_send: "Fehlerbericht senden",
					gui_cancel: "Abbrechen",
					gui_close: "Nicht senden",
					gui_toggleSettings: "Einstellungen über das Fehler-Popup anzeigen/ändern",
					gui_setting_showAll: "Diesen Fehler beim nächsten Auftreten wieder anzeigen",
					gui_setting_hideThis: "Diesen Fehler bis zum nächsten Update nicht anzeigen",
					gui_setting_hideAll: "Fehler in [[PRODUCT_NAME]] bis zum nächsten update nicht anzeigen",
					gui_toggleData: "Übertragene Daten anzeigen/ändern",
					gui_toggleComment: "Kommentar zu diesem Fehler schreiben",
					gui_commentDefault: "Schreib dein Kommentar hier rein!",
					
					gui_tooltip_sendAndSave: "Fehlerbericht senden und Alert-Config speichern",
					gui_tooltip_save: "Alert-Config speichern aber keinen Fehlerbericht senden",
					gui_tooltip_close: "Fehlerfenster schließen",
					gui_tooltip_viewData: "Gesendete Daten anzeigen",
					gui_tooltip_hideData: "Gesendete Daten ausblenden",
					gui_tooltip_viewConfig: "Benachrichtigungsconfiguration anzeigen",
					gui_tooltip_hideConfig: "Benachrichtigungsconfiguration ausbelnden",
					gui_tooltip_saveConfigInfo: "Um diese Config zu speichern müssen Cookies aktiv sein!",
					gui_tooltip_toggleComment:"Du hast ne Idee, was diesen Fehler verursachen könnte? Alle Infos könnten hilfreich sein!"
				},
				"fr": {
					fatalError: "Une erreur à été signalé dans un rapport concernant un de vos script !\n\n\nLe son est plaisant, oui ? Non il ne l'est pas >_<' !^^\nNavré mais il y un bug dans FaarksErrorReporter, il est maintenant désactivé jusqu'à la prochaine action.\n\n\nIMPORTANT: Ce message à été causé par l'un de vos script, ne venez pas nous ennuyer avec ça!^^\nSVP soyez sympa et envoyez moi suivre les informations à : (Faark at forum.grepolis.de or faark@grepolis.de) \n--------------------------------------------------------------------------------------------\n",
					config_reseted: "Réinitialiser la configuration...",

					guiFlag_product_name_name: "Nom du script",
					guiFlag_product_name_description: "Nom du script ou l'erreur est survenue",
					guiFlag_product_version_name: "Version du script",
					guiFlag_product_version_description: "Version du script ou l'erreur est survenue",
					guiFlag_error_message_name: "Message d'erreur",
					guiFlag_error_message_description: "Information sur l'erreur survenue...",
					guiFlag_error_file_name: "Fichier d'erreur",
					guiFlag_error_file_description: "Le fichier exact ou l'erreur est survenue",
					guiFlag_error_line_name: "Erreur à la ligne",
					guiFlag_error_line_description: "L'erreur est survenue à la ligne",
					guiFlag_error_stack_name: "Emplacement exact de l'erreur",
					guiFlag_error_stack_description: "Trace complète de l'erreur...",
					guiFlag_web_location_name: "Adresse WEB",
					guiFlag_web_location_description: "URL du site ou vous vous trouvez",
					guiFlag_web_document_name: "Contenu du site",
					guiFlag_web_document_description: "Le contenu complet du site ou vous vous trouvez peut grandement nous aider, en particulier lors d'une mise à jour de Grepolis.",
					guiFlag_web_browser_name: "Navigateur & Système d'exploitation",
					guiFlag_web_browser_description: "Information sur votre navigateur & votre système d'exploitation",
					guiFlag_errorTool_version_name: "Version du rapport",
					guiFlag_errorTool_version_description: "Version du journal d'erreur",
					guiFlag_unknown_name: "[[FLAG]]",
					guiFlag_unknown_description: "Informations diverses...",

					gui_headline: "Erreur de \"[[PRODUCT_NAME]]\":",
					gui_intro: "Une erreur est survenue dans [[PRODUCT_NAME]] (Version [[PRODUCT_VERSION]]; ecrit par [[PRODUCT_AUTHOR]])! Aidez moi, s'il vous plait, à résoudre le problème en soumettant le rapport d'erreur à son dévellopeur.",
					gui_send: "Envoyer le rapport",
					gui_cancel: "Annuler",
					gui_close: "Ne pas envoyer",
					gui_toggleSettings: "Montrer/Cacher la configuration des alertes",
					gui_setting_showAll: "Signaler à nouveau cette erreur si elle se reproduit à l'avenir",
					gui_setting_hideThis: "Ne plus signaler cette erreur jusqu'à la prochaine version",
					gui_setting_hideAll: "Ne plus afficher l'erreur dans [[PRODUCT_NAME]] jusqu'à la prochaine mise à jour",
					gui_toggleData: "Afficher/cacher le rapport à soumettre",
					gui_toggleComment: "Écrire un commentaire sur ce rapport",
					gui_commentDefault: "Écrivez votre commentaire ici...",

					gui_tooltip_sendAndSave: "Envoyer le rapport d'erreur et sauvegarder la configuration des alertes",
					gui_tooltip_save: "Sauvegarder la configuration sans envoyer le rapport",
					gui_tooltip_close: "Fermer la fenetre d'alerte",
					gui_tooltip_viewData: "Afficher le rapport soumit",
					gui_tooltip_hideData: "Caché le rapport soumit",
					gui_tooltip_viewConfig: "Configuration d'alerte",
					gui_tooltip_hideConfig: "Cacher la configuration",
					gui_tooltip_saveConfigInfo: "Vous devez activer vos coockies pour sauvegarder les options!",
					gui_tooltip_toggleComment:"Avez vous des informations supplementaire sur la cause de ces erreurs? Toute information nous sera précieuse!"
				},
				"en": {
					fatalError: "Error in one of your Userscript's Error-Reporter!\n\n\nSounds funny, jay? No it isn!^^\nSorry, but there was an Error in FaarksErrorReporter, it is disabled until next page-load.\n\n\nIMPORTANT: This message is caused by one of your userscripts, do not annoy the support with that!^^\nPlease be that pleasant an send me (Faark at forum.grepolis.de or faark@grepolis.de) the following info:\n--------------------------------------------------------------------------------------------\n",
					config_reseted: "Error-Config resetted...",
					
					guiFlag_product_name_name: "Script-Name",
					guiFlag_product_name_description: "The name of script in which the error occurred",
					guiFlag_product_version_name: "Script-Version",
					guiFlag_product_version_description: "The version of the script in which the error occurred",
					guiFlag_error_message_name: "Error-Message",
					guiFlag_error_message_description: "The actual error information...",
					guiFlag_error_file_name: "Error-File",
					guiFlag_error_file_description: "The exact script file in which the error occurred",
					guiFlag_error_line_name: "Error-Line",
					guiFlag_error_line_description: "The exact line where the error occurred",
					guiFlag_error_stack_name: "Exact error-location",
					guiFlag_error_stack_description: "The whole error-tracer...",
					guiFlag_web_location_name: "Web-Addresss",
					guiFlag_web_location_description: "The URL of the current website",
					guiFlag_web_document_name: "Document-Content",
					guiFlag_web_document_description: "The whole content of the current website can be usefull. eg in case of an grepo-update.",
					guiFlag_web_browser_name: "Browser/OS-Version",
					guiFlag_web_browser_description: "Information about your browser & operating system",
					guiFlag_errorTool_version_name: "Reporter-Version",
					guiFlag_errorTool_version_description: "Version of that Error-Reporter",
					guiFlag_unknown_name: "[[FLAG]]",
					guiFlag_unknown_description: "Other additional info...",
					
					gui_headline: "Error in \"[[PRODUCT_NAME]]\":",
					gui_intro: "There was an error in [[PRODUCT_NAME]] (Version [[PRODUCT_VERSION]]; written by [[PRODUCT_AUTHOR]])! Please help resolve that error by submiting usefull data about that problem to the developer.",
					gui_send: "Send Report",
					gui_cancel: "Cancel",
					gui_close: "Dont send",
					gui_toggleSettings: "Show/hide notify-config-panel",
					gui_setting_showAll: "Show this error again, in case it occurs in the future",
					gui_setting_hideThis: "Dont show this error til next update",
					gui_setting_hideAll: "Dont show errors in [[PRODUCT_NAME]] til next update",
					gui_toggleData: "Show/hide data to submit",
					gui_toggleComment: "Add a comment to that error",
					gui_commentDefault: "Write your comment here...",
					
					gui_tooltip_sendAndSave: "Send error report and save the Alert Config",
					gui_tooltip_save: "Save Alert Config but do not send error report",
					gui_tooltip_close: "Close Error Window",
					gui_tooltip_viewData: "Show Sent Data",
					gui_tooltip_hideData: "Hide Sent Data",
					gui_tooltip_viewConfig: "Alert Config Profile",
					gui_tooltip_hideConfig: "Hide Alert Config Profile",
					gui_tooltip_saveConfigInfo: "In order to save this config cookies have to be activated!",
					gui_tooltip_toggleComment:"Do you have any idea what could have cause this error? Any information you may have would be helpful!"
				}
			},
			initiated: false,
			defaultLangs: [ "en", "de" ],
			get: function( index, data, fatal ){
				if( fatal || (typeof faarksTextSelection === "undefined") ){
					for( var i = 0; i < this.defaultLangs.length; i++ ){
						if( this.langs[this.defaultLangs[i]] && this.langs[this.defaultLangs[i]][index] ){
							var text = this.langs[this.defaultLangs[i]][index];
							if( data ){
								for( var d in data ){
									var p = new RegExp("\\[\\["+d+"\\]\\]","i");
									var oldText;
									do{
										oldText = text;
									}while( oldText != ( text = text.replace( p, data[d] ) ) );
								}
							}
							return text;
						}
					}
				}else{
					if( !this.initiated ){
						faarksTextSelection.init( "fer", "Faarks Error Reporter", this.langs );
						this.initiated = true;
					}
					return faarksTextSelection.get( "fer", index, data );
				}
			}
		},
		upload: function(data){
			var form = $("<form method='POST' action='"+this.config.serverUrl+"'></form>");
			$("body").append( form );
			for( var i in data ){
				form.append( "<input type='hidden' name='"+i+"' value='"+escape(data[i])+"' />" );
			}
			form.submit();
		},
		errorConfig: {
			domain: null,
			reset: function(){
				for( var i in faarksErrorReporter.products ){
					this.set( i, "", -1 );
					faarksErrorReporter.products[i].errorConfig = undefined;
				}
				HumanMessage.success( fer.text.get("config_reseted") );
			},
			load: function( productId ){
				var prod = faarksErrorReporter.products[productId];
				prod.errorConfig = [];//default... show all errors
				var c_name = "faarksErrorReporter_"+prod.shortName;
				if (document.cookie.length>0){//cookieFnc by w3s integrated
					c_start=document.cookie.indexOf(c_name + "=");
					if (c_start!=-1){
						c_start=c_start + c_name.length+1;
						c_end=document.cookie.indexOf(";",c_start);
						if (c_end==-1)
							c_end=document.cookie.length;
						var text = unescape(document.cookie.substring(c_start,c_end));
						var data = text.split(" ");
						var vers = /v([0-9]+\.?[0-9]+)/.exec( data[0] );
						if( vers ){
							if( Number( vers[1] ) < prod.version ){
								this.set( productId, "", -1 );
							}else{
								if( data.length > 1 ){
									prod.errorConfig = data.slice( 1 );
								}else{
									prod.errorConfig = true;
								}
								return;
							}
						}
					}
				}
			},
			set: function( productId, lineNumber, expiredays ){
				var prod = faarksErrorReporter.products[productId];
				var c_name = "faarksErrorReporter_"+prod.shortName;
				var value =  "v"+prod.version.toString() + 
					( arguments.length > 1 ? 
						" "+( (prod.errorConfig instanceof Array) ? 
							prod.errorConfig.concat(lineNumber).join(" ") : 
							lineNumber.toString() ) :
						"" );
				expiredays = expiredays ? expiredays : 21;
				//setCookie-Fnc by w3s
				var exdate=new Date();
				exdate.setDate(exdate.getDate()+expiredays);
				document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+";domain=.grepolis.com";
				this.load( productId );
			},
			get: function( productId, lineNumber ){// true: do not report/cancel error report
				var prod = faarksErrorReporter.products[productId];
				if( !prod.errorConfig )
					this.load( productId );
				if( prod.errorConfig === true )
					return true;
				else if( prod.errorConfig instanceof Array ){
					return $.inArray(lineNumber.toString(),prod.errorConfig)>-1;
				}else{
					throw new Error("Unknown Error-Config: ["+typeof prod.errorConfig+"] " + prod.errorConfig.toString());
				}
			}
		},
		gui: {
			current: {
				dataCache: null,
				pid: null
			},
			dataFlags: { /* {name,description[,required][[,loaded[by script!]]]} *EDIT*: NAME/DESCRIPTON NOW ADDED BY LANG-SYS IN initFlags! USES EXACTLY guiFlag_[name]_name AND guiFlag_[name]_description IN TRANSLATION-CONFIG*/
				product_name: {required:true},
				product_version: {required:true},
				
				error_message:{required:true},
				error_file: {required:true},
				error_line: {required:true},
				error_stack: {required:true},
				
				web_location: {},
				web_document: {},
				web_browser: {},
				
				errorTool_version: {required:true}
			},
			close: function(send, save){
				if( save )
					switch( $("input[name='faarksErrorReporter_showBugMode']:checked").val() ){
						case 'self':
							faarksErrorReporter.errorConfig.set(this.current.pid,this.current.dataCache.error_line);
							break;
						case 'all':
							faarksErrorReporter.errorConfig.set(this.current.pid);
							break;
					}
				var data = {};
				for( var index in this.dataFlags ){
					if( ( $("input[name='faarksBugReporter["+index+"]']:checked").length > 0 ) && (this.current.dataCache[index] !== null) && (this.current.dataCache[index] !== undefined) ){
						data[index] = this.current.dataCache[index];
					}
				}
				data["comment"] = $("#faarksErrorReporter_commentBoxText").val();
				$("#faarksErrorReporter_overlay").remove();
				faarksErrorReporter.current.active = false;
				if( send )
					faarksErrorReporter.upload( data );
			},
			toggleAlertConfig: function(){
				if( $("#faarksErrorReporter_toggelAlertConfig_open").is(":visible") ){
					$("#faarksErrorReporter_toggelAlertConfig_open").hide();
					$("#faarksErrorReporter_toggelAlertConfig_close").show();
				}else{
					$("#faarksErrorReporter_toggelAlertConfig_open").show();
					$("#faarksErrorReporter_toggelAlertConfig_close").hide();
				}
			},
			toggleDataConfig: function(){
				if( $("#faarksErrorReporter_toggelDataConfig_open").is(":visible") ){
					$("#faarksErrorReporter_toggelDataConfig_open").hide();
					$("#faarksErrorReporter_toggelDataConfig_close").show();
				}else{
					$("#faarksErrorReporter_toggelDataConfig_open").show();
					$("#faarksErrorReporter_toggelDataConfig_close").hide();
				}
			},
			toggleCommentBox: function(){
				if( $("#faarksErrorReporter_toggelCommentBox_open").is(":visible") ){
					$("#faarksErrorReporter_toggelCommentBox_open").hide();
					$("#faarksErrorReporter_toggelCommentBox_close").show();
				}else{
					$("#faarksErrorReporter_toggelCommentBox_open").show();
					$("#faarksErrorReporter_toggelCommentBox_close").hide();
				}
			},
			setTooltip: function( text ){
				if( !text )
					text = "&nbsp;";
				$("#faarksErrorReporter_tooltip").html(text);
			},
			createTooltip: function( elements, text ){
				elements.unbind('mouseenter');
				elements.unbind('mouseleave');
				elements.bind('mouseenter',fer_cif(function(){this.setTooltip(text);},this));
				elements.bind('mouseleave',fer_cif(function(){this.setTooltip();},this));
			},
			initCss: function( ){
				if( $("#faarksErrorReporter_styles").length <= 0 ){
					$("head").append("<style type='text/css' id='faarksErrorReporter_styles'>\
						#faarksErrorReporter_overlay{ display: block; height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 40000; }\
						#faarksErrorReporter_content{ top: 180px; background-color:#000000; border:3px dashed #FFFFFF; color:#999999; font-size:14px; padding:12px 2px 0; position:absolute; text-align:center; width:550px; z-index:10000; }\
						#faarksErrorReporter_headline{ color:#666666; line-height:normal; }\
						#faarksErrorReporter_background{ visibility: visible; opacity: 0.4; background-image:url(http://grepo.faark.de/faarksInternalToolset/rel/curtain_bg.png); height:100%; width:100%; }\
						#faarksErrorReporter_tooltip{ margin-bottom: 10px; font-style: italic; font-size: 80%; }\
						#faarksErrorReporter_commentBoxText{ margin-left:20px; margin-top:5px; width:90%; height:50px; }\
						.faarksErrorReporter_button { cursor: pointer; display:block; outline-style:none; color:#804000; font-weight:bold; text-decoration:none; }\
						#faarksErrorReporter_mainSubmitButton { font-size:150%; color:#A05010; margin-bottom:4px; }\
						.faarksErrorReporter_button:hover, #faarksErrorReporter_mainSubmitButton:hover { color:#0082BE; };\
					</style>");
				}
			},
			initFlags: function() {
				for( var i in this.dataFlags ){
					var old = this.dataFlags[i];
					if( !old.loaded ){
						var n = fer.text.get( "guiFlag_"+i+"_name" );
						var d = fer.text.get( "guiFlag_"+i+"_description" );
						this.dataFlags[i] = {
							loaded: true,
							name: n?n:fer.text.get( "guiFlag_unknown_name", { flag: i } ),
							description: d?d:fer.text.get( "guiFlag_unknown_description", { flag: i } ),
							required: old.required ? true : false
						};
					}
				}
			},
			init: function( productId, data ){
				faarksErrorReporter.current.active = true;
				this.current.dataCache = data;
				this.current.pid = productId;
				var prod = faarksErrorReporter.products[productId];
				this.initCss();
				this.initFlags();
				//lang-crap
				var prodLang = {};
				for( var i in prod ){
					prodLang["product_"+i]=prod[i];
				}
				var t = function( i, data ){ return fer.text.get.apply( fer.text, [ i, data ? $.extend( data, prodLang ) : prodLang ] ); };

				$("#faarksErrorReporter_overlay").remove();
				$("body").append('<div id="faarksErrorReporter_overlay">\
					<div id="faarksErrorReporter_content" style="left: '+((window.innerWidth-550)/2)+'px;">\
						<h2 id="faarksErrorReporter_headline">'+t("gui_headline")+'</h2><br>\
						<span style="display:block;">\
							'+t("gui_intro")+'\
						</span>\
						<div style="float:right;margin-right:2px" class="faarksErrorReporter_sendButton faarksErrorReporter_button" href="#">'+t("gui_send")+'</div>\
						<div style="clear: both;"></div>\
						<div style="display: block; margin: 20px auto 0px auto; width:500px; text-align: left;">\
							<div class="faarksErrorReporter_button" id="faarksErrorReporter_toggelAlertConfig_open" href="#" style="display:block">+ '+t("gui_toggleSettings")+'</div>\
							<div id="faarksErrorReporter_toggelAlertConfig_close" style="display:none;">\
								<div class="faarksErrorReporter_button" href="#">- '+t("gui_toggleSettings")+'</div><br/>\
								<div style="margin-left:10px;">\
									<label><input type="radio" name="faarksErrorReporter_showBugMode" value="none"> '+t("gui_setting_showAll")+'</label><br/>\
									<label><input type="radio" name="faarksErrorReporter_showBugMode" value="self" checked="checked"> '+t("gui_setting_hideThis")+'</label><br/>\
									<label><input type="radio" name="faarksErrorReporter_showBugMode" value="all"> '+t("gui_setting_hideAll")+'</label><br/>\
								</div>\
							</div>\
							<br/>\
							<div class="faarksErrorReporter_button" id="faarksErrorReporter_toggelDataConfig_open" href="#" style="display:block">+ '+t("gui_toggleData")+'</div>\
							<div id="faarksErrorReporter_toggelDataConfig_close" style="display:none;">\
								<div class="faarksErrorReporter_button" href="#">- '+t("gui_toggleData")+'</div><br/>\
								<div id="faarksErrorReporter_leftDataConfig" style="float:left;margin-left:10px;"></div>\
								<div id="faarksErrorReporter_rightDataConfig" style="float:right;margin-right:10px;"></div>\
								<div style="clear: both;"></div>\
							</div>\
							<br/>\
							<div class="faarksErrorReporter_button"  id="faarksErrorReporter_toggelCommentBox_open" href="#" style="display:block">+ '+t("gui_toggleComment")+'</div>\
							<div id="faarksErrorReporter_toggelCommentBox_close" style="display:none;">\
								<div class="faarksErrorReporter_button" href="#">- '+t("gui_toggleComment")+'</div><br/>\
								<textarea id="faarksErrorReporter_commentBoxText">'+t("gui_commentDefault")+'</textarea>\
							</div>\
						</div>\
						<br/>\
						<div id="faarksErrorReporter_tooltip">&nbsp;</div>\
						<div href="#" class="faarksErrorReporter_sendButton faarksErrorReporter_button" id="faarksErrorReporter_mainSubmitButton">'+t("gui_send")+'</div>\
						<div href="#" class="faarksErrorReporter_saveButton faarksErrorReporter_button" style="position:absolute;bottom:0px;left:4px;">'+t("gui_close")+'</div>\
						<div href="#" class="faarksErrorReporter_cancelButton faarksErrorReporter_button" style="position:absolute;bottom:0px;right:4px;">'+t("gui_cancel")+'</div>\
					</div>\
					<div id="faarksErrorReporter_background"></div>\
				</div>');
				$("#faarksErrorReporter_overlay div:first").css("top", (window.innerHeight - $("#faarksErrorReporter_overlay div:first").height() ) / 2);
				
				$(".faarksErrorReporter_sendButton").click( fer_cif(function(){this.close(true,true);return false;},this) );
				$(".faarksErrorReporter_saveButton").click( fer_cif(function(){this.close(false,true);return false;},this) );
				$(".faarksErrorReporter_cancelButton").click( fer_cif(function(){this.close(false,false);return false;},this) );
				$("#faarksErrorReporter_toggelDataConfig_close .faarksErrorReporter_button, #faarksErrorReporter_toggelDataConfig_open").click( fer_cif(function(){this.toggleDataConfig();return false;},this) );
				$("#faarksErrorReporter_toggelAlertConfig_close .faarksErrorReporter_button, #faarksErrorReporter_toggelAlertConfig_open").click( fer_cif(function(){this.toggleAlertConfig();return false;},this) );
				$("#faarksErrorReporter_toggelCommentBox_close .faarksErrorReporter_button, #faarksErrorReporter_toggelCommentBox_open").click( fer_cif(function(){this.toggleCommentBox();return false;},this) );
				
				this.createTooltip( $(".faarksErrorReporter_sendButton"), t("gui_tooltip_sendAndSave") );
				this.createTooltip( $(".faarksErrorReporter_saveButton"), t("gui_tooltip_save") );
				this.createTooltip( $(".faarksErrorReporter_cancelButton"), t("gui_tooltip_close") );
				this.createTooltip( $("#faarksErrorReporter_toggelDataConfig_open"), t("gui_tooltip_viewData") );
				this.createTooltip( $("#faarksErrorReporter_toggelDataConfig_close .faarksErrorReporter_button"), t("gui_tooltip_hideData") );
				this.createTooltip( $("#faarksErrorReporter_toggelAlertConfig_open"), t("gui_tooltip_viewConfig") );
				this.createTooltip( $("#faarksErrorReporter_toggelAlertConfig_close div"), t("gui_tooltip_saveConfigInfo") );
				this.createTooltip( $("#faarksErrorReporter_toggelAlertConfig_close .faarksErrorReporter_button"), t("gui_tooltip_hideConfig") );
				this.createTooltip( $("#faarksErrorReporter_toggelCommentBox_close, #faarksErrorReporter_toggelCommentBox_open"), t("gui_tooltip_toggleComment") );
				
				var dItems = [];
				for( var index in this.dataFlags ){
					if( (data[index] !== null) && (data[index] !== undefined) ){
						var i = $('<label style="display:block;"><input '+(this.dataFlags[index].required?'disabled="disabled" ':"")+'type="checkbox" name="faarksBugReporter['+index+']" value="on" checked="checked" /> '+this.dataFlags[index].name+'</label>');
						var flagContent = $.trim( data[index].toString().replace(/&/gmi, '&amp;').replace(/"/gmi, '&quot;').replace(/>/gmi, '&gt;').replace(/</gmi, '&lt;') );
						if( flagContent.length > 50 ){
							flagContent = flagContent.substr(0,47)+"...";
						}
						this.createTooltip( i, this.dataFlags[index].description + "<br/><span style=\"font-size:90%;\">Daten: "+flagContent+"</span>");
						dItems.push( i );
					}
				}
				for( var i = 0; i < Math.ceil( dItems.length / 2 ); i++ ){
					$("#faarksErrorReporter_leftDataConfig").append( dItems[i] );
				}
				for( var i = Math.ceil( dItems.length / 2 ); i < dItems.length; i++ ){
					$("#faarksErrorReporter_rightDataConfig").append( dItems[i] );
				}
			}
		},
		//report( exception )
		//report( message, url, line[, stack])
		report: function(){//TODO: ADD non-EXCEPTION-Formats-Support
			try{
				if( !this.current.enabled )
					return;
				var e = arguments.length == 1 ? arguments[0] : undefined;
				if( (typeof e === "object") && (typeof e.message === "string") && (typeof e.fileName === "string") && (!isNaN( Number( e.lineNumber ) ) ) && (typeof e.stack === "string")){//exception
					var e = arguments[0];
					this.report( e.name+": "+e.message, e.fileName, e.lineNumber, e.stack );
				}else if((arguments.length >= 3)&&arguments[0]&&arguments[1]&&!isNaN(Number(arguments[2]))){//message,url,line,stack
					//if( typeof console === "object") console.log("Reporting error... Arugments: %o",arguments);
					var url = arguments[1].toString();
					for( var file in this.products ){
						if( this.errorConfig.get( file, arguments[2] ) )
							return;
						if( url.indexOf( file ) >= 0 ){
							var prod = this.products[ file ];
							var data = {
								error_message: arguments[0],
								error_file: arguments[1],
								error_line: arguments[2],
								error_stack: arguments[3],
								
								product_name: prod.name,
								product_version: prod.version,
								
								web_location: window.location.href,
								web_document: $("html").html(),
								web_browser: navigator.userAgent,
								
								errorTool_version: this.config.version
								
							};
							
							this.gui.init( file, data );
							return;
						}
					}
				}
			}catch(err){
				this.onErrorInError( err );
			}
		},
		onErrorInError: function(ex){//that func is called by error-func's catches and, in case of error
			this.current.enabled = false;
			alert( this.text.get("fatalError",null,true)+ex.name+": "+ex.message+"\nat "+ex.fileName+", line " + ex.lineNumber + "\nStack: "+ (ex.stack?ex.stack:"N/A") );
		},
		onError: function(errorMsg, url, lineNumber){
			try{
				//console.log("err");
				//console.log("ErrorStack: %o",new Error().stack);
				this.report( errorMsg, url, lineNumber );
			}finally{
				if( this.current.oldOnError )
					return this.current.oldOnError.apply( window, arguments );
				return false;
			}
		},
		exec_func: function( fnc, scope, args ){
			try{
				return fnc.apply( scope ? scope : window, args ? args : [] );
			}catch(err){
				faarksErrorReporter.report( err );
			}
		},
		create_func: function( fnc, scope ){
			return function(){
				return faarksErrorReporter.exec_func( fnc, scope, arguments );
			}
		},
		create_internal_func: function( fnc, scope ){
			return function(){
				try{
					if( typeof fnc === "string" )
						eval( fnc );
					else
						return fnc.apply( scope ? scope : window, arguments );
				}catch(err){
					this.onErrorInError( err );
				}
			}
		},
		init: function( fileName, productInfo ){
			if( !$ || (typeof Game === "undefined") )//no jquery/Game -> no valid grepo-side
				return;
			
			productInfo.file = fileName;
			productInfo.shortName = fileName.split(".")[0];
			this.products[fileName] = productInfo;
			
			// default class init
			if( this.current.initiated )
				return;
			var self = this;
			this.current.oldOnError = window.onerror;
			window.onerror = function (){self.onError.apply(self,arguments);};//diese Fehler-Funktion ist echt scheisse, gibt keine zeile und nur ne drecks message!
			this.current.enabled = true;
			this.current.initiated = true;
		}
	};
	var fer = faarksErrorReporter;
	function fer_go ( fnc, scope, args ){
		return faarksErrorReporter.exec_func(fnc,scope,args);
	}
	function fer_cf ( fnc, scope, args ){
		if( (typeof fnc !== "function") || (typeof scope !== "object") )
			throw new Error("Invalid Params ["+fnc+","+scope+","+args+"]!");
		return function(){
			try{
				if( typeof fnc === "string" )
					eval( fnc );
				else
					return fnc.apply( scope ? scope : window, args ? args : arguments );
			}catch(err){
				faarksErrorReporter.report( err );
			}
		}
	}
	function fer_cif ( fnc, scope ){
		return faarksErrorReporter.create_internal_func( fnc, scope );
	}
}
faarksErrorReporter.init( "faarksGrepoTools.js", { name:"Faark's Grepo-Tools", version: 0.71, author: "Faark" } );
function fer_test(){
	//javascript:faarksErrorReporter.errorConfig.reset();alert(faarksTextSelection.get("test"));void(0);
	faarksErrorReporter.errorConfig.reset();
	faarksErrorReporter.report( new Error("This is an Test-Error!") );
}
try{

	if( typeof faarksTextSelection === "undefined" ){
		var faarksTextSelection = {
			
			version: 1.0,
			defaultUsage: ["en","de"],
			lastData: null,
			lang: null,
			replacements: [
				{ find: /\[\[now\]\]/gi, replace: function(){return new Date().toLocaleString();} },
				{ find: /\[\[by\]\]/gi, replace: function(){return faarksTextSelection.get("sys","by",faarksTextSelection.lastData);} },
				{ find: /\[\[what\]\]/gi, replace: function(){return "";} },
				{ find: /\[\[id\]\]/gi, replace: function(){return "";} }
			],
			projects: {
				sys: {
					name: "Default Strings",
					replacements: [],
					strings: {
						en: {
							by: "<span [[ID]]style='float:right;color: gray;font-size: 60%;'>[[WHAT]]by Faark</span>"
						}
					}
				}
			},
			
			
			generate: function( sysname, lang, index, data ){
				this.lastData = data;
				var text = this.projects[sysname].strings[lang][index];
				var all = this.projects[sysname].replacements;
				if( data ){
					var datas = [];
					if( data.length ){
						datas = data;
					}else for( var i in data ){
						datas.push({ find: new RegExp("\\[\\["+i+"\\]\\]","gi"), replace: data[i] });//i.replace("[","\[").replace(")","\"")
					}
					all = datas.concat( all );
				}
				for( var i = 0; i < all.length; i++ ){
					text = text.replace( all[i].find, all[i].replace );
				}
				return text;
			},
			get: function( sysname, index, data ){
				if(!this.lang){
					//1st startup
					var lng = /([a-zA-Z]+)[0-9]*\./.exec( document.location.href );
					this.lang = lng ? lng[1] : this.defaultUsage[0];
					this.projects.sys.replacements = this.projects.sys.replacements.concat( this.replacements );
				}
				if( !this.projects[sysname] ){
					throw new Error("No data for project ["+sysname+"] aviable...");
				}
				var langs = this.projects[sysname].strings;
				if( langs[this.lang] && langs[this.lang][index] ){
					return this.generate( sysname, this.lang, index, data );
				}else{
					for( var i = 0; i < this.defaultUsage.length; i++ ){
						if( langs[this.defaultUsage[i]] && langs[this.defaultUsage[i]][index] ){
							return this.generate( sysname, this.defaultUsage[i], index, data );
						}
					}
					throw new Error("String ["+index+"] not found in ["+this.projects[sysname].name+"]'s active Languages!");
				}
			},
			// init( sysname, name, lang, langdata[, replacements])
			// init( sysname, name, langsdata[, replacements])
			init: function( sysname, name, a, b, c ){
				var rep=[],langdata = {};
				if( typeof a === "string" ){
					langdata[a]=b;
					rep=c?c:rep;
				}else{
					langdata=a;
					rep=b?b:rep;
				}
				this.projects[sysname] = {
					name: name,
					replacements: rep.concat( this.replacements ),
					strings: langdata
				};
			}
		};
	}
	
	faarksTextSelection.init( "fgt", "Faarks Grepo Tools", {
		de: {
			townid_text: " (Id: [[TOWNID]])",
			
			toolbuttons_statsPopup: "Öffnet das Profil von diesem<br/>Spieler auf GrepoStats.com<br/><span style='float:right;color: gray;font-size: 60%;'>by Faark & Marvinho</span>",
			toolbuttons_toolsPopup: "Öffnet das Profil von diesem<br/>Spieler auf GrepoTools.de<br/><span style='float:right;color: gray;font-size: 60%;'>by Grex & Faark</span>",
			toolbuttons_statsLang: "de",
			
			favorCalc_favorHeadline: "<h4>Gunst</h4>",
			favorCalc_defaultItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-  Production per hour: [[OUTPUT]]<br/>-  Voll in etwa [[FULL_IN]]h<br/>-  Voll am [[FULL_AT]]",
			favorCalc_fullItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-  Production per hour: [[OUTPUT]]<br/>-  Gunstspeicher ist voll!!!",
			
			enhancedSim_stringOutput: "Link mit gespeicherten Sim-Daten (Benötigt FaarksGrepoTools):\n\n\n[[ADDRESS]]",
			enhancedSim_stringInputHeadline: "Bitte kopier hier die URL mit den Sim-Daten rein:",
			enhancedSim_invalidInputString: "Fehler: Diese URL enthält keine Sim-Daten in einem gültigen Format!",
			enhancedSim_caputreButtonPopup: "Diese Einheiten in den Simulator einfügen.<br/>[[BY]]",
			
			enhancedSim_swapSideText: "Seiten Tauschen",
			enhancedSim_swapSidePopup: "Tauscht die Seiten der Einheiten...<br/>Aus Verteidigen werden Angreiffer,<br/>letztere zu Verteidigen<br/>[[BY]]",
			
			enhancedSim_getSimUrl_text: "Sim. Speichern",
			enhancedSim_getSimUrl_popup: "Zeigt dir einen Link, der den Simulator<br/>mit den diesen Einstellungen öffnet.<br/>[[BY]]",
			
			enhancedSim_openSimLink_text: "Sim. Laden",
			enhancedSim_openSimLink_popup: "Importiert einen Sim-Data-Link in den aktuellen Simulator.<br/>So können zB zwei verschiedene Daten-Quellen geöffnet werden.<br/>[[BY]]",
			
			academyTimeleft_resItem: "Resourcen verfügbar in [[IN]] Stunden,<br/>am [[AT]]<br/>",
			academyTimeleft_doneIn: "<h4>[[ORDER]]</h4>Fertig erforscht am [[DONE_AT]]<br/>[[BY]]",
			
			
			walkDuro_fullBy: "<span style='float:right;color: gray;font-size: 50%;'>Laufzeiten by Grex & Faark</span>",
			walkDuro_onError: "<span style=\"font-size:50%;color: red;\">Fehler beim Lade der Laufzeiten</span>",
			walkDuro_onLoading: "<span style=\"font-size:80%;color: gray;\">Lade Laufzeiten <img src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\" style=\"width: 10px; height: 10px; display: inline; position: relative; top: 1px;\"/></span>",
			
			quickCast_popup: "Das Bild zeigt den Gott, den du<br/>für diese Stadt gewählt hast.<br/><br/>Wenn du auf es klickst, kannst du<br/>direkt auf diese Stadt zaubern<br/>[[BY]]",
			
			extTownlist_errorMsg: "Fehler beim ermitteln der Dorf-Koordinaten",
			extTownlist_infoPopup: "Öffnet das Info-Fenster zu dieser<br/>Stadt. Sehr praktisch, um direkt<br/>Einheiten oder Ressourcen zu<br/>verschicken.<br/>[[BY]]",
			extTownlist_gotoMap: "Öffnet die Stadt auf der Karte.<br/><span style=\"text-align:right;float: right; color: gray; font-size: 60%;\">by Faark<br/>prior/similar implemention by Kapo el Ligno</span>",
			extTownlist_gotoOnMap: "Scrollt direkt zu dieser Stadt,<br/>ohne die Seite neu zu laden.<br/><i style=\"font-size: 70%\">(Nur auf der Map!)</i><br/>[[BY]]",
			
			paginator_defaultPopup: "Gehe direkt zu einer Seite,<br/>indem du sie hier ein gibst<br/>und Enter drückst.<br/>[[BY]]",
			paginator_confirmPopup: "Zur gewählten Seite gehen<br/>[[BY]]",
			paginator_cancelPopup: "Abbrechen und anfangs-<br/>Seite wieder einfügen<br/>[[BY]]",
			
			gotoLastForumPage_popup: "Gehe zur letzten Seite ([[PAGE]])<br/>[[BY]]",
			
			
			
			moralInPopup_loadingMoralPopupLine: "<td><img style=\"width:10px;height:10px;float:left;padding: 1pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"></td><td><span style=\"font-size:80%; color:grey;\">Lade Moral...</span></td>",
			moralInPopup_moralPopupLine: "<td><img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 1px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"></td><td>Moral: [[MORAL]]%</span></td>",
			moralInPopup_townInfo_error_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 1px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Fehler beim Laden der Moral :(",
			moralInPopup_townInfo_error_popup: "Leider ist beim Laden der Moral<br/>folgender Fehler aufgetreten:<br/>[[ERRORTEXT]]<br/><br/>Sorry :([[BY]]",
			moralInPopup_townInfo_loading_text: "<img style=\"width:10px;height:10px;float:left;padding: 2pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"> Moral wird geladen...",
			moralInPopup_townInfo_loading_popup: "Die Moral wird von Grex's Server<br/>gelagen, bitte warten...[[BY]]",
			moralInPopup_townInfo_moral_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 1px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Moral: [[MORAL]]%",
			moralInPopup_townInfo_moral_popup: "Diese Moral wirst du vorraussichtlich haben,<br/>wenn du diese Stadt angreiffst.<br/><br/>Aber wie üblich sind alle Angaben ohne Gewähr,<br/>va. kürzliche Änderungen kennt der<br/>Grex's Moral-Server vl noch nicht drin.[[BY]]"

		},
		en: {
			townid_text: " (Id: [[TOWNID]])",
			
			toolbuttons_statsPopup: "Opens the players profile<br/>on GrepoStats.com<br/><span style='float:right;color: gray;font-size: 60%;'>by Faark & Marvinho</span>",
			toolbuttons_toolsPopup: "Opens the players profile<br/>on GrepoTools.de<br/><span style='float:right;color: gray;font-size: 60%;'>by Grex & Faark</span>",
			toolbuttons_statsLang: "www",
			
			favorCalc_favorHeadline: "<h4>Favor</h4>",
			favorCalc_defaultItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-Production per hour: [[OUTPUT]]<br/>-Full in: [[FULL_IN]] hours:minutes<br/>-Full on [[FULL_AT]]",
			favorCalc_fullItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-Production per hour: [[OUTPUT]]<br/>-Favor is Full!!!",
			
			enhancedSim_stringOutput: "Link containing the sim-data (requires FaarksGrepoTools):\n\n\n[[ADDRESS]]",
			enhancedSim_stringInputHeadline: "Please insert the url containing the sim-data here:",
			enhancedSim_invalidInputString: "Error: That link does not contain sim-data in a valid format!",
			enhancedSim_caputreButtonPopup: "Inserts units into the sim.<br/>[[BY]]",
			
			enhancedSim_swapSideText: "Unit Swapper",
			enhancedSim_swapSidePopup: "Switches the units in the simulator<br/>On the second click, the attacker<br/>will become defender as the old<br/>defener becomes the attacker.<br/><br/>(Deffender <==> Attacker)<br/>[[BY]]",
			
			enhancedSim_getSimUrl_text: "Sim-Data Link",
			enhancedSim_getSimUrl_popup: "Shows a link that includes these<br/>current simulator-settings. When<br/>it is copied and introduced the<br/>simulator will then open with<br/>the old input settings.<br/>[[BY]]",
			
			enhancedSim_openSimLink_text: "Load Sim-Data",
			enhancedSim_openSimLink_popup: "Import sim-data from a link<br/>into the current simulator.<br/>(you can add data from<br/>another data-source)<br/>[[BY]]",
			
			academyTimeleft_resItem: "Resources available in [[IN]]h,<br/>on [[AT]]<br/>",
			academyTimeleft_doneIn: "<h4>[[ORDER]]</h4>Resarch done at [[DONE_AT]]<br/>[[BY]]",
			
			
			walkDuro_fullBy: "<span style='float:right;color: gray;font-size: 50%;'>Way-duration by Grex & Faark</span>",
			walkDuro_onError: "<span style=\"font-size:50%;color: red;\">Error loading way-duration</span>",
			walkDuro_onLoading: "<span style=\"font-size:80%;color: gray;\">Loading way-duration <img src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\" style=\"width: 10px; height: 10px; display: inline; position: relative; top: 1px;\"/></span>",
			walkDuro_offline: "<span style=\"font-size:50%;color: red;\">Way-duration offline for that server</span>",
			
			quickCast_popup: "The picture shows the God<br/>that this city has elected.<br/><br/>If you click on it, you can <br/>bring up the spell caster<br/>for the current city.<br/>[[BY]]",
			
			extTownlist_errorMsg: "Error getting town-coordinates",
			extTownlist_infoPopup: "Opens the info-popup for the current town.<br/>Usefull to send units or ressources<br/>in your empire.<br/>[[BY]]",
			extTownlist_gotoMap: "Opens the map with that town.<br/><span style=\"text-align:right;float: right; color: gray; font-size: 60%;\">by Faark<br/>prior/similar implemention by Kapo el Ligno</span>",
			extTownlist_gotoOnMap: "Scrolls directly to that town,<br/>without reloading the page.<br/><i style=\"font-size: 40%\">(Only while on map!)</i><br/>[[BY]]",
			
			paginator_defaultPopup: "Go to a specific page...<br/>just slide the bar then<br/>click the checkmark.<br/>[[BY]]",
			paginator_confirmPopup: "Go to the selected page<br/>[[BY]]",
			paginator_cancelPopup: "Cancel and stay on this page<br/>[[BY]]",
			
			gotoLastForumPage_popup: "Go to the last page ([[PAGE]])<br/>[[BY]]",
			
			gotoTempleWhenNoGod_popup: "There is no god set in this town<br/><br/>Click here to go to the temple to choose one...<br>[[BY]]",
			
			getForumLink_popup: "The Link to that Grepo-Forum contains special chars,<br/>that's why you cant post it in e.g. other forums.<br/><br/>Click here to get a link with working chars...<br/>[[BY]]",
			
			
			moralInPopup_loadingMoralPopupLine: "<td><img style=\"width:10px;height:10px;float:left;padding: 2pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"></td><td><span style=\"font-size:80%; color:grey;\">Loading Moral...</span></td>",
			moralInPopup_moralPopupLine: "<td><img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 1px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"></td><td>Moral: [[MORAL]]%</span></td>",
			moralInPopup_townInfo_error_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 2px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Error loading Moral :(",
			moralInPopup_townInfo_error_popup: "There was an Error while loadin Moral:<br/>[[ERRORTEXT]]<br/><br/>Sorry :([[BY]]",
			moralInPopup_townInfo_loading_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"> Loading Moral...",
			moralInPopup_townInfo_loading_popup: "Moral is loading from a Server,<br/>please wait...[[BY]]",
			moralInPopup_townInfo_moral_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 2px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Moral: [[MORAL]]%",
			moralInPopup_townInfo_moral_popup: "That is the moral, u should have when<br/>attacking that town. No liability assumed! ;)<br/>Changes in the last time are may not<br/>calculated by the Moral-Server.[[BY]]"
		},
		fr: {
			townid_text: " (Id: [[TOWNID]])",

			toolbuttons_statsPopup: "Afficher le profil du joueur<br/>sur GrepoStats.com<br/><span style='float:right;color: gray;font-size: 60%;'>par Faark & Marvinho</span>",
			toolbuttons_toolsPopup: "Afficher le profil du joueur<br/>sur GrepoTools.de<br/><span style='float:right;color: gray;font-size: 60%;'>par Grex & Faark</span>",
			toolbuttons_statsLang: "fr",

			favorCalc_favorHeadline: "<h4>Faveur</h4>",
			favorCalc_defaultItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-Production horaire: [[OUTPUT]]<br/>-Plein dans: [[FULL_IN]] heures:minutes<br/>-Plein le [[FULL_AT]]",
			favorCalc_fullItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-Production horaire: [[OUTPUT]]<br/>-Faveur Maximum!!!",

			enhancedSim_stringOutput: "Lien contenant les données actuelles du simulateur  (nécessite FaarksGrepoTools):\n\n\n[[ADDRESS]]",
			enhancedSim_stringInputHeadline: "Coller le lien des données du simulateur:",
			enhancedSim_invalidInputString: "Erreur: Le lien ne comporte pas des données valide!",
			enhancedSim_caputreButtonPopup: "Insérer les unités dans le simulateur.<br/>[[BY]]",

			enhancedSim_swapSideText: "Echanger",
			enhancedSim_swapSidePopup: "Inverse la place des unités dans le simulateur.<br/>\
										En cliquant l'attaquant devient le défenseur et<br/>\
										le défenseur devient l'attaquant.<br/><br/>\
										(Defenseur <==> Attaquant)<br/>[[BY]]",

			enhancedSim_getSimUrl_text: "Sauver",
			enhancedSim_getSimUrl_popup: "Créé un lien contenant les donnés du simulateur.<br/>\
										  Ce lien est ensuite collé dans le champ \"Charger\"<br/>\
										  il affichera les données actuelle du simulateur<br/>\
										  gardé en mémoire.<br/>[[BY]]",

			enhancedSim_openSimLink_text: "Charger",
			enhancedSim_openSimLink_popup: "Importer les données du simulateur<br/>\
											à partir du lien précédemment créé.<br/>\
											(vous pouvez insérer des données <br/>\
											provenant d'une autre source)<br/>[[BY]]",

			academyTimeleft_resItem: "Ressources disponible dans : [[IN]] h,<br/>le : [[AT]]<br/>",
			academyTimeleft_doneIn: "<h4>[[ORDER]]</h4>Recherche terminé le : [[DONE_AT]]<br/>[[BY]]",


			walkDuro_fullBy: "<span style='float:right;color: gray;font-size: 50%;'>Temps de route. par Grex & Faark</span>",
			walkDuro_onError: "<span style=\"font-size:50%;color: red;\">Erreur de chargement du temps de route</span>",
			walkDuro_onLoading: "<span style=\"font-size:80%;color: gray;\">Chargement du temps de route<img src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\" style=\"width: 10px; height: 10px; display: inline; position: relative; top: 1px;\"/></span>",
			walkDuro_offline: "<span style=\"font-size:50%;color: red;\">Temps de route desactivé pour ce monde</span>",

			quickCast_popup: "Affiche la divinité vénéré par la ville.<br/><br/>\
							  Cliquez et lancez les forces divine de <br/>\
							  votre choix sur votre ville.<br/>[[BY]]",

			extTownlist_errorMsg: "Erreur de coordonnées",
			extTownlist_infoPopup: "Afficher les informations de cette ville.<br/>\
									Vous pouvez envoyer des ressources où des<br/>\
									unités sur toutes les villes de l'empire.<br/>[[BY]]",
			extTownlist_gotoMap: "Centrer cette ville sur la carte.<br/><span style=\"text-align:right;float: right; color: gray; font-size: 60%;\">par Faark<br/>Version originale par Kapo el Ligno</span>",
			extTownlist_gotoOnMap: "Accédez directement à cette ville,<br/>\
									sans avoir à recharger votre page.<br/><i style=\"font-size: 40%\">(Uniquement sur la carte!)</i><br/>[[BY]]",

			paginator_defaultPopup: "Se rendre à une page précise...<br/>\
									 Faites glisser le curseur jusqu'a<br/>\
									 la page voulu et confirmez.<br/>[[BY]]",
			paginator_confirmPopup: "Confirmer<br/>[[BY]]",
			paginator_cancelPopup: "Annuler<br/>[[BY]]",

			gotoLastForumPage_popup: "Confirmer ([[PAGE]])<br/>[[BY]]",

			gotoTempleWhenNoGod_popup: "Cette ville ne vénère aucun dieu. <br/><br/>\
										Cliquez ici pour vous rendre dans <BR/>\
										le Temple et choisir une divinité.<br>[[BY]]",

			getForumLink_popup: "Ce lien, déstiné au forum interne de Grépolis,<br/>\
								 contient des caractères spéciaux non valide.<br/><br/>\
								 Cliquez ici pour obtenir un lien valide<br/>[[BY]]",


			moralInPopup_loadingMoralPopupLine: "<td><img style=\"width:10px;height:10px;float:left;padding: 2pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"></td><td><span style=\"font-size:80%; color:grey;\">Charger le Moral...</span></td>",
			moralInPopup_moralPopupLine: "<td><img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 1px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"></td><td>Moral: [[MORAL]]%</span></td>",
			moralInPopup_townInfo_error_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 2px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Erreur de chargement :(",
			moralInPopup_townInfo_error_popup: "Une erreur est survenue lors du chargement:<br/>[[ERRORTEXT]]<br/><br/>Désolé :([[BY]]",
			moralInPopup_townInfo_loading_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 5px 0 2px;\" src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\"> Charger le Moral...",
			moralInPopup_townInfo_loading_popup: "Le moral est calculé à partir d'un serveur externe,<br/>Veuillez patienter...[[BY]]",
			moralInPopup_townInfo_moral_text: "<img style=\"width:14px;height:14px;float:left;padding: 1pt 3px 0 2px;\" src=\"http://static.grepolis.com/images/game/place/simulator/morale.png\"> Moral: [[MORAL]]%",
			moralInPopup_townInfo_moral_popup: "Ceci n'est qu'une estimation du moral donné à titre indicatif.<br/>\
												Nous ne pouvons être tenus pour responsable de l'estimation! ;)<br/>\
												Tout changement au cours de l'attaque ne sera évidemment<br/>\
												pas prise en compte par le simulateur.[[BY]]"
		},
		ro: {
			townid_text: " (Id: [[TOWNID]])",
			
			toolbuttons_statsPopup: "Deschide profil acestui<br/>Jucatorii GrepoStats.com<br/><span style='float:right;color: gray;font-size: 60%;'>by Faark & Marvinho</span>",
			toolbuttons_toolsPopup: "Deschide profil acestui<br/>Jucatorii GrepoTools.de<br/><span style='float:right;color: gray;font-size: 60%;'>by Grex & Faark</span>",
			toolbuttons_statsLang: "ro",
			
			favorCalc_favorHeadline: "<h4>Favor</h4>",
			favorCalc_defaultItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-  production per hour: [[OUTPUT]]<br/>-  in ~[[FULL_IN]]h full<br/>-  full on [[FULL_AT]]",
			favorCalc_fullItem: "<b>[[GOD]]: [[FAVOR]]</b><br/>-  production per hour: [[OUTPUT]]<br/>-  Cant store more favor!!!",
			
			enhancedSim_stringOutput: "Link la datele stocate Sim (necesita FaarksGrepoTools):\n\n\n[[ADDRESS]]",
			enhancedSim_stringInputHeadline: "Introduceti link-ul primit:",
			enhancedSim_invalidInputString: "Eroare: URL-ul nu contine date Sim intr-un format valabil !",
			enhancedSim_caputreButtonPopup: "Trupe in Sim inserare<br/>[[BY]]",
			
			enhancedSim_swapSideText: "Interschimba unitati",
			enhancedSim_swapSidePopup: "Introduce unitatile in simulator <br/>La al doilea click, din atacator vor deveni aparator pentru ca  <br/>acesta din urma sa-si apere teritoiul.<br/>[[BY]]",
			
			enhancedSim_getSimUrl_text: "Link-ul pentru date Sim",
			enhancedSim_getSimUrl_popup: "Va arata un link. Cand este introdus, simulatorul <br/>se deschide cu aceste setari.<br/>[[BY]]",
			
			enhancedSim_openSimLink_text: "Configurare cu date Sim",
			enhancedSim_openSimLink_popup: "Importurile unui Sim-Data-Link in simulatorul curent.<br/> Introduceti aici link-ul primit si configurarea va fi incarcata.<br/>[[BY]]",
			
			academyTimeleft_resItem: "Resources available in [[IN]]h,<br/>on [[AT]]<br/>",
			academyTimeleft_doneIn: "<h4>[[ORDER]]</h4>Resarch done at [[DONE_AT]]<br/>[[BY]]",
			
			
			walkDuro_fullBy: "<span style='float:right;color: gray;font-size: 50%;'>Way-duration by Grex & Faark</span>",
			walkDuro_onError: "<span style=\"font-size:50%;color: red;\">Error loading way-duration</span>",
			walkDuro_onLoading: "<span style=\"font-size:80%;color: gray;\">Loading way-duration <img src=\"http://grepo.faark.de/faarksGrepoPicSaver/resources/loading.gif\" style=\"width: 10px; height: 10px; display: inline; position: relative; top: 1px;\"/></span>",
			
			quickCast_popup: "That pic shows the god, the citizens<br/>in that town are praying for.<br/><br/>Click on it to cast on that town<br/>[[BY]]",
			
			extTownlist_errorMsg: "Error getting town-coordinates",
			extTownlist_infoPopup: "Opens the info-popup for the current town.<br/>Usefull to send units or ressources<br/>in your empire.<br/>[[BY]]",
			extTownlist_gotoMap: "Opens the map with that town.<br/><span style=\"text-align:right;float: right; color: gray; font-size: 60%;\">by Faark<br/>prior/similar implemention by Kapo el Ligno</span>",
			extTownlist_gotoOnMap: "Scrolls directly to that town,<br/>without reloading the page.<br/><i style=\"font-size: 40%\">(Only while on map!)</i><br/>[[BY]]",
			
			paginator_defaultPopup: "Du-te direct la o pagina,<br/>click aici pentru a da un<br/>und apasati Enter.<br/>[[BY]]",
			paginator_confirmPopup: "Du-te la pagina selectata<br/>[[BY]]",
			paginator_cancelPopup: "Anulare-<br/>Introduceti din nou pagina<br/>[[BY]]",
			
			gotoLastForumPage_popup: "Go to last page ([[PAGE]])<br/>[[BY]]"
		}
	});
	
	
	String.prototype.format = function(){
		var pattern = /\{\d+\}/g;
		var args = arguments;
		return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
	}

	var faarksGrepoTools = {
		/* util */
		currentWorld: "",
		currentFolder: "",
		currentTownName: "",
		currentLang:  "",
		currentAction: "",
		getString: function(index,data){
			return faarksTextSelection.get("fgt",index,data);
		},
		objectHasPropertys: function( o ){
			for( var i in o )
				return true;
			return false;
		},
		humanReadableDate: function(timestamp, lang){
	/*
	var faarksGrepoTools.humanReadableDate_Strings = {
		"de": {
	//		format: "{0} um {1}",
			today: "heute",
			tomorrow: "morgen",
			day0: "Montag"
		},
		"en": {
			today: "today",
			tomorrow: "tomorrow"
		}
	}*/
			return timestamp.toLocaleString();
		},
		getParams: function( fromLink ){
			if( !fromLink )
				fromLink = document.location.href;
			var reg = /[\?\&]([^\&=]+)=([^\&#]+)/gi;
			var data = {};
			var part = null;
			while( part = reg.exec( fromLink ) ){
				data[ part[1] ] = part[2];
			}
			return data;
		},
		getParam: function(name, fromLink){
			var p = this.getParams( fromLink );
			return typeof p[name] === "undefined" ? null : p[name];
		},
		uidgen: function( length ){
			if(!length)
				length = 32;
			var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
			var id = "";
			for( index = 0; index < length; index++ ){
				id = id + chars.substr(Math.floor(Math.random()*(chars.length-1)),1);
			}
			return id;
		},
		setInterrupt: function( oldObject, oldMethodName, newObject, newMethod, runBeforeInterrupt ){
			var oldMethod = oldObject[oldMethodName];
			oldObject[oldMethodName] = function(){
				var r=undefined,isEx=false;
				if( runBeforeInterrupt )
					fer_go( newMethod, newObject, arguments );
				try{
					r = oldMethod.apply( this, arguments );
				}catch(err){
					r = err;
					isEx = true;
				}
				if( !runBeforeInterrupt )
					fer_go( newMethod, newObject, arguments );
				if( isEx )
					throw r;
				return r;
			}
		},
		
		
		
		
		
		/* modules */
		villageIdToTownInfo: { // add village-id in towninfo-popups
			oldInit: null,
			mousePopup: new MousePopup( faarksTextSelection.get("sys","by",{what:"VillageId "})),
			drawFunc: function () {
				if (($('#townWindow #towninfo_towninfo').length === 1)&&($("#faarksGrepoTools_addedTownId").length === 0)) {
					$('#townWindow #towninfo_towninfo .game_header').append("<span id=\"faarksGrepoTools_addedTownId\">"+fgt.getString("townid_text",{townid: TownInfo.town_id})+"</span>");
					$("#faarksGrepoTools_addedTownId").mousePopup( this.mousePopup );
				}
			},
			init: function(){
				if( (typeof TownInfo === 'object') && (typeof TownInfo.init === 'function') ){
					$('body').ajaxComplete( fer_cf( this.drawFunc, this ) );
				}
			}
		},
		toolButtonsInPlayerProfile: { // Grepo-/GameStats-Button in PlayerProfile...
			playerGrepoStats_toolTip: new MousePopup( faarksTextSelection.get("fgt","toolbuttons_statsPopup") ),
			playerGrepoTools_toolTip: new MousePopup( faarksTextSelection.get("fgt","toolbuttons_toolsPopup") ),
			drawInPopup: function(){
				var el = $('#townWindow .list_item_left a');
				if( el.length === 1 ){
					var id = /player_id=([0-9]+)/.exec(el.attr("href"))[1];
					var el = $('#townWindow .list_item_right');
					if( (el.length === 1) && ($("#townWindow .faarksGrepoTools_shownInGrepoStatsButton").length === 0 ) ){
						var no = $( "<a class=\"faarksGrepoTools_shownInGrepoStatsButton faarksGrepoTools_playerButton\" href=\"http://"+fgt.getString("toolbuttons_statsLang")+".grepostats.com/world/"+faarksGrepoTools.currentWorld+"/player/"+id+"\" target=\"_blank\"></a>" );
						var no2 = $( "<a class=\"faarksGrepoTools_shownInGrepoGameStatsButton faarksGrepoTools_playerButton\" href=\"http://www.grepotools.de/"+faarksGrepoTools.currentWorld+"/details/player/"+id+"\" target=\"_blank\"></a>" );
						el.append( no ).append( no2 );
						el.css( "width", 110 );
						no.mousePopup( this.playerGrepoStats_toolTip );
						no2.mousePopup( this.playerGrepoTools_toolTip );
					}
				}
			},
			initCss: function(){
				$('head').append("<style type=\"text/css\">\
				.faarksGrepoTools_playerButton{\
					margin-left: 3px;\
					position: relative;\
					height: 23px;\
					width: 26px;\
					float: left;\
				}\
				.faarksGrepoTools_shownInGrepoStatsButton{\
					top: 1px;\
					left: 1px;\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_grepostats.png) no-repeat scroll 0 0;\
				}\
				.faarksGrepoTools_shownInGrepoStatsButton:hover{\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_grepostats_hover.png) no-repeat scroll 0 0;\
				}\
				.faarksGrepoTools_shownInGrepoGameStatsButton{\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_gamestats.png) no-repeat scroll 0 0;\
				}\
				.faarksGrepoTools_shownInGrepoGameStatsButton:hover{\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_gamestats_hover.png) no-repeat scroll 0 0;\
				}");
			},
			init: function(){
				this.initCss();
				this.drawInPopup = fer_cf( this.drawInPopup, this );
				
				if( $("#player_buttons").length > 0 ){
					$("#player_buttons").css( "width", 250 );
					var ftmp_pid = Number( /player_id=([0-9]+)/.exec(document.location.href)[1] );
					var no = $( "<a class=\"faarksGrepoTools_shownInGrepoStatsButton faarksGrepoTools_playerButton\" href=\"http://"+fgt.getString("toolbuttons_statsLang")+".grepostats.com/world/"+faarksGrepoTools.currentWorld+"/player/"+ftmp_pid+"\" target=\"_blank\"></a>" );
					var no2 = $( "<a class=\"faarksGrepoTools_shownInGrepoGameStatsButton faarksGrepoTools_playerButton\" href=\"http://www.grepotools.de/"+faarksGrepoTools.currentWorld+"/details/player/"+ftmp_pid+"\" target=\"_blank\"></a>" );
					$("#player_buttons").append( no ).append( no2 );
					no.mousePopup( this.playerGrepoStats_toolTip );
					no2.mousePopup( this.playerGrepoTools_toolTip );
				}
				$("body").ajaxComplete( this.drawInPopup );
			}
		},
		favorCalc: { //Time to full favor -> Favor-Tooltip
			favorData: null,
			newFavorText: null,
			getFavorFormText: function(text){
				var arr = [];
				var regex = /<li>([^\:]+): ?([-+]?[0-9]*\.?[0-9]) ?-([^\:]+): ?([-+]?[0-9]*\.?[0-9])<\/li>/g;
				var ret = null;
				while( ret = regex.exec(text) ){
					arr.push( { 
						god: ret[1], 
						favor: Number(ret[2]), 
						prodText: ret[3],
						output: Number(ret[4])} );
				}
				return arr;
			},
			init: function(){
				this.favorData = this.getFavorFormText( PopupFactory.texts["favor_production"] );
				if( this.favorData.length > 0 ){
					var nft = fgt.getString("favorCalc_favorHeadline")+"<ul>";
					for( var el in this.favorData ){
						var data = this.favorData[el];
						if( data["favor"] >= 500 ){
							nft = nft + "<li>" + fgt.getString("favorCalc_fullItem",data) + "</li>";
						}else{
							var tl = (500-data["favor"])/(data["output"]);
							var ml = Math.floor((tl-Math.floor(tl))*60);
							data.full_in = Math.floor(tl) + ":" + (ml<10?"0"+ml:ml);
							data.full_at = faarksGrepoTools.humanReadableDate(new Date(new Date().getTime() + Math.floor((500-data["favor"])/(data["output"]/3600000)) ))
							nft = nft + "<li>" + fgt.getString("favorCalc_defaultItem",data) + "</li>";
						}
					}
					nft = nft+"</ul><br/>"+faarksTextSelection.get("sys","by");
					this.newFavorText = nft;
					$("#favor").mousePopup(new MousePopup(nft));
				}
			}
		},
		updateDuration: { // Update duration....
			oldFunction: null,
			duroInvalidated: true,
			interval: null,
			duation: null,
			onIntervalUpdate: function(){
				if( this.duroInvalidated ){
					this.duroInvalidated = false;
					var durEl = $("#way_duration");
					if( durEl.length == 0 ){
						window.clearInterval(this.interval);
						this.interval = null;
						this.duation = null;
					}else{
						var result = /\~([0-9]*)\:([0-9]*)\:([0-9]*)/.exec( durEl.text() );
						if( result ){
							this.duation = (((((Number( result[1] ) * 60) + Number( result[2] )) * 60 ) + Number( result[3] ) ) * 1000) - (Layout.client_server_time_diff*1000);
						}else{
							this.duation = null;
						}
					}
				}
				if( this.duation != null ){
					var arrival_in_timezone=new Date((new Date().getTime() + this.duation));
					$("#arrival_time").text("~"+readableDate( new Date(arrival_in_timezone.getTime()-(Timestamp.serverGMTOffset()*1000)), 'asUTC' ));
					var is_night;
					var night_starts_at_hour=Game.night_starts_at_hour+Game.locale_gmt_offset/3600;
					if(Game.night_duration==0){
						is_night=false;
					}else if(night_starts_at_hour+Game.night_duration>24){
						is_night=arrival_in_timezone.getUTCHours()<=(night_starts_at_hour+Game.night_duration-1)%24||arrival_in_timezone.getUTCHours()>=night_starts_at_hour;
					}else{
						is_night=arrival_in_timezone.getUTCHours()<=night_starts_at_hour+Game.night_duration-1&&arrival_in_timezone.getUTCHours()>=night_starts_at_hour;
					}
					if(is_night){
						$('#nightbonus').show();
					}else{
						$('#nightbonus').hide();
					}					
				}
			},
			onDuroUpdate: function(){
				this.duroInvalidated = true;
				if( this.interval == null ){
					this.interval = window.setInterval( this.onIntervalUpdate , 75);
				}
				this.onIntervalUpdate();
			},
			bindDurCounter: function(){
				$('.index_unit').bind('click', this.onDuroUpdate );
				$('.unit_input').bind('keyup', this.onDuroUpdate );
				this.duation = null;
			},
			init: function(){
				if( (typeof( TownInfo ) == "object") && (typeof( TownInfo.bindDurationCounter ) == "function") ){
					this.onIntervalUpdate = fer_cf( this.onIntervalUpdate, this );
					this.onDuroUpdate = fer_cf( this.onDuroUpdate, this );
					faarksGrepoTools.setInterrupt( TownInfo, "bindDurationCounter", this, this.bindDurCounter );
				}
			}
		},
		enhancedSimulator: { //Sim-Details Speichern/Einfügen
			simOpen: typeof( FightSimulator ) == "object",
			input_regExp: /sim\[([^\]]*)\]\[([^\]]*)\]\[([^\]]*)\]/,// /sim(\[([^\]]*)\])?(\[([^\]]*)\])?(\[([^\]]*)\])?/,
			pushModTimeout: null,
			pushModUpdate: function(){
				if( this.pushModTimeout == null ){
					this.pushModTimeout = window.setTimeout(fer_cf(function(){
						this.pushModTimeout = null;
						FightSimulator.closeModsExtended();
					},this), 50);
				}
			},
			setGod: function( side, god_id ){
				if( god_id ){
					$.each($(".place_sim_select_gods .place_symbol"), function(i,el){
						if( $(el).hasClass("place_att")==(side=="att") )
							$(el).parent().find("SELECT").val(god_id);
					});
					FightSimulator.switchGod(side, god_id);
					return true;
				}
				return false;
			},
			pasteUnits: function(side,units){
				var godSet = false;
				var list = $(".place_insert_field");
				for( var i = 0; i < list.length; i++ ){
					var cside = $(list[i]).attr("name").toString().match(/sim\[units\]\[([^\]]*)\]/);
					if( cside && (cside[1]==side) )
						$(list[i]).val("");
				}
				for( var type in units ){
					if( !godSet )
						godSet = this.setGod( side, GameData.units[type].god_id );
					for( var i = 0; i < list.length; i++ ){
						if( $(list[i]).attr("name") == "sim[units]["+side+"]["+type+"]" )
							$(list[i]).val(units[type]);
					}
				}
			},
			pasteMods: function(side,mods){
				var list = $(".place_insert_field, .place_checkbox_field ");
				for( var i = 0; i < list.length; i++ ){
					var cside = $(list[i]).attr("name").toString().match(/sim\[mods\]\[([^\]]*)\]/);
					if( cside && (cside[1]==side) )
						if( $(list[i]).hasClass("place_checkbox_field") )
							$(list[i]).attr('checked', false);
						else
							$(list[i]).val("");
				}
				for( var type in mods ){
					for( var i = 0; i < list.length; i++ ){
						if( $(list[i]).attr("name") == "sim[mods]["+side+"]["+type+"]" )
							if( $(list[i]).hasClass("place_checkbox_field") )
								$(list[i]).attr('checked', mods[type]);
							else
								$(list[i]).val(mods[type]);
					}
				}
				this.pushModUpdate();
			},
			getDataAddress: function(data){
				return window.location.protocol + "//" + window.location.host + url( 'building_place', '', { action: 'simulator', faarksGrepoApplySimData: $.toJSON( data ) } );
			},
			getCurrentMode: function(){
				return $(".place_sim_select_strategies select").val();
			},
			copy: function(){
				var list = $('#place_simulator_form').serializeArray();
				var data = { units: { att: {}, def:{} }, mods:{ att: {}, def: {} } };
				for( var i = 0; i < list.length; i++ ){
					var e = list[i];
					if( e.name == "sim[attack_strategy]" ){
						data['attack_strategy'] = e.value;
					}else{
						var info = this.input_regExp.exec( e.name );
						if( info && (e.value != "" ) ){
							data[info[1]][info[2]][info[3]] = e.value;
						}
					}
				}
				return data;
			},
			getCurrentMods: function(){
				return this.copy()["mods"];
			},
			getCurrentDataAddress: function(){
				return this.getDataAddress( this.copy() );
			},
			open: function(data, noEmptys ){
				if( this.simOpen ){
					if( data.units ){
						if( data.units.att && (!noEmptys || faarksGrepoTools.objectHasPropertys(data.units.att) ) )
							this.pasteUnits( "att", data.units.att );
						if( data.units.def && (!noEmptys || faarksGrepoTools.objectHasPropertys(data.units.def) ) )
							this.pasteUnits( "def", data.units.def );
					}
					if( data.mods ){
						if( data.mods.att && (!noEmptys || faarksGrepoTools.objectHasPropertys(data.mods.att) ) )
							this.pasteMods( "att", data.mods.att );
						if( data.mods.def && (!noEmptys || faarksGrepoTools.objectHasPropertys(data.mods.def) ) )
							this.pasteMods( "def", data.mods.def );
					}
					if( data.attack_strategy )
						$(".place_sim_select_strategies select").val( data.attack_strategy )
				}else{
					window.location = this.getDataAddress( data );
				}
			},
			getSaveLink: function(){
				alert(fgt.getString("enhancedSim_stringOutput",{address:this.getCurrentDataAddress()}));
				return false;
			},
			openSaveLink: function(){
				var url = prompt(fgt.getString("enhancedSim_stringInputHeadline"));
				if( url ){
					var startData = /faarksGrepoApplySimData=([^&]*)/.exec( decodeURIComponent( url ) );
					if( startData )
						startData = $.secureEvalJSON(decodeURIComponent( startData[1] ));
					if( startData || (startData = this.convertOtherFormat1( document.location.href ) ) )
						this.open( startData, true );
					else{
						alert(fgt.getString("enhancedSim_invalidInputString"));
					}
				}
				return false;
			},
			toggleSites: function(){
				var curUnits = this.copy()["units"];
				this.open({ units: { att: curUnits["def"], def: curUnits["att"] } });
				return false;
			},
			addCaptureButtonToDialog: function(data){
				var addButton = $("<a id=\"faarksGrepoApplySimData_dialogButton\" class=\"faarksGrepoApplySimData_captureSidebarButton faarksGrepoPicSaver_button\" href=\""+this.getDataAddress(data)+"\"></a>");
				$("#info_tab_window_bg .cancel").after( addButton );
				addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
			},
			convertOtherFormat1: function( dataString ){
				var match = false;
				var exp = /[?&]([^=]*)=([^&]*)/gi;
				var data = null;
				var data2 = null;
				var result = { units: { att: {}, def:{} }, mods:{ att: {}, def: {} } };
				while( data = exp.exec( dataString ) ){
					if( data2 = this.input_regExp.exec( data[1] ) ){
						match = true;
						if( data2[3] == "wall_levthis" )
							data2[3] = "wall_level";
						result[data2[1]][data2[2]][data2[3]] = data[2];
					}
				}
				if( match )
					return result;
			},
			sourceModules: { 
				townOverviewSidebar: {
					sim: null,
					collect: function(){
						var data={};
						$.each(
							$("#units_land .index_unit, #units_sea .index_unit"),
							function(i,el){
								data[$(el).attr("id")]=$($(el).find("span")[0]).text();
							}
						);
						return this.sim.getDataAddress( { units: { att:data } } );
					},
					addSidebarButton: function(event,ui){
						var el = $("#unit_info_tab_window_bg .tab_content");
						var sideBox = $("#faarksGrepoTownSidebarBox");
						if( sideBox.length == 0 ){
							sideBox = $("<div id=\"faarksGrepoTownSidebarBox\"></div>");
							sideBox.insertBefore( el.parent().children().get(0) );
						}
						var addButton = $("<a id=\"faarksGrepoApplySimData_captureSidebarButton\" href=\""+this.collect()+"\" class=\"faarksGrepoPicSaver_button\"></a>");
						addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
						sideBox.append( addButton );
					},
					init: function(simObj){
						if( $("#units_overview").length > 0 ){
							this.sim = simObj;
							this.addSidebarButton = fer_cf( this.addSidebarButton, this );
							$("#unit_info_tab_window_bg").bind('tabsshow',this.addSidebarButton);
							this.addSidebarButton();
						}
					}
				},
				combatReport: {
					init: function(simObj){
						if( $(".report_fight_classic").length > 0 ){
							var data = { units: { att: {}, def: {} }, mods: { att: {}, def: {} } };
							var list = $(".report_side_attacker_unit .report_unit");
							for( var i = 0; i < list.length; i++ ){
								var classList = list[i].className.replace(/^\s+|\s+$/g, "").split(/\s+/);
								for( var c = 0; c < classList.length; c++ ){
									var d = /^unit_(.*)$/.exec( classList[c] );
									if( d ){
										data["units"]["att"][d[1]] = Number( $(list[i]).find("span:first").text() );
									}
								}
							}
							var list = $(".report_side_defender_unit .report_unit");
							for( var i = 0; i < list.length; i++ ){
								var classList = list[i].className.replace(/^\s+|\s+$/g, "").split(/\s+/);
								for( var c = 0; c < classList.length; c++ ){
									var d = /^unit_(.*)$/.exec( classList[c] );
									if( d ){
										data["units"]["def"][d[1]] = Number( $(list[i]).find("span:first").text() );
									}
								}
							}
							var morale = /[0-9]{1,3}/.exec($("#report_booty_bonus_fight .morale").text());
							if( morale )
								data.mods.att.morale = morale[0];
							var luck = /-?[0-9]{1,3}/.exec($("#report_booty_bonus_fight .luck").text());
							if( luck )
								data.mods.att.luck = luck[0];
							var oldwall = /[0-9]{1,3}/.exec($("#report_booty_bonus_fight .oldwall").text());
							if( oldwall )
								data.mods.def.wall_level = oldwall[0];
							if( $("#report_booty_bonus_fight .nightbonus").length > 0 )
								data.mods.def.is_night = "on";
							
							var buttonBox = $("#faarksGrepoReportButtonBox");
							if( buttonBox.length == 0 ){
								buttonBox = $("<div id=\"faarksGrepoReportButtonBox\"></div>");
								$("#report_report_header").append( buttonBox );
							}
							var addButton = $("<a class=\"faarksGrepoApplySimData_captureSidebarButton faarksGrepoPicSaver_button\" href=\""+simObj.getDataAddress( data )+"\"></a>");
							addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
							buttonBox.append( addButton );
						}
					}
				},
				spyReport: {
					init: function(self){
						//spy-report => sim
						if($("#report_game_body").length > 0){
							var src = $("#report_arrow img").attr("src");
							if( src && (src.search("espionage.png") >= 0) ){
								var data = { units: { def: {} } };
								var list = $("#report_game_body .report_unit");
								for( var i = 0; i < list.length; i++ ){
									var classList = list[i].className.replace(/^\s+|\s+$/g, "").split(/\s+/);
									for( var c = 0; c < classList.length; c++ ){
										var d = /^unit_(.*)$/.exec( classList[c] );
										if( d ){
											data["units"]["def"][d[1]] = Number( $(list[i]).find("span:first").text() );
										}
									}
								}
								if( ($("#spy_buildings #building_tower").length > 0) || ($("#spy_buildings #building_wall").length > 0) ){
									data.mods = { def: { } };
									if( $("#spy_buildings #building_tower").length > 0 )
										data.mods.building_tower = "on";
									if( $("#spy_buildings #building_wall").length > 0)
										data.mods.wall_level = $("#spy_buildings #building_wall span:first").text();
								}
								var buttonBox = $("#faarksGrepoReportButtonBox");
								if( buttonBox.length == 0 ){
									buttonBox = $("<div id=\"faarksGrepoReportButtonBox\"></div>");
									$("#report_report_header").append( buttonBox );
								}
								var addButton = $("<a class=\"faarksGrepoApplySimData_captureSidebarButton faarksGrepoPicSaver_button\" href=\""+self.getDataAddress( data )+"\"></a>");
								addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
								buttonBox.append( addButton );
							}
						}
					}
				},
				wisdomReport: {
					init: function( simObj ){
						if($("#report_game_body").length > 0){
							var src = $("#report_power_symbol").css("background");
							if( src && (src.search("power_wisdom.png") >= 0) ){
								var data = { units: { att: {} } };
								var list = $("#report_game_body #right_side .report_unit");
								for( var i = 0; i < list.length; i++ ){
									var unit = /\/([a-zA-Z_]+)_[0-9]+x[0-9]+\.[a-zA-Z]+/.exec( $(list[i]).css("background-image") );
									if( unit ){
										data["units"]["att"][unit[1]] = Number( $(list[i]).find("span:first").text() );
									}
								}
								var buttonBox = $("#faarksGrepoReportButtonBox");
								if( buttonBox.length == 0 ){
									buttonBox = $("<div id=\"faarksGrepoReportButtonBox\"></div>");
									$("#report_report_header").append( buttonBox );
								}
								var addButton = $("<a class=\"faarksGrepoApplySimData_captureSidebarButton faarksGrepoPicSaver_button\" href=\""+simObj.getDataAddress( data )+"\"></a>");
								addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
								buttonBox.append( addButton );
							}
						}
					}
				},
				placeLines: {
					init: function(self){
						//Place => sim
						if( $("#place_defense ul.game_list li.place_units").length > 0){
							var list = $("#place_defense ul.game_list li.place_units");
							for( var i = 0; i < list.length; i++ ){
								var cnt = 0;
								var data = { def: { } };
								var el = $(list[i]);
								var ul = el.find(".place_unit");
								for( var ui = 0; ui < ul.length; ui++ ){
									var ud = /units\/(.*)_40x40/.exec( $(ul[ui]).css("background-image") );
									if( ud ){
										data.def[ud[1]] = $(ul[ui]).find("span:first").text();
										cnt++;
									}
								}
								if( cnt > 0 ){
									el.css("position","relative");
									var addButton = $("<a class=\"faarksGrepoApplySimData_captureSidebarButton faarksGrepoApplySimData_placeButton faarksGrepoPicSaver_button\" href=\""+self.getDataAddress( { units: data } )+"\"></a>");
									addButton.mousePopup(new MousePopup(fgt.getString("enhancedSim_caputreButtonPopup")));
									el.append(addButton);
								}
							}
						}
					}
				},
				commandPopup: {
					sim: null,
					collect: function(){
						if( $("#commandWindow").length > 0 ){
							var units = $("#commandWindow .index_unit");
							var got = false;
							var off = {};
							for( var i = 0; i < units.length; i++ ){
								var classList = units[i].className.replace(/^\s+|\s+$/g, "").split(/\s+/);
								for( var c = 0; c < classList.length; c++ ){
									if( GameData.units[ classList[c] ] ){
										off[classList[c]] = Number( $(units[i]).find("span:first").text() );
										got = true;
									}
								}
							}
							$("#faarksGrepoApplySimData_dialogButton").remove();
							if( got )
								this.sim.addCaptureButtonToDialog( { units: { att: off } } );
						}
					},
					init: function(self){
						this.sim = self;
						this.collect = fer_cf( this.collect, this );
						$('body').ajaxComplete( this.collect );
					}
				},
				conquerorPopup: {
					sim: null,
					collect: function(){
						if( $("#conquerorWindow").length > 0 ){
							var units = $("#conquerorWindow .index_unit");
							var got = false;
							var off = {};
							for( var i = 0; i < units.length; i++ ){
								var id = /conqueror_unit_([^\s]+)/.exec($(units[i]).attr("id"));
								if( id && id[1] ){
									off[id[1]] = Number( $(units[i]).find("span:first").text() );
									got = true;
								}
							}
							$("#faarksGrepoApplySimData_dialogButton").remove();
							if( got )
								this.sim.addCaptureButtonToDialog( { units: { def: off } } );
						}
					},
					init: function(simObj){
						this.sim = simObj;
						this.collect = fer_cf( this.collect, this );
						$('body').ajaxComplete( this.collect );
					}
				}
			},
			init: function(){
				var self = this;
				with(this){
					$("style:first").append("\
					#faarksGrepoTownSidebarBox{\
						display: block;\
						position: absolute;\
						right: 10px;\
						top: 40px;\
						z-index: 98;\
						float: right;\
					}\
					#faarksGrepoReportButtonBox{\
						display: block;\
						position: absolute;\
						right: 3px;\
						top: 2px;\
						z-index: 98;\
						float: right;\
					}\
					#faarksGrepoTownSidebarBox div,#faarksGrepoReportButtonBox div,#faarksGrepoTownSidebarBox a,#faarksGrepoReportButtonBox a{\
						margin-left: 2px;\
					}\
					#faarksGrepoApplySimData_captureSidebarButton, .faarksGrepoApplySimData_captureSidebarButton {\
						display: inline-block;\
						height: 23px;\
						width: 22px;\
						background: transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_sim_new.png) no-repeat scroll 0 0;\
					}\
					.faarksGrepoApplySimData_placeButton{\
						position: absolute;\
						right: 3px;\
						top: 2px;\
						display:none;\
					}\
					ul.game_list li:hover .faarksGrepoApplySimData_placeButton{\
						display:block;\
					}\
					#faarksGrepoApplySimData_dialogButton{\
						position: absolute;\
						right: 64px;\
						top: 0px;\
					}\
					#faarksGrepoApplySimData_captureSidebarButton:hover, .faarksGrepoApplySimData_captureSidebarButton:hover {\
						background: transparent url(http://grepo.faark.de/faarksGrepoTools/resources/view_on_sim_hover_new.png) no-repeat scroll 0 0;\
					}\
					");
				}
				if( this.simOpen ){
					FightSimulator.faarksGrepoSimData_oldSwitchGod = FightSimulator.switchGod;
					FightSimulator.switchGod = function(player,god_id){
						var r,isEx=false;
						try{
							//save old god units
							var old = { att: {}, def: {} };
							var l = $(".place_insert_field");
							for(var i=0;i<l.length;i++){
								var data = self.input_regExp.exec( $(l[i]).attr("name") );
								if( data && $(l[i]).hasClass('building_place_'+data[2]+'_'+this[data[2]+'_god_id']) )
									old[data[2]][data[3]] = $(l[i]).val();
							}
							//change good
							try{
								r = this.faarksGrepoSimData_oldSwitchGod.apply( this, arguments );
							}catch(ex){
								r=ex;
								isEx=true;
							}
							//set old units
							var l = $(".place_insert_field");
							for(var i=0;i<l.length;i++){
								var data = self.input_regExp.exec( $(l[i]).attr("name") );
								if( data && $(l[i]).hasClass('building_place_'+data[2]+'_'+this[data[2]+'_god_id']) && old[data[2]][data[3]] )
									$(l[i]).val( old[data[2]][data[3]] );
							}
						}catch(err){
							faarksErrorReporter.report( err );
						}finally{
							if(isEx)
								throw r;
							return r;
						}
					}
					
					
					var startData = null;
					if( startData = /faarksGrepoApplySimData=([^&]*)/.exec( document.location.href) )
						startData = $.secureEvalJSON(decodeURIComponent( startData[1] ));
					if( startData || (startData = this.convertOtherFormat1( document.location.href ) ) )
						this.open( startData );
					
					$("#place_simulator_form .game_list_footer").append("<a id=\"faarksGrepoSwapSimSides_button\" href=\"#\" style=\"display: inline-block; margin: 0px 0px 0px 3px;\" class=\"button\"><span class=\"left\"></span><span class=\"middle\">"+fgt.getString("enhancedSim_swapSideText")+"</span><span class=\"right\"></span><span style=\"clear: both;\"></span></a>");
					$("#faarksGrepoSwapSimSides_button").click( fer_cf( this.toggleSites, this ) );
					$("#faarksGrepoSwapSimSides_button").mousePopup(new MousePopup(fgt.getString("enhancedSim_swapSidePopup")));
					
					
					$("#place_simulator_form .game_list_footer").append("<a id=\"faarksGrepoGetSimLink_button\" href=\"#\" style=\"display: inline-block; margin: 0px 0px 0px 3px;\" class=\"button\"><span class=\"left\"></span><span class=\"middle\">"+fgt.getString("enhancedSim_getSimUrl_text")+"</span><span class=\"right\"></span><span style=\"clear: both;\"></span></a>");
					$("#faarksGrepoGetSimLink_button").click( fer_cf( this.getSaveLink, this ) );
					$("#faarksGrepoGetSimLink_button").mousePopup(new MousePopup(fgt.getString("enhancedSim_getSimUrl_popup")));
					
					$("#place_simulator_form .game_list_footer").append("<a id=\"faarksGrepoOpenSimLink_button\" href=\"#\" style=\"display: inline-block; margin: 0px 0px 0px 3px;\" class=\"button\"><span class=\"left\"></span><span class=\"middle\">"+fgt.getString("enhancedSim_openSimLink_text")+"</span><span class=\"right\"></span><span style=\"clear: both;\"></span></a>");
					$("#faarksGrepoOpenSimLink_button").click( fer_cf( this.openSaveLink, this ) );
					$("#faarksGrepoOpenSimLink_button").mousePopup(new MousePopup(fgt.getString("enhancedSim_openSimLink_popup")));
					
				}else{
					//init source-modules
					for( var i in this.sourceModules ){
						if( this.sourceModules[i] && (typeof this.sourceModules[i] === "object") && (typeof this.sourceModules[i].init === "function") )
							this.sourceModules[i].init(this);
					}
				}
				
			}
		},
		timeleftInAcademy: { // timeleft til ress aviable in Aca
			mousePopup_overriddenShowDiv: function(){
				if( ($("#popup_content .academy_popup").length > 0) && ($("#popup_content").find("#faarksGrepoAkaResTimeleft_by").length==0)){
					var imgs = $("#popup_content").find("img");
					var neededTechPoints = 0;
					var ressis = ["wood","stone","iron"];
					var timeleft = -1;
					for( var i = 0; i < imgs.length; i++ ){
						var key = /([^\/]*).png$/.exec( imgs[i].attributes["src"].value )[1];
						var data = imgs[i].nextSibling.nodeValue;
						var needed = 0;
						if( $.inArray( key, ressis ) != -1 ){
							needed = Number(data) - Number(Layout.resources[key]);
							if( needed > 0 ){
								var left = Math.floor(needed/(((Number(Layout.production[key])/60)/60)));
								if( (timeleft < left) || (timeleft == -1) )
									timeleft = left;
							}
						}else if( key == "research_points" ){
							needed = Number($("#academy_research_points span").val()) - Number(data);
						}
						if( needed > 0 ){
							$(imgs[i].nextSibling).replaceWith("<div style=\"display:inline-block; margin-right: 7px;\">"+data+"<br/><span style=\"color:red;font-size:80%;font-style:italic;\">-"+needed+"</span></div>");
						}else{
							$(imgs[i].nextSibling).replaceWith("<div style=\"display:inline-block; margin-right: 7px; position: relative; top: -8px;\">"+data+"</span></div>");
						}
					}
					if( timeleft > 0 ){
						$("#popup_content").append( fgt.getString("academyTimeleft_resItem",{"in":readableSeconds(timeleft),"at":faarksGrepoTools.humanReadableDate( new Date( new Date().getTime() + (timeleft*1000) ) )}));
					}
					$("#popup_content").append(faarksTextSelection.get("sys","by",{id:"id='faarksGrepoAkaResTimeleft_by' ",what:"Resource-Timeleft "}));
				}
			},
			buildingAcademy_newInitMousePopup: function(){
				if(BuildingAcademy.orders.length>0){
					$.each(BuildingAcademy.orders,function(i,order){
						$('#academy_tasks_'+i+' .academy_tasks_image').mousePopup(new MousePopup(fgt.getString("academyTimeleft_doneIn",{id:'id="faarksGrepoAkaResTimeleft_by" ',what:'Resource-Timeleft ',order:order.name,done_at:faarksGrepoTools.humanReadableDate( new Date( order.to_be_completed_at*1000 ) )})));
					});
				}
			},
			init: function(){
				if ( typeof BuildingAcademy == "object") {
					faarksGrepoTools.setInterrupt( MousePopup.prototype, "showDiv", this, this.mousePopup_overriddenShowDiv );
					faarksGrepoTools.setInterrupt( BuildingAcademy, "initializeMousePopups", this, this.buildingAcademy_newInitMousePopup );
					
					BuildingAcademy.initializeMousePopups();
				}
			}
		},
		walkDuration: { // Add Durations to Mouseover-Popup on Worldmap
			durCache: {},
			units: null,
			durMods: {
				calculated: false,
				dataSource: null,
				data: null
			},
			exclude: ["xx1"],
			includeLangs: ["de","en"],
			defaultUnits: ["big_transporter","bireme","attack_ship","colonize_ship"],
			unitTypes: {
				land: ["sword","slinger","archer","hoplite","rider","chariot","catapult","minotaur","zyklop","centaur","medusa"],
				air: ["manticore","harpy","pegasus"],
				sea: ["big_transporter","bireme","attack_ship","demolition_ship","small_transporter","trireme","colonize_ship","sea_monster"]
			},
			unitRequestActive: false,
			useDefaultUnits: false,
			
			isActiveHereCache: null,
			isActive: function(){
				if( this.isActiveHereCache === null ){
					this.isActiveHereCache = ($.inArray( faarksGrepoTools.currentWorld, this.exclude ) == -1) && ($.inArray( faarksGrepoTools.currentLang, this.includeLangs ) >=0);
				}
				return this.isActiveHereCache;
			},
			afterGotContent: function( townId ){
				if( !this.durMods.calculated ){
					if( this.durMods.dataSource && this.durCache[ this.durMods.dataSource ] && (this.durCache[ this.durMods.dataSource ] !== true) && this.durMods.baseData && !this.durCache[ this.durMods.dataSource ].error){
						var dur = this.durCache[this.durMods.dataSource];
						var mods = { };
						for( var i in this.durMods.baseData ){
							if( GameData.units[i] ){
								var realTime = this.durMods.baseData[i].duration - dur.offset;
								mods[i] =  Math.round((dur.time / (realTime*GameData.units[i].speed) )*Math.pow(10,2))/Math.pow(10,2);
							}
						}
						this.durMods = { calculated: true, data: mods, baseData: this.durMods.baseData };
					}else{
						if( this.durCache[ this.durMods.dataSource ] && this.durCache[ this.durMods.dataSource ].error && (townId != this.durMods.dataSource)){
							this.durMods = {
								calculated: false,
								dataSource: null,
								data: null
							};
						}
						if( townId )
							this.gotUnits( townId );
						if( this.durMods.dataSource )
							this.getTime( this.durMods.dataSource );
					}
				}
				this.updateContent( townId );
			},
			gotUnits: function(town_id){
				if( this.units )
					return true;
				if( !this.unitRequestActive && !this.durMods.dataSource ){
					this.unitRequestActive = true;
					$.ajax({
						timeout: 3000,
						dataType:"text",
						url: url('town_info',undefined,{action:"attack",id:town_id}),
						error: fer_cf(function(){ this.unitRequestActive = false; }, this),
						success: fer_cf(function(data,testStatus,xhr){
							//var data = data.replace(/\<script[^\>]*\>[\s\S]*\<\/script\>/,"");
							this.unitRequestActive = false;
							var searchedData = /TownInfo.unitInfo ?= ?([^\;]*);/.exec(data);
							if( searchedData ){
								this.durMods.baseData = $.secureEvalJSON( searchedData[1] );
								this.durMods.dataSource = town_id;
								
								var el = $("<div></div>");
								var x=$.ready;
								var y=$.fn.ready;
								$.ready = $.fn.ready = function(){};
								try{
									el.html(data);
								}finally{
									$.ready = x;
									$.fn.ready = y;
								}
								var units = el.find("#town_info_units .index_unit");
								this.units = {};
								for( var i = 0; i < units.length; i++ ){
									var el = $(units[i]);
									this.units[el.attr("id")] = Number( el.find("span:first").text() );
								}
								this.afterGotContent();
							}
						},this)
					});
				}
				return false;
			},
			getTime: function(town_id){
				if( this.durCache[town_id] ){
					if( this.durCache[town_id] === true )
						return null;
					return this.durCache[town_id];
				}else{
					$.ajax({
						url: 'http://www.grepotools.de/backend.cgi',
						data: {
							type:"plainb",
							speed:1,
							world:faarksGrepoTools.currentWorld,
							mytid:Game.townId,
							tid:town_id
						},
						error: fer_cf(function(request,error){
							this.durCache[town_id] = false;
						},this),
						success: fer_cf(function(request){
							var data = request.split("|");
							if( (data.length == 3) )
								if(Number(data[0])>0)
									this.durCache[town_id] = { time: Number(data[0]), offset: Number(data[1]), sameIsland: Number(data[2]) };
								else{
									var text = "Server send invalid data: ["+request.toString()+"]";
									this.durCache[town_id] = { error: text };
								}
							else if( data.toString() )
								this.durCache[town_id] = { error: data.toString() };
							else{
								var text = "Server send invalid data: ["+request.toString()+"]";
								this.durCache[town_id] = { error: text };
							}
							this.afterGotContent( town_id );
//							if( this.durCache[town_id].error && ( this.durCache[town_id].error != "Town not found") )//remove known errors like new towns not in db
//								throw new Error( this.durCache[town_id].error );
						},this)
					});
					this.durCache[town_id] = true;
				}
			},
			mayAddUnitToRows: function(otherIslandData,unit,upperrow,lowerrow,inv){
				if( (this.useDefaultUnits && ( jQuery.inArray(unit,this.defaultUnits) != -1 )) || (this.units[unit] && (this.units[unit] > 0) )  ){
					var col = (upperrow.children().length % 2 == (inv?1:0)) ? "#E5BF75" : "#FFE2A1";
					upperrow.append("<td style=\"background-color: "+col+"; \"><img style=\"width:25px;height:25px;\" src=\"http://static.grepolis.com/images/game/units/"+unit+"_40x40.png\"/></td>");
					lowerrow.append("<td style=\"background-color: "+col+"; padding: 0px 1px 0px 1px; font-size: 9px;\">"+readableSeconds(((otherIslandData.time/GameData.units[unit].speed)/this.durMods.data[unit])+otherIslandData.offset)+"</td>");
				}
			},
			drawContent: function(targetEl,otherIslandData){
				var tbl = $("<table cellspacing=\"0\" cellpadding=\"0\" style=\"border: 1px solid #E1AF55;text-align:center;margin-top:3px;\"></table>");
				var upperRow = $("<tr></tr>");
				var lowerRow = $("<tr></tr>");
				var gotLandWay = otherIslandData.sameIsland;
				var nothingDrawn = true;
				if( gotLandWay ){
					for( var i = 0; i < this.unitTypes.land.length; i++ ){
						this.mayAddUnitToRows(otherIslandData,this.unitTypes.land[i],upperRow,lowerRow,nothingDrawn);
					}
					if( upperRow.find("td").length > 0 ){
						for( var i = 0; i < this.unitTypes.air.length; i++ ){
							this.mayAddUnitToRows(otherIslandData,this.unitTypes.air[i],upperRow,lowerRow,nothingDrawn);
						}
						targetEl.append(tbl);
						tbl.append(upperRow).append(lowerRow);
						nothingDrawn = false;
						tbl = $("<table cellspacing=\"0\" cellpadding=\"0\" style=\"border: 1px solid #E1AF55;text-align:center;margin-top:1px;\"></table>");
						upperRow = $("<tr></tr>");
						lowerRow = $("<tr></tr>");
					}
				}
				for( var i = 0; i < this.unitTypes.sea.length; i++ ){
					this.mayAddUnitToRows(otherIslandData,this.unitTypes.sea[i],upperRow,lowerRow,nothingDrawn);
				}
				if( !gotLandWay || nothingDrawn ){
					for( var i = 0; i < this.unitTypes.air.length; i++ ){
						this.mayAddUnitToRows(otherIslandData,this.unitTypes.air[i],upperRow,lowerRow,nothingDrawn);
					}
				}
				if( upperRow.find("td").length > 0 ){
					targetEl.append(tbl);
					tbl.append(upperRow).append(lowerRow);
					nothingDrawn = false;
				}
				return nothingDrawn;
			},
			updateContent: function( onlyTown ){
				var el = $("#grepoWalkDuration_div");
				var town_id = el.data("grepoWalkDuration.villageid");
				if( town_id && ( (town_id == onlyTown) || !onlyTown ) ){
					if( !this.isActive() ){
						el.html(fgt.getString("walkDuro_offline"));
					}else{
						var otherIslandData = this.getTime( town_id );
						if( otherIslandData && otherIslandData.error){
							el.html(fgt.getString("walkDuro_onError"));
						}else if( this.gotUnits( town_id ) && otherIslandData && this.durMods.calculated ){
							if(!otherIslandData.error ){
								el.html("");
								this.useDefaultUnits = false;
								if( this.drawContent( el, otherIslandData ) ){
									this.useDefaultUnits = true;
									this.drawContent( el, otherIslandData );
								}
								el.append(fgt.getString("walkDuro_fullBy"));
							}else{
								el.html(fgt.getString("walkDuro_onError"));
							}
						}else{
							el.html(fgt.getString("walkDuro_onLoading"));
						}
					}
				}
			},
			checkMouseOver: function(e){
				var townid = /^town-(\d+)$/.exec(e.target.id);
				if( townid != null ){
					townid = townid[1];
					if (townid && (townid != Game.townId)) {
						var popup = $("#popup_content");
						var el = $("<div id=\"grepoWalkDuration_div\"></div>");
						el.data("grepoWalkDuration.villageid",townid);
						popup.append(el);
						this.updateContent( townid );
					}
				}
			},
			init: function(){
				if (typeof WMap == "object" ) {
					document.addEventListener('mouseover', fer_cf( this.checkMouseOver, this ), false);
				}
			}
		},
		quickCast: { // Cast-UI when click on god-logo
			init: function(){
				$("#god_mini").css("cursor","pointer");
				$("#god_mini").mousePopup(new MousePopup(fgt.getString("quickCast_popup")));
				$("#god_mini").click( function( ) { TownInfo.init(Game.townId,'town_info',false,"#content");$("#info_tab_window_bg").tabs('select',4); } );
				// open town-Spell-dialog javascript:$("#info_tab_window_bg").tabs('select',4);void(0);
			}
		},
		/*incommingLink: { //incomming-link; now implemented by inno
			init: function{
				if( $("#game_incoming").length > 0 ){
					var cnt = Number( $("#game_incoming").text() );
					$("#game_incoming").css("cursor","pointer");
					$("#game_incoming").mousePopup(new MousePopup("Auf dich laufen gerade "+cnt+" Angriffe!!!<br/><br/>Klicke hier, um in die<br/> Befehlsübersicht zu gelangen.<br/><span style='float:right;color: gray;font-size: 60%;'>by Faark</span>"));
					$("#game_incoming").click( function(){ window.location.href=url("building_place","command_overview");} );
				}
			}
		},*/
		movablePopups: { //movable popups
			makeWindowMovable: function( win ){
				try{
					if( $(win).length <= 0 )
						return;
					var loc = win.offset();
					$("body").append(win);
					win.css({"text-align":"left","z-index":98,"top":loc.top,"left":loc.left});
					win.draggable({cancel:"#info_tab_window_bg a, #info_tab_window_bg ul li, #info_tab_window_bg div div, #info_tab_window_bg iframe, #tutorial_window_arrows",containment:"document",cursor: 'move',opacity: 0.7,scroll:true,snap:true });
				}catch(err){
					faarksErrorReporter.report(err);
				}
			},
			after_townLinkClicked: function(){
				Layout.town_link_clicked_menu.css({ "z-index": 99 });
			},
			init: function(){
				$("style:first").append(" #ajax_loader{ z-index:10000 } ");
				faarksGrepoTools.setInterrupt( Layout, "townLinkClicked", this, this.after_townLinkClicked );
				if( (typeof TownInfo === 'object') && (typeof TownInfo.init === 'function') ){
					faarksGrepoTools.setInterrupt( TownInfo, "init", this, function(){this.makeWindowMovable( $("#townWindow") );} );
				}
				if( (typeof ConquerorInfo === 'object') && (typeof ConquerorInfo.init === 'function') ){
					faarksGrepoTools.setInterrupt( ConquerorInfo, "init", this, function(){this.makeWindowMovable( $("#conquerorWindow") );} );
				}
				if( (typeof CommandInfo === 'object') && (typeof CommandInfo.init === 'function') ){
					faarksGrepoTools.setInterrupt( CommandInfo, "init", this, function(){this.makeWindowMovable( $("#commandWindow") );} );
				}
				if( $("#player_hint").length > 0 ){
					this.makeWindowMovable( $("#player_hint") );
				}
				if( (typeof Tutorial === 'object') && (typeof Tutorial.init === 'function') ){
					faarksGrepoTools.setInterrupt( Tutorial, "init", this, function(){if( $('#tutorial_window').parent("#box").length > 0){this.makeWindowMovable( $("#tutorial_window") );}} );
					this.makeWindowMovable( $("#tutorial_window") );
				}
				if( (typeof UnitsBeyondInfo === 'object') && (typeof UnitsBeyondInfo.init === 'function') ){
					faarksGrepoTools.setInterrupt( UnitsBeyondInfo, "init", this, function(){this.makeWindowMovable( $("#unitsBeyondWindow") );} );
				}
				if( (typeof Reports === 'object') && (typeof Reports.showPublishReportDialog === 'function') ){
					faarksGrepoTools.setInterrupt( Reports, "showPublishReportDialog", this, function(){this.makeWindowMovable( $("#report_publish_dialog") );} );
				}
			}
		},
		advancedTownlistLinks: { //advanced townlist
			isGrouplist: false,
			townCoordCache: {},
			scrollToTown: function(town_id){
				if( typeof WMap === "undefined"){
					return true;
				}else{
					if( this.townCoordCache[town_id] === true )
						return;//loading
					else if( this.townCoordCache[town_id] && (this.townCoordCache[town_id].status == "ok") ){
						var x = this.townCoordCache[town_id].x-1;
						var y = this.townCoordCache[town_id].y-1;
						//WMap.jumpToPos( x, y );
						//copy of jumpToPos, to use custom callback that sets focus
						var map=WMap.mapTiles.pixel2Map(WMap.scrollBorder.xMax,WMap.scrollBorder.yMax);
						WMap.clearMarker();
						WMap.mapTiles.focussed_town_id = town_id;
						WMap.mapData.checkReload(x,y,WMap.chunkSize,WMap.chunkSize,function(){
							//set location
							WMap.setPosition({x:x,y:y});
							WMap.last_move_x=WMap.last_move_y=0;
							//change focus
							var towns = MapTiles.mapData.getTowns(MapTiles.tile.x,MapTiles.tile.y,MapTiles.tileCount.x,MapTiles.tileCount.y);
							for(i in towns){
								var town=towns[i];
								if( (town.id == town_id) && (WMap.getTownType(town) == 'town')){
									var islandOffset = MapTiles.map2Pixel(town.x,town.y);
									$(".focussedtown").remove();
									var div_town_focus=$('<div />')
									.addClass('focussedtown')
									.css({
										'left':MapTiles.cssOffset.x+islandOffset.x+town.offset_x+'px',
										'top':MapTiles.cssOffset.y+islandOffset.y+town.offset_y+'px'
									});
									MapTiles.elm.towns.append(div_town_focus);
								}
							}
							
						});
						
					}else{
						$.ajax({
							url: 'http://www.grepotools.de/townid2coo.cgi',
							data: {
								townid:town_id,
								world:faarksGrepoTools.currentWorld
							},
							error: fer_cf(function(request,error){
								HumanMessage.error(fgt.getString("extTownlist_errorMsg"));
								this.townCoordCache[town_id] = false;
							},this),
							success: fer_cf(function(request){
								var data = request.split("|");
								if( data.length == 2 )
									this.townCoordCache[town_id] = { status: "ok", x: Number(data[0]), y: Number(data[1]) };
								else
									this.townCoordCache[town_id] = { error: request };
								this.scrollToTown( town_id );
							},this)
						});
						$('#town_list').hide().empty();
					}
					return false;
				}
			},
			showTownInfo: function(id){
				TownInfo.init(id,'town_info',false,'#content');
				$('#town_list').hide().empty();
			},
			staticAddButtonToTownlist: function(){
				if( this.isGroupList )
					return;
				if( $("#town_list li .faarksGrepoTownListEnhancement_box").length > 0 )
					return;
				var els = $("#town_list li");
				for( var i = 0; i < els.length; i++ ){
					var el = $(els[i]);
					var a = el.find("a:first");
					var tid = null;
					var oldLink = /town_id=([^\&]*)/.exec( a.attr("href") );
					if( oldLink ){
						tid = Number( oldLink[1] );
					}else{
						var newLink = /gotoTown\(([0-9]*)\)/.exec( a[0].attributes["onclick"].value );
						if( newLink ){
							tid = Number( newLink[1] );
							
							var locationData = faarksGrepoTools.getParams();
							locationData["town_id"] = tid;
							a.attr( "href", url( '', '', locationData ) ).removeAttr( "onclick" );
						}else{
							throw new Error( "no townId found" );
						}
					}
					if( el.find(".faarksGrepoTownListEnhancement_box").length == 0 ){
						a.before("<div class=\"faarksGrepoTownListEnhancement_box\"><div class=\"faarksGrepoTownListEnhancement_infoButton\"></div><a href=\""+url("map","",{target_town_id:tid})+"\" class=\"faarksGrepoTownListEnhancement_gotoButton\"></a></div>");
						el.find(".faarksGrepoTownListEnhancement_infoButton").click( fer_cf(this.showTownInfo,this,[tid]) );
						el.find(".faarksGrepoTownListEnhancement_gotoButton").click( fer_cf(this.scrollToTown,this,[tid]) );
						el.find(".faarksGrepoTownListEnhancement_infoButton").mousePopup(new MousePopup(fgt.getString("extTownlist_infoPopup"),{"z-index":30000}));
						if( typeof WMap === "undefined")
							el.find(".faarksGrepoTownListEnhancement_gotoButton").mousePopup(new MousePopup(fgt.getString("extTownlist_gotoMap"),{"z-index":30000}));
						else
							el.find(".faarksGrepoTownListEnhancement_gotoButton").mousePopup(new MousePopup(fgt.getString("extTownlist_gotoOnMap"),{"z-index":30000}));
					}
				}
			},
			initCss: function(){
				$('head').append("<style type=\"text/css\">\
				.faarksGrepoTownListEnhancement_box{\
					display: none;\
					position: absolute;\
					right: 24px;\
					z-index: 350;\
				}\
				#town_list li:hover .faarksGrepoTownListEnhancement_box{\
					display: block;\
				}\
				.faarksGrepoTownListEnhancement_infoButton, .faarksGrepoTownListEnhancement_gotoButton{\
					width: 14px;\
					height: 14px;\
					display: inline-block;\
					cursor: pointer;\
					margin-left: 3px;\
					position:relative;\
					top:1px;\
				}\
				.faarksGrepoTownListEnhancement_infoButton{\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/bbc_logo_town_small.png) no-repeat scroll 0 0;\
				}\
				.faarksGrepoTownListEnhancement_gotoButton{\
					background:transparent url(http://grepo.faark.de/faarksGrepoTools/resources/bbc_logo_world_small.png) no-repeat scroll 0 0;\
				}");
			},
			init: function(){
				if( $('#town_list').length > 0 ){
					this.initCss();
				}
				$('#town_list').ajaxComplete(fer_cf( this.staticAddButtonToTownlist, this ));
				$('#city_list').click(fer_cf( function(){ this.isGroupList = false; }, this ));
				$('#town_group_list').click(fer_cf( function(){ this.isGroupList = true; }, this ));
				//$("#popup_div").css("z-index",10000);
			}
		},
		advancedPaginator: {
			initAdvancedPaginator: function( baseEl, urlFunc ){
				if( (baseEl.length <= 0) || !urlFunc )
					return;
				this.go = function(){
					var no = Number( this.input.val() );
					if( no < this.min )
						no = this.min;
					if( no > this.max )
						no = this.max;
					var url = this.url( no );
					if( url )
						window.location.href = url;
					return false;
				};
				this.cancel = function(){
					this.input.val( this.defaultValue );
				};
				this.focus = function(){
					this.uSlider.showSlider(this.input.attr("id"));
				};
				this.url = urlFunc;
				this.baseElement = baseEl;
				var oldCurrentBox = baseEl.find("#paginator_selected");
				var min = oldCurrentBox;
				var max = oldCurrentBox;
				while( min.length > 0 ){
					this.min = Number( min.text() );
					min = min.prev(".paginator_bg");
				}
				while( max.length > 0 ){
					this.max = Number( max.text() );
					max = max.next(".paginator_bg");
				}
				if( this.min == this.max )
					return;
				this.input = $("<input type=\"text\"></input>");
				this.defaultValue = oldCurrentBox.text();
				this.input.val( this.defaultValue );
				this.input.focus( fer_cf( this.focus, this ) );
				//this.input.blur( fer_cf( this.blur, this) );
				this.input.keypress( fer_cf( function(event){if(event&&((event.which&&event.which==13)||(event.keyCode&&event.keyCode==13))){return this.go();}},this) );
				this.input.attr("id", faarksGrepoTools.uidgen());
				this.input.css({
					border: "none",
					"background-color": "transparent",
					"font-weight": "bold",
					padding: 0,
					margin: 0,
					"text-align":"center",
					color: "#FFCC66",
					width: 39,
					height: 19
				});
				oldCurrentBox.css({
					position:"relative",
					padding:0
				});
				oldCurrentBox.html("");
				var sliderBox = $('\
				<div class="unit_slider_container" style="top:22px;height:45px;float:none;">\
					<a class="unit_slider_button button prev" href="#"></a>\
					<div class="unit_slider"></div>\
					<a class="unit_slider_button button next" href="#"></a>\
					<div class="game_footer" id="buttons">\
						<a class="confirm" href="#" style="float: right;margin-left:2px;"></a>\
						<a class="cancel" href="#" style="float: right;margin-left:2px;"></a>\
					</div>\
				</div>');
				var toggleBox = $('<div class="unit_slider_toggle" style="top:0px;right:-1px"></div>');
				sliderBox.find(".confirm").click( fer_cf(function(){ this.go(); return false; },this ) );
				sliderBox.find(".cancel").click( fer_cf(function(){ this.cancel(); return false; },this) );
				oldCurrentBox.append(sliderBox);
				oldCurrentBox.append(toggleBox);
				oldCurrentBox.append(this.input);
				this.input.mousePopup(new MousePopup(fgt.getString("paginator_defaultPopup")));
				sliderBox.find(".confirm").mousePopup(new MousePopup(fgt.getString("paginator_confirmPopup")));
				sliderBox.find(".cancel").mousePopup(new MousePopup(fgt.getString("paginator_cancelPopup")));
				if(typeof UnitSlider == "undefined"){
					$("head").append("<script type=\"text/javascript\" src=\"/cache/game/unitslider.js\"></script>");
					$.ready(fer_cf(function(){
						this.uSlider = new UnitSlider();
						this.uSlider.initialize(this.input.attr("id"),this.min,this.max);
					},this));
				}else{
					this.uSlider = new UnitSlider();
					this.uSlider.initialize(this.input.attr("id"),this.min,this.max);
				}
			},
			init: function(){
				if( $("#paginator_selected").length > 0 ){
					new this.initAdvancedPaginator($("#report_reports .game_header"),function(a){return url("report","index",{folder_id:Number(faarksGrepoTools.currentFolder),status:"all",offset:(a-1)*10});});
					new this.initAdvancedPaginator($("#ally_events .game_list_footer"),function(a){return url("alliance","index",{offset:(a-1)*10});});
					new this.initAdvancedPaginator($("#message_messages .game_header"),function(a){return url("message","",{folder_id:Number(faarksGrepoTools.currentFolder),status:"all",offset:(a-1)*10});});
					new this.initAdvancedPaginator($("#message_message_list .game_header"),function(a){return url("message","view",{offset:(a-1)*10,id:faarksGrepoTools.getParam("id")});});
					new this.initAdvancedPaginator($("#forumtitle"),function(a){return url("alliance","forum",{"forum[forum_id]":Number(faarksGrepoTools.getParam("forum[forum_id]",$("#forumtitle a.paginator_bg:first").attr("href"))),"forum[page]":a});});
					new this.initAdvancedPaginator($("#threadtitle"),function(a){return url("alliance","forum",{"forum[thread_id]":faarksGrepoTools.getParam("forum[thread_id]"),"forum[page]":a});});
					if( Game.controller == "ranking" ){
						new this.initAdvancedPaginator($("#content"),function(a){var alink=$("#content a.paginator_bg:first").attr("href");return url("ranking",faarksGrepoTools.getParam("action",alink),$.extend({offset:(a-1)*12},(faarksGrepoTools.getParam("type",alink)?{type:faarksGrepoTools.getParam("type",alink)}:{})));});
					}
				}
			}
		},
		gotoLastForumPage: {
			init: function(){
				if($("#threadlist").length > 0){
					var posts = $("#threadlist .thread");
					for( var i = 0; i < posts.length; i++ ){
						var post = $(posts[i]);
						var page = Math.ceil( ( Number( $.trim(post.find(".postcount").text()) ) + 1 )/ 20 );
						if( page > 1 ){
							post.find(".title").append('<a class="lastpostlink" href="'+post.find(".title a").attr("href")+"&forum[page]="+page+'" style="background:transparent url(http://static.grepolis.com/images/game/forum/expand.png) repeat scroll 0 0; width:12px; height:12px; display:inline-block; position:relative; top:2px;"></a>');
							post.find(".lastpostlink").mousePopup(new MousePopup(fgt.getString("gotoLastForumPage_popup",{page:page})));
						}
					}
				}
			}
		},
		templeLinkWhenNoGod: {
			init: function(){
				if( $("#god_mini").length < 1 ){
					$("#res").append('<a id="god_mini" href="'+url("building_temple")+'" alt="" style="margin-top: 5px; margin-right: 10px;opacity:0.8;filter:alpha(opacity=80)"><img alt="" src="http://static.grepolis.com/images/game/temple/shield.png" style="width: 52px; height: 52px;"></a>');
					$("#god_mini").mousePopup(new MousePopup(fgt.getString("gotoTempleWhenNoGod_popup")));
				}
			}
		},
		getForumLink: {
			alert: function(){
				alert( document.location.href.replace("[","%5B").replace("]","%5D") );
			},
			init: function(){
				if( $("#forum").length > 0 ){
					var btn = $('<div style="display:block; position:absolute; top:6px; right:5px; width: 12px; height: 12px; background-image:url(\'http://grepo.faark.de/faarksGrepoTools/resources/Icon_External_Link.png\')"></div>');
					btn.click( fer_cf( this.alert, this ) );
					btn.mousePopup(new MousePopup(fgt.getString("getForumLink_popup")));
					$("#forumtitle, #threadtitle").append(btn);
				}
			}
		},
		moralInPopup: {
			//useOnLangs: ["de", "en"],
			useOnWorlds: [],
			data: {
				cache: {},
				onResponde: function( request, responde, error ){
					if( error ){
						this.cache[ request.townid ] = null;
					}else if( !responde ){
						this.cache[ request.townid ] = { state: "error", text: "Server Error" };
					}else if( isNaN( Number( responde ) ) ){
						this.cache[ request.townid ] = { state: "error", text: responde };
					}else{
						this.cache[ request.townid ] = { state: "ok", moral: Number( responde ) };
					}
					faarksGrepoTools.moralInPopup.towninfo.update( request.townid );
					faarksGrepoTools.moralInPopup.tooltip.update( request.townid );
				},
				get: function( townId ){
					if( !this.cache[townId] ){
						// REQUEST DATA HERE
						this.cache[townId] = {state:"processing"};
						$.ajax({
							type: "GET",
							url: "http://www.grepotools.de/moral.cgi",
							dataType: "text",
							townid: townId,
							data: {
								world: faarksGrepoTools.currentWorld,
								atterpid: Game.player_id,
								deffertid: townId
							},
							timeout: 5000,
							error: function(request,error){
								faarksGrepoTools.moralInPopup.data.onResponde( this, request, error );
							},
							success: function(request){
								faarksGrepoTools.moralInPopup.data.onResponde( this, request, null );
							}
						});
					}
					return this.cache[townId];
				}
			},
			tooltip: {
				data: null,
				lastShownTownId: null,
				getText: function(){
					var data = this.data.get( this.lastShownTownId );
					if( data.state == "ok" ){
						if( data.moral ){
							return faarksGrepoTools.getString( "moralInPopup_moralPopupLine", { moral: data.moral } );
						}
					}else if( data.state == "processing" ){
						return faarksGrepoTools.getString( "moralInPopup_loadingMoralPopupLine" );
					}
				},
				onMouseOver: function(e){
					var townid = /^town-(\d+)$/.exec(e.target.id);
					if( townid != null ){
						townid = townid[1];
						if (townid && (townid != Game.townId)) {
							this.lastShownTownId = townid;
							var text = this.getText();
							if( text )
								$("#popup_content table.popup_table_inside:first").append( "<tr id=\"faarksGrepoTools_toolTipRow_moral_town"+townid+"\">"+text+"</tr>" );
						}
					}
				},
				update: function( townId ){
					if( townId && (townId != this.lastShownTownId ) )
						return;
					var row = $("#faarksGrepoTools_toolTipRow_moral_town"+this.lastShownTownId);
					if( row.length == 1 ){
						var text = this.getText();
						if( text )
							row.html( text );
						else
							row.remove();
					}
				},
				init: function(dataSource){
					this.data = dataSource;
					if (typeof WMap == "object" ) {
						document.addEventListener('mouseover', function(e){ faarksGrepoTools.moralInPopup.tooltip.onMouseOver(e); }, false);
					}
	            }			
			},
			towninfo: {
				data: null,
				getRowContent: function(){
					var data = this.data.get( TownInfo.town_id );
					switch( data.state ){
						case 'ok':
							return {
								text: faarksGrepoTools.getString( "moralInPopup_townInfo_moral_text", { moral: data.moral } ),
								tool: faarksGrepoTools.getString( "moralInPopup_townInfo_moral_popup", { moral: data.moral } )
							};
							break;
						case 'processing':
							return {
								text: faarksGrepoTools.getString( "moralInPopup_townInfo_loading_text" ),
								tool: faarksGrepoTools.getString( "moralInPopup_townInfo_loading_popup" )
							};
							break;
						case 'error':
							if( (data.text == "Same players") || (data.text == "Town not found") )
								return null;
							return {
								text: faarksGrepoTools.getString( "moralInPopup_townInfo_error_text", {errortext: data.text} ),
								tool: faarksGrepoTools.getString( "moralInPopup_townInfo_error_popup", {errortext: data.text} )
							};
							break;
					}
				},
				staticOnTabLoaded: function(){ faarksGrepoTools.moralInPopup.towninfo.onTabLoaded( $(this) ); },
				onTabLoaded: function( element ){
					var box = element.find("#towninfo_towninfo .game_list");
					if( ( box.length === 1 ) && (box.find("#faarksGrepoTools_townMoraleInfoRow").length === 0) ){
						var cls = box.find("li:last").hasClass("even") ? "odd" : "even";
						var data = this.getRowContent();
						if( data ){
							box.append( $("<li id=\"faarksGrepoTools_townMoraleInfoRow\" class=\""+cls+"\"></li>").append( data.text ) );
							if( data.tool )
								$("#faarksGrepoTools_townMoraleInfoRow").mousePopup(new MousePopup(data.tool));
						}
					}
				},
				towninfo_oldinit: null,
				towninfo_init: function(town_id,type,element_id){
					var r = null;
					var e = null;
					try{
						r = faarksGrepoTools.moralInPopup.towninfo.towninfo_oldinit.apply(TownInfo, arguments);
					}catch(er){e=er;}
					try{
						$('#townWindow').unbind('ajaxComplete',faarksGrepoTools.moralInPopup.towninfo.staticOnTabLoaded);
						$('#townWindow').ajaxComplete(faarksGrepoTools.moralInPopup.towninfo.staticOnTabLoaded);
					}catch(er){}
					if( e )
						throw e;
					return r;
				},
				update: function( tid ){
					if( tid && (tid != TownInfo.town_id ) ){
						return;
					}
					var box = $("#faarksGrepoTools_townMoraleInfoRow");
					if( box.length === 1 ){
						var data = this.getRowContent();
						if( !data )
							box.remove();
						else{
							box.html( data.text );
							if( data.tool )
								box.mousePopup(new MousePopup(data.tool));
						}
					}
				},
				init: function( data ){
					this.data = data;
					if( (typeof TownInfo === 'object') && (typeof TownInfo.init === 'function') ){
						this.towninfo_oldinit = TownInfo.init;
						TownInfo.init = this.towninfo_init;
					}
				}
			},
			init:function(){
				if( $.inArray( faarksGrepoTools.currentWorld, this.useOnWorlds ) >= 0 ){
					this.tooltip.init( this.data );
					this.towninfo.init( this.data );
				}
			}
		},
		myHttpData: { // overwrites jquery.httpData to not update client/servertime when making an external request...
			innoHttpData: null,
			originalHttpData: null,
			grepoUrlRegexp: /((https?)?\:)?(\/\/)?([a-zA-Z0-9]*).grepolis.com\//,
			localUrlRegexp: /^\//,
			newHttpData: function( xhr, type, s ){
				if( s && s.url && !this.grepoUrlRegexp.exec( s.url ) && !this.localUrlRegexp.exec( s.url)  ){
					return this.originalHttpData.apply( jQuery, arguments );
				}else{
					return this.innoHttpData.apply( jQuery, arguments );
				}
			},
			init: function(){
				if( jQuery && jQuery.httpData && httpDataOld ){
					this.innoHttpData = jQuery.httpData;
					this.originalHttpData = httpDataOld;
					var self = this;
					jQuery.httpData = function(){return self.newHttpData.apply( self, arguments );};
				}
			}
		},		/*ToDo:
			AllyFile
			Direct Trade
			NoGod... gotoTemple-Btn
			http://forum.grepolis.de/showpost.php?p=57159&postcount=69
			Sim-More input-types (like Schwert: 323)
			Sim-Weiterrechnen
			large map
		*/
		init: function(){
			/* util */
			this.currentWorld = Game.world = /([a-zA-Z0-9]*)\./.exec(document.location.href)[1];
			this.currentAction = Game.action = this.getParam("action")
			this.currentTownName = Game.town_name = $("#town_name_href").text();
			this.currentFolder = this.getParam("folder_id");
			this.currentLang = /([a-zA-Z]+)[0-9]*\./.exec( document.location.href ) ? /([a-zA-Z]+)[0-9]*\./.exec( document.location.href )[1] : "en"
			
			/* modules */
			for( var i in this ){
				if( (typeof this[i] === "object") && this[i] && (typeof this[i].init === "function") ){
					try{
						this[i].init();
					}catch(err){
						faarksErrorReporter.report( err );
					}
				}
			}
		}
	};
	var fgt = faarksGrepoTools;
	faarksGrepoTools.init();
}catch(err){
	faarksErrorReporter.report( err );
}
















