Large

MyFreeFarm Berater

By WhiteScripter Last update May 9, 2013 — Installed 501,363 times.

There are 611 previous versions of this script.

the source is over 100KB, syntax highlighting in the browser is too slow

// ==UserScript==
// @name           MyFreeFarm Berater
// @namespace      http://userscripts.org/scripts/show/66964
// @updateURL      about:blank
// @description    Extends MyFreeFarm
// @date           09.05.2013
// @version        1.4.69
// @include        http://userscripts.org/scripts/show/66964
// @include        http://myfreefarm.*
// @include        http://wolnifarmerzy.pl*
// @include        http://mabelleferme.fr*
// @include        http://enkicsitanyam.hu*
// @include        http://tr.myfreefarm.com*
// @include        http://veselaferma.com*
// @include        http://fermavesela.ro*
// @include        http://mojaderewnja.ru*
// @include        http://migranjalinda.es*
// @include        http://*.myfreefarm.*
// @include        http://*.wolnifarmerzy.pl*
// @include        http://*.mabelleferme.fr*
// @include        http://*.enkicsitanyam.hu*
// @include        http://*.tr.myfreefarm.com*
// @include        http://*.pt.myfreefarm.com*
// @include        http://*.veselaferma.com*
// @include        http://*.fermavesela.ro*
// @include        http://*.mojaderewnja.ru*
// @include        http://*.migranjalinda.es*
// @exclude        http://*forum.*
// @exclude        http://*board.*
// @exclude        http://*farmpedia.*
// @exclude        http://*/dyn_bubbles.php*
// @exclude        http://*/nachrichten/bbhelp.php*
// @exclude        http://*/payment/*
// @exclude        http://*myfreefarm.pytalhost.com/*
// @exclude        http://*facebook.com/*
// @grant          GM_addStyle
// @grant          GM_deleteValue
// @grant          GM_getValue
// @grant          GM_listValues
// @grant          GM_log
// @grant          GM_registerMenuCommand
// @grant          GM_setValue
// @grant          GM_xmlhttpRequest
// @grant          unsafeWindow
// @require        http://userscripts.org/scripts/source/94946.user.js
// ==/UserScript==

//***********************************************************************************************************
// global variables
const VERSION="1.4.69"; //GM_info["script"]["version"];
const neededVersionFunctionFile="1.0.37";
const USO_ID    ="66964";
const USO_Home  ="http://userscripts.org/scripts/show/"+USO_ID; //GM_info["script"]["namespace"]
const USO_Source="http://userscripts.org/scripts/source/"+USO_ID+".user.js";
const USO_Meta  ="http://userscripts.org/scripts/source/"+USO_ID+".meta.js";
if(NEVER==undefined){
	alert("Hi, I am the Berater-Script.\nThe function-file is missing.\nPlease install me again.");
	location.href=USO_Source;
}else if(compareVersions(neededVersionFunctionFile,VERSIONfunctionFile)>0){
	alert("Hi, I am the Berater-Script.\nThe function-file is too old.\nPlease install me again.");
	location.href=USO_Source;
}
var DEVMODE=GM_getValue("devmode",false);
var DEVMODE_EVENTS=GM_getValue("devmode_events",false);
var DEVMODE_FUNCTION=GM_getValue("devmode_function",false);
var hotkeymap=null;
var regDelimThou2=null;
var regDelimThou3=null;
const css_styles_init = {
	"systemMsg_marketsale":[[],""],
	"systemMsg_contractsale":[[],"font-style:italic;"],
	"lowrack":[[],"background:orangered;color:#000;"],
	"farmicart_lowrack":[[],"color:yellow!important;"],
	"timeholder":[[],"background-color:#936b52;border:1px groove #4d240e;border-radius:10px;padding:5px;margin-bottom:5px;"],
	"timer":[[],"background-color:#de9008;color:white;font-weight:bold;text-align:center;"],
	"timer_ready":[["timer"],"background-color:red;"],
	"watertimer":[[],"background-color:blue;color:white;font-weight:bold;text-align:center;"],
	"prod_border_lowamount":[[],"border:1px solid blue;"],
	"prod_border_missing":[[],"border:1px solid red;"],
	"cloud_back_noprice":[[],"background-color:white;"],
	"cloud_border_noprice":[["cloud_back_noprice"],"border:2px solid black;"],
	"cloud_back_below":[[],"background-color:#fdd;"],
	"cloud_border_below":[["cloud_back_below"],"border:2px solid red;"],
	"cloud_back_between":[[],"background-color:#ffe87c;"],
	"cloud_border_between":[["cloud_back_between"],"border:2px solid #ff8c00;"],
	"cloud_back_above":[[],"background-color:#dfd;"],
	"cloud_border_above":[["cloud_back_above"],"border:2px solid green;"],
	"farmi_price_unknown":[[],"background-color:none;"],
	"farmi_price_low":[[],"background-color:#FF3333;"],
	"farmi_price_between":[[],"background-color:yellow;"],
	"farmi_price_above":[[],"background-color:#22AA22;"],
	"farmi_amount_missing":[["farmi_price_above"],"border:1px solid red;"],
	"farmi_amount_low":[["farmi_price_above"],"border:1px solid blue;"],
	"farmi_amount_above":[["farmi_price_above"],"border:1px solid grey;"]};
		
var strImages=new Object();
strImages["leftarrow"]="data:image/gif;base64,R0lGODlhIwAaAPcAAEQWBLyCVIROJKRqNFwyBOy2dGQ6JNyiZIRSPJxuVHxCDMySVIxeNLR2PFwyFPzSpEwmBNyefIxWJHRGJOy6lGw6FLSGZJxqRJRePFQmFMSSbKRyRKx6VOSqfIxiTHxONHRKNKRiPOSqdKx2TFwuBIRWNPzKlLyKXHw6DIQ+JJxmLHQyFIRGJHQ6FKxqROy6hGxCHLyOZMyabMR+ZIxOJHQ2BGxCJMyedJxeLJpmPLx6VOSyjEQeBPCyfIRCHMSCXMqSZGQyHF8mBHNGLLB+TJVaPMSGZKRqTJpiRFkuFJRWNPzOpHQ6HPC+jOSidJ1eNFwiBGIyDPzitOKmfIxWLPi+nMiWdKpyTMR6XLiCXIJOLLRyPHQ+JIxaPLRyVKh2RGwyFEwmDGk6HJxePOSqhIxONLx6TFouDPzOnK5uTHxCHNCadIxOLGpCLEceDNSSZFguHKVqPPS+fGs+JIxWPPzWtNyihHpKJO6+lLSGbKJuRNSWbKx6XPSufKdmRLB6TIpaNKx2VNCmdOy2jOyydIlKHMyObPyyhOy2fMySXPjGnHQ2HIRKLGwyDFwqDPzSrMyOXPy2hHxGLPy+jPzmvJRWLLR2ROCibIRCFJxmRFQiDLRyRJxmNMyOZNyedPyyfLx+TGQuFPzOrLRyTGQuDNyadHRCLFw2BIFWPJRiNGQ2FFQqBNiifLyKZJBiPMSWbLR+VOyufIRSNMSOXHxCJHY2FIdKJHk+FK5uRHRGHKBiLL9+VMeGXMiWZGg2HMmKZKFuTJZaNHU+HPTCjOmmdKBiNGQ2DIRaLMJ+XLSGXIRSLLh2VFQqDGg+HI1SLEsiDKxuPPS6fNSWXPzKnHA2DEQaBLyGVIRSJPzWpFQqFIxmTKRmPHw+DIRGHGw2FJxiPIxSNHxGHHxKLJRaLLR6RGQyBGw6JJReNGQyFFQmBJRWJHxGJPS6lLyGZKRqRMySbKxyRLR6VOyqfIRONHxKNOyqdLR2TGQuBIxWNMSKXHw6FHRCHMSOZNSabJROJHRCJCH5BAAAAAAALAAAAAAjABoABwj/AG20sWHAgYMgqlSdMUaABIRVBAw6SCJRFTpvYoQJk8QIH74SzjygkiVuQgVVFSoIuHKi1w1BN2RYsaLBAp8jSLSs+ydsHbhvR74JNTWnmRhSUcIV69Wrn6BXMXplgbULlA579kZdOZIpmCQmYrisk0UFUJAgYKKoKcbrUj1IoHr9GcHhzyhc24o9CRbsiR89aTKBW8flnxZl+Fj48qZk1yVil0CRM5MPlzs/uOJA2xynWLBxSoJlyoQEHyNa6xgpW1SLDS9WpXiB2sVr1xMfwTT66NaNxjW+wc6B0wKuCD5aoTAKa6TESIQIv7BgSeNHSS1bhoYrE3Dn3751WrRg/8BXBh8GDHSUMdn375YO6MtmIPNShMmKWl6qMCJ1R5w4Lf71p5pHbDDCBj7CNPPPE1ns8cMuyKTBRi0r0BJBFe2IU0EzJYjT3R3C/KMGeGyUyAY4kggjRj+e9JPPg3HY4oMz7LAjSgXhKdNCOFoI0cItQghDCwuM2FKkLVoIo8ov1uxiBjTqKFCDLk2YgM0x+5BwBxQojIMCClN44oMt/jjDhjPggDPPPHMEsccfxQwwgAoNLECICS+ggYcUdQwyTT3E1COPE/5gcqYSlYRWhBJ0/BNKKZsUA8ob0lwSTQHRICLFNA88skQsh3xCTB/EFFKID+oo4YwzSjDaxT9u4v9SCQ666LLFApP0MEwTDyhCCR7YRHJIB05MUQxvSmwTTKLBKNGFKUnchQsut+mDSTAdDIJHOasYkwsJE1xTgRpksCKMLSFcUZ2ispjjCC6bbGLGKE/Ycos+LUyhCAUE5AKDFilRUcGPLajxjbrOCMCGFvP4ogkOcdhjCTzb4CDAPrlQEwMFWaxyDAMMuALIMZVcI8A4ceDyDT5oyjLEMzxIkAM88MSxTSrBUCHALVTEsMM1yuQwwh9zfTECXnF8Eww4+MjygQ0ZPHOLM9vooccFOXwzxjn4RKEMK8pUcAERJ8zSCRCzBKCyM1qU0IUs0PKQQRTCUJHJFVe4840r37j/Y+83LbSQygYB8HJCbfZ8Q8U8sgCCyhC+uPFMEt54Iww4RwCjRyZj5JAJLs6MWQkNT+gBT2bfVKIMOG4j0AYcbmjiAD3/+BJKBYwUgQQS3xRhyzdKsBAMDbZQ8cQ5SlChkxaylOB6Nm5Uw4w4XkjiCymhBCHGOvMU4YyBJTqzjy3OVOKMLQIACGAbvmQgeTbiXPCOGL6AgY4jUJAixjzrICGLMhhggyxsoQxZ9OcwstDCHJIAAQBUAw5t4MAv1uAfcfDkflBwRCjEIA5ZOE19HyiJDegHAR7w4BlhSAIIgNGOWQABH134yDwmwAUxnOEMSQgFOnwhhjn40Ci+OEMYECAwxGxQZA7ayAM/3tCPgAAAOw==";
strImages["rightarrow"]="data:image/gif;base64,R0lGODlhIwAaAPcAADwSBLqCU4BMDPC6eGpdRKKQfNSeXIluTF4wBHxiPNSGTGZLLLOnjF80JIFzXIdNLMK9pMuJZOKmfGg+EK9vRJVeRF4wFI9XLM6TZOisbNy2nJOFa8y7lOq0gmlYO1hAJfzYrrR6RPzHk8SSfN6UZ0gkBHxmRKSSdMqecXdBJLmplI9ZPNzLqbeFZOq7j9CUWrZ5XG4yFE0lFOugbIxWHKB7VJ9iLGRNPJSafJ9nRLy0lKNvRPCpfLFxVMiVdH5LHGwwC/TBpHlBDJxZMsqKXHtLLum0jFckBPG9nJ+MalxGNKxvPI1LI4peRIhRPGRGJJx5XMrCpXdoVGQ3FOymbJxqVHlAHIhSMMyaZLp7VPzCkp5kPLGhja5pRci2pKx2RHlePN6ZdHxGNKJwVMyOdJReNGpAJ3pGJvi8kGM3CcmOZeyydPm0gnhZOsqgfHE5FMe1m1kqBNmtjI9XNM6VbJSCdOWaZIdoR7mLZ8V+XPWufMmEXIh6XLJxTJ+EaNimdJ5dPPzmtMymf8CwjPnMpOaifLqEXO+gZK6cgUUcBHA4BFc/HPnHnPzuxPzftPq7hJRiOcZ9TIx+bLypjKaWfLyadLuumNSaXJ6MdLSOdPW1jMV9VMSafGdSPHpGHKRqPHFiSNSmZIx2VGpSM2U6JOKuhJliRNPCnEwqDFUqFaR2TIRSJJBSJIBiRpx+Y/zSps29pPC0lLyTb9ifcuKTXNeMW9TEpJ5eNHpSM7GihPzOlJJePLZ+XLZ2VNCadPTGpPnCnLR2PJRSL552VIZGJtWOZbyKXMWulrSSfHxOPIhqVK9mPGw+HHRcTOOfZIJxVF8wDMmDVGJONIx2ZIdONNSKbNqphFkwHPGrdMy7nLZ6TEkkDHZoTHVCLKyGbOihdIxXJKFjNJ9pTLm1nKJvTOyqhIBLJHw/FFclDIxeTGE4HMyihHE5HIt7ZOzKrNyihEYeDHM5DPzOnNyafHxSPIVGHKSahGdGLO6mdM6abLd2TFsqDOKabPKuhKiWhGQ6LCH5BAAAAAAALAAAAAAjABoABwj/AItQ63bGzBMzZtips7BvX5wj+9IkKhEHwRFoqa5ptPDmibkzHuc4oYeLZJEiCWOwm0MOjw88+XzJlGWoxRhxTXB1Y8ZsypkzRXCJKTJHJzN27B6Ii0DGFz86aqIG0KcvS59ePfqIg1SEGTR1zH4+EEMtxRSfffKEmccvQpYsmyjo67JlS5cLQwBtyZEDEi5zFqBNsTKH2oOzc7IUmkciwp5NeR736QPo0y0Kn7aUGTJn1xZTd6wEnmL4zZsrhiS03bQp2qYugIQ9IAbkyhtPF7YM4TxnBZhdZZ5M2UfM9JUsdNruCUF3CDEr3Yil6EYHUhpmnk7OmXPhSpEEc1JA/0sBhJg+1fq0adO3jIkVoE7EXHuAxFWaCdlxFb2C64K5OUWk8QYQOfCzRySs9cFEPD/E88B2J5lRAwh/IPCGOil8ZM4V5nRoDjNWmLNJISTsUUwegJyjiBAICLCKJ08EN4cGjrhgzgTnnGGFJ+YU8QCH5lgxhBoG1nIiEOfMMoAALdJAAy5WIJCDCISwsUQ88fBYRI9XcPjGFnREEMkeewDiRD1DXJLBABlk8IgWIMjDCAhoPEJFLSGw8gYzDxRxwQWrMNNHGI9FE4EwwrxBQyhrZLAGG1qgAYIjjMjzyCNt8jBLBDkwQxR3VpCDwWOb7CEMIFawMsujA2jyyquEiP8ggi5rUIFBCP4FecUcZZQxBSBZUEUVIPFYQQcbPxwRw7IpxABEMI6G8kk8CKTx3wMbcjcFS33MxR4x9dTjyTlzWMEOOs958ocuodAwwQQ/BGnFGxl2yA4xQ3TRBQWwDfEAE4gC2SUzvnQgCw2r/BDvdg90I8YV1Jh7Whd96Asbog/IxkQOQ5TxiSCG7HBBAjYkAEkOFazgBDXUELPsPm/MkQNdXSwDyG4XCJObOUOQg8IXOWgDydCQ7LLCCtQ4cQU7R4gXgxVX7NVFDjbfkpduZWxxizZb7CB0OFtA0oTRKzTRDTSJ5EDMWcxckIPUOdx8CyC3vP0AcDdfcQGvvbWusUIRFiSSiDjlQhPHG/oNUdcK23W5N6+AzNHhSRAXcY8Z2whugTgVLH3EERa89+AcXf74Y29XPJDCCl2WtEAD1wi+jTp99CCOMOwYDhE7RThB+hViPEANxKxTgws199zTzTUyACBDKg2ok0cv4nB8BkMWpGJBDGaIQQ/L1CTDshhnSPPBNdvAI4MMGjXQwD9YaWXKAxZkj07696NDyv78q9NAKttIn/rYl5FrNCAgADs=";
strImages["leftarrow_dark"]="data:image/gif;base64,R0lGODlhIwAaAPcAACQKBIxiPFw2FHxOJDwiDMSOXKx6RFw6LFQuDJRmTHRCHCwWBIxeNDwiFJRuRHxONEQWBGQ6JMSidKx+XJRiRGw+FEwuHMSedGxGLHxKHFQiBFQmFGw2FKRyTEQeBIRWLMSaZLSGTIRWNHxCHDweDCwSBJxiNIxOLFwuDCwWDJRaNHxGLMSObLR6VLyGXFQqDKxyTEwqFKxyPJRqRGQyHGw2HLyKbHxOLIxONEQaDFQqHEQeDHxCJFwuFHxKNLSGZDQOBFw2HEwqDMSWZHRCLDwWBEwiFHQ+JMSufFwuHFQiDGQqFIxWPJxiPJRaPJRSPIxmPEwiDLSOZLSCTKRuTGxCJIRaPKRuREQaBKRmRGQ+HHRKJFQqFKRyVDQSDDwWDHxKLMSCVKx2VGw6HHxSLIxSNFwyFFQmDCQOBLx6TGxCLEwuFDQaBEQmFGw+JJRmRFQyHMSafHRKLGw6FFQeBMSabLSKVJRWNHxGHDwSBIxSLLyWbLR+VLSKXGQqDLR2TKxyRMSyjMSihKRqTEwqHKRqRFQeDIRCLMSuhHQ+HIRKJJx2TGQyDHxGJLSKZGQ6HJxmPJRePLySZHRGJIxePLR+TFw+LJxmNDwaBEwmFFwyHEwmDKRyRKR2VDwaDMSefMSebJRiPGQ2FIROJEQiDDQWBEQiFJxuREwWBGw6JJxiRFQuHHRGLFwmFEweBIxWLIxWNDQSBDQWDJxaNIRGLFwqDLRyTJxqRGwyHHQ2HIROLJRONEwaDEweDGQuFIRKNDwOBGQ2HHw+JFwiDJRWPJRmPLyOZKxuTHRCJIxaPEwaBGw+HHxKJFwqFIRKLHQ6HIRSLJRSNGQyFFwmDCwOBFQuFHQ6FLyKVIRGHJRSLMSWbLx+VLyKXLRyRIRGJLyKZKRmPJxePAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAAAAAAALAAAAAAjABoABwj/ABu0aeCpFCZPnjAZLFWiIRs2RUrJYvMFE6YimHbs6HWmWRJNZnocgGMhRhuLHnIgYMUACpVFM2YkSEDBygM1EbhsiLJjU5IIyFKNWWZKIxaMZx5BKnarQ7FQb0RAKwNNlzMwjVYgc6NpQ68cvTL16KEpYcIoY14BMmDiVTFdW26AUdQo0TMOHGoEO4JshZskm4xE4UJ2Qw4PvmBdgQFIz6hRKnhsbcRjBB4eCp7VkCYtWCo3qboa2USYF5Zmd2wNmpVNjwo9YzQE6xVFw5kztXp0DhasRzMzNGhEKYJFIwQaxLoMclIGxyFhuJS1UuW7ms4oUc4QDpakR5Jgj2g0/9tBKgodXcciOXsSjRYuQ1+U/bLBpcgGITHyZ9q0gTCNJM1s0AMN5EURDCxZOIFDNCsswQsEw3RhAxNcZAQHF5tskgltUZDWzFgfbrBDDoVcUYgKd5ShwDRn+PLND3F4YF0PHpCWhytR5NGLEme0EmCAXIwYCSxV4cGIBsrMwc0QEpixQymbAOOKNHQoI8YVStTSjC9jcclFEjt4cosuyyRSQQUZXDIFCHbUYQwigkygTTdpdFPJFX4Mg4IvNPBJQw00aEJKEYU08owel4AjQwhThGAHEntcICkfYYTxRxi2TFNLi75wKc1/QRjxRRbeSMPBM9bgYUIBfBTQhwR7BP/iyAUubJNGB38kwqM0R9TgZ6BGlOIND8NyoAQdSnDwhwvGYBILG0IUsQkKO4pBhRIbjLFCIjRIAyiYsTTSiDMnePNMLa64skMX2jgirQdreEBCNR544IoHSowBhhvN9GudJ9SIgocidB0hSjObaIAFJY6IUIoZQTzyiABmSNNDLbw2MgYNYyWRCTVo+LJMI5MosMwjovRQDSlmUDJBNdVoEdcNA4DBTF2JbExWElw0QA01rvSQyCTIILPMGLxJg0kPHXDhQRVkqBBAJKEwcMckY3QcxCqmlAIANUVEYYYbjbByxBhoI3NGL2O4gsUjk7yiwtx63FCDJj2sookmbXzOAXIpnhSXhBusbCWUGzz4gpvFHCAj7tkck6UJ16X87AkXUXhSRA5c0BCBUME0s/EZuDQzjTRjiMJZM9p9xHUJaAAQywZyZJJDEcTtIFZvXPTbrxIvjNVD71wUn4kpnpQAAAALZFIFBTscVEQeQBSxAxeZpKJyBGMRxrN2MK9BSuXLp2DKAypQscEG+0UfCxCxWJ/JKtXowEV+97dBCglsULM8Gg0hBAaSEYkmaCJQPMuERuIXP4TsgATkeWBBfkaNhpSiFA2IgBUiAYlCBAQAOw==";
strImages["rightarrow_dark"]="data:image/gif;base64,R0lGODlhIwAaAPcAAB4GAIhVL1MqA7mITUA2JHJhT6BuNVtEKjgWAE87HqBZKj4pFIJ3XjgZD1RINVkqFJCMc5lbPKx1Tz8fBX1FJGY4JDgWB2AyFJtkPLJ7Q6eGbGRYQZqKZbODVUAyHTIhD8KkfYNOJMKVZJNjT6plPicPAE8+JHNjSZhuRkwiD4h4ZWAzHqeZeIZYPLOKYJxlNIZNNUQYByoPB7RwQ14xC3BPL287FDwqHmVqT28+JIuDZXNFJLl4T4BGL5ZmSVIpC0MWAryQc00iA2wzGJhcNU8pFbODXjIPALmMbG9eQDUlGXtFHl8pD1w4JFotHjwlD2xNNZiQdEw/LzwbB7Z1Q2xAL00hC1ouFppqPIhPL8KQY248HoBwX31AJZaGc3tLJE04HqpqSU8lGXJGL5pgSWU4GUAhEU4lEL+LYTsbApZgPbaCScCDVU0zHZhwT0YcB5WEazMTAKV8XmAyGZtmQ2VVSbBqPFk/JohcPpNSNbx9T5ZWNVpONYJGKm9WP6R1SW42HsKwg5p1U49/XsCac7ByT4hWNbhwPH1sVCULAEYbADIgC8CVbMK3k8Kqg8GKVmU7HJRQKl5SQ4t4XnVmT4tqSYp9aaBqNW5eSYNgSbyEXpNQL5NqTz4uHk4lC3NAHkY7J6B1PF5LL0AuGT0dD6x9Vmo7JKCQbCoTAzATB3NLKlYuD2EuD1M7JWxSO8KfdZqMc7mDZYtkRaRvR6xkNaNeNaCTc244GU4uGYByVsKbZWM4HoZSNYZLL5xqSbyUc8CQbINLHmUuFm5LL1klEKFgPYtcNZN9ZoNjT08rHlpAL30+HkMfC0k1Kq1vPFVGLzgWA5ZWLzsrGV5LPFkrGaBcQ6Z4VjMWC7l7SZqKbIZOKicPA0s/KkkiFHtZQ7JwSV4yD3A7GW9AKoiEbHJFKrZ5VlMpD08gBzIPA144KjobC5pyVkYcC1xPPLaYe6dyViUMA0gcA8KbbKdqT08uHlglC3NqVj4lFLd1SZtqQ4ZLKjUTA6xqQ7p9VndmVjwdFCH5BAAAAAAALAAAAAAjABoABwj/AItQ63bGzBMzZtips7BvX5wj+9IkKhEHwRFoqa5ptPDmibkzHuc4oYeLZJEiCWOwm0MOjw88+XzJlGWoxRhxTXB1Y8ZsypkzRXCJKTJHJzN27B6Ii0DGFz86aqIG0KcvS59ePfqIg1SEGTR1zH4+EEMtxRSfffKEmccvQpYsmyjo67JlS5cLQwBtyZEDEi5zFqBNsTKH2oOzc7IUmkciwp5NeR736QPo0y0Kn7aUGTJn1xZTd6wEnmL4zZsrhiS03bQp2qYugIQ9IAbkyhtPF7YM4TxnBZhdZZ5M2UfM9JUsdNruCUF3CDEr3Yil6EYHUhpmnk7OmXPhSpEEc1JA/0sBhJg+1fq0adO3jIkVoE7EXHuAxFWaCdlxFb2C64K5OUWk8QYQOfCzRySs9cFEPD/E88B2J5lRAwh/IPCGOil8ZM4V5nRoDjNWmLNJISTsUUwegJyjiBAICLCKJ08EN4cGjrhgzgTnnGGFJ+YU8QCH5lgxhBoG1nIiEOfMMoAALdJAAy5WIJCDCISwsUQ88fBYRI9XcPjGFnREEMkeewDiRD1DXJLBABlk8IgWIMjDCAhoPEJFLSGw8gYzDxRxwQWrMNNHGI9FE4EwwrxBQyhrZLAGG1qgAYIjjMjzyCNt8jBLBDkwQxR3VpCDwWOb7CEMIFawMsujA2jyyquEiP8ggi5rUIFBCP4FecUcZZQxBSBZUEUVIPFYQQcbPxwRw7IpxABEMI6G8kk8CKTx3wMbcjcFS33MxR4x9dTjyTlzWMEOOs958ocuodAwwQQ/BGnFGxl2yA4xQ3TRBQWwDfEAE4gC2SUzvnQgCw2r/BDvdg90I8YV1Jh7Whd96Asbog/IxkQOQ5TxiSCG7HBBAjYkAEkOFazgBDXUELPsPm/MkQNdXSwDyG4XCJObOUOQg8IXOWgDydCQ7LLCCtQ4cQU7R4gXgxVX7NVFDjbfkpduZWxxizZb7CB0OFtA0oTRKzTRDTSJ5EDMWcxckIPUOdx8CyC3vP0AcDdfcQGvvbWusUIRFiSSiDjlQhPHG/oNUdcK23W5N6+AzNHhSRAXcY8Z2whugTgVLH3EERa89+AcXf74Y29XPJDCCl2WtEAD1wi+jTp99CCOMOwYDhE7RThB+hViPEANxKxTgws199zTzTUyACBDKg2ok0cv4nB8BkMWpGJBDGaIQQ/L1CTDshhnSPPBNdvAI4MMGjXQwD9YaWXKAxZkj07696NDyv78q9NAKttIn/rYl5FrNCAgADs=";

var FARMNAME=null;
var USERLEVEL=null;
// cases(%=number): %=money, "c%"=coins, "f%"=fictive money
const NPC=[[,0.5,1.1,1.34,2.75,3.95,8.05,17.8,18.5,"f85","f110","f180","f280",,,,,0.16,0.52,1.02,1.44,1.96,2.28,3.8,3.69,"f340",4.38,"f510","f590",12.4,"f650",3.49,5.19,8.75,6,15.63,16.88,37.5,3.9,52.44,51.75,60.25,58.13,66.19,18.2,"c79",150,,1200,,1200,,,,,4500,,14400,1200,,"c125",,"c23",,4800,4200,,,,,,,,750,2100,"c25",,,,,,,10800,12000,,1500,3300,,,,,"f650","f1500","f1500",5000,12000,"c10",,"c20",,"c5","c5","c5","c5",,"c5",,,10.12,3.72,"f155.1","f545.7",37.42,23.32,7.44,82.36,"f106.8","f148.8","f69.6","f196.8","f278.4","f408","f240","f324","f250","f864",47.15,42.8,76.44,,"f12.8","f73.5","f127","f106","f53.05","f113.75","f44","f33.33","f71.3","f73.2","f181.2","f321","f316","f491","f350","f484.2","f906.5","f421.7","f473.5","f749.98","f237.1","f675","f975",12.25,37.5,"f1025","f1100","f810",],{},[],[]]; // task_new_plant task_new_product
	/*
	var new_NPC=NPC.clone();
	new_NPC[0][155]=37.5;
	GM_log(implode(new_NPC));
	*/
const INIT_NPCSAISON={"94":false,"95":false,"96":false,"98":false,"100":false,"101":false,"102":false,"103":false,"105":false}; // task_new_product
var NPCSAISON = INIT_NPCSAISON;
const ALL_ZONES = {"farm":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],"windmill":["windmill"],"forestry":["forest","sawmill","carpentry"],"foodworld":["foodworld-1","foodworld-2"]}; // task_new_zone
unsafeData.ALL_ZONES=ALL_ZONES.clone();
const DATA_zones = {"1":{"location":"farm","farmNr":0},"2":{"location":"farm","farmNr":0},"3":{"location":"farm","farmNr":0},"4":{"location":"farm","farmNr":0},"5":{"location":"farm","farmNr":0},"6":{"location":"farm","farmNr":0},"7":{"location":"farm","farmNr":1},"8":{"location":"farm","farmNr":1},"9":{"location":"farm","farmNr":1},"10":{"location":"farm","farmNr":1},"11":{"location":"farm","farmNr":1},"12":{"location":"farm","farmNr":1},"13":{"location":"farm","farmNr":2},"14":{"location":"farm","farmNr":2},"15":{"location":"farm","farmNr":2},"16":{"location":"farm","farmNr":2},"17":{"location":"farm","farmNr":2},"18":{"location":"farm","farmNr":2},"19":{"location":"farm","farmNr":3},"20":{"location":"farm","farmNr":3},"21":{"location":"farm","farmNr":3},"22":{"location":"farm","farmNr":3},"23":{"location":"farm","farmNr":3},"windmill":{"location":"windmill"},"forest":{"location":"forestry"},"sawmill":{"location":"forestry"},"carpentry":{"location":"forestry"},"foodworld-1":{"location":"foodworld"},"foodworld-2":{"location":"foodworld"}}; // task_new_zone
unsafeData.DATA_zones=DATA_zones.clone();
// All single-slot-zones themselves and all slots of multi-slot-zones
var ALL_SLOTS={};
// Growing duration in min
const PRODUCT_GROWTIME=[[,20,45,45,90,120,240,480,960,240,720,1440,2880,,,,,15,90,240,480,600,500,800,720,1000,780,2000,3000,950,4000,1000,720,1200,800,2000,880,3000,960,4000,4800,5500,6200,6800,7200,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2880,,,,,,720,,,,,,,740,,,700,360,135,2160,1000,1440,1680,540,5100,840,1080,480,1320,1800,2520,1260,1620,720,3780,6400,7400,7800,640,180,180,90,90,200,200,100,130,150,80,80,120,120,120,375,300,240,300,480,220,360,3120,3240,1440,1920,1440,2520,840,600],{"1":600,"2":960,"3":2160,"4":480,"5":2750,"6":490,"41":300,"42":345,"43":360,"44":270,"45":300,"46":330,"47":420,"48":480,"49":510,"50":180,"51":210,"52":240,"53":480,"54":510,"55":540,"101":240,"102":700,"103":640,"104":360,"105":960,"106":90,"107":120,"108":1320,"109":570,"110":330,"111":160,"112":935,"113":120,"114":300,"115":180,"116":1040,"117":1920,"118":300,"119":1440,"120":2010,"500":0,"501":0,"502":0,"511":0,"512":0}]; // task_new_plant task_new_product
	/*
	var new_PRODUCT_GROWTIME=PRODUCT_GROWTIME.clone();
	new_PRODUCT_GROWTIME[0][155]=32*60;
	GM_log(implode(new_PRODUCT_GROWTIME));
	*/
// Points earned at cropping
const PRODUCT_POINTS=[[,3,17,10,44,64,128,267,600,750,950,1540,2350,,,,,1,7,24,42,63,52,88,92,3100,108,4500,5000,319,5400,179,133,229,157,405,733,2569,211,3611,4444,5220,6028,6769,1833,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,2500,,,,,,0,,,,,,,0,,0,0,179,31,2300,4900,490,340,240,1174,890,1240,580,1640,2320,3400,2000,2700,1250,7200,1475,1552,1636,0,36,36,18,18,40,36,20,26,30,16,16,24,24,24,3600,60,48,60,69,44,72,5400,7750,450,2600,8250,9725,6250,0],{"1":30,"2":48,"3":108,"4":24,"5":138,"6":0,"21":0,"22":0,"23":0,"24":0,"25":0,"41":150,"42":105,"43":108,"44":108,"45":60,"46":66,"47":294,"48":144,"49":153,"50":54,"51":42,"52":48,"53":48,"54":51,"55":54,"101":48,"102":140,"103":128,"104":74,"105":0,"106":18,"107":66,"108":0,"109":114,"110":70,"111":32,"112":187,"113":24,"114":60,"115":36,"116":208,"117":384,"118":660,"119":0,"120":0,"500":0,"501":0,"502":0,"511":0,"512":0}]; // task_new_plant task_new_product
	/*
	var new_PRODUCT_POINTS=PRODUCT_POINTS.clone();
	new_PRODUCT_POINTS[0][155]=2600;
	GM_log(implode(new_PRODUCT_POINTS));
	*/
// Required quest to unlock product
const PRODUCT_QUEST=[{"117":["farm",2,15],"118":["farm",2,25],"119":["farm",2,35],"120":["farm",2,45],"121":["farm",2,50],"123":["farm",2,15],"124":["farm",2,25],"125":["farm",2,35]},{"1":["lodge",1,3],"2":["lodge",1,9],"3":["lodge",1,24],"4":["lodge",1,47],"5":["lodge",1,63],"21":["lodge",1,3],"22":["lodge",1,9],"23":["lodge",1,24],"24":["lodge",1,47],"25":["lodge",1,63],"41":["lodge",1,6],"42":["lodge",1,6],"43":["lodge",1,6],"44":["lodge",1,9],"45":["lodge",1,9],"46":["lodge",1,9],"47":["lodge",1,24],"48":["lodge",1,24],"49":["lodge",1,24],"50":["lodge",1,47],"51":["lodge",1,47],"52":["lodge",1,47],"53":["lodge",1,63],"54":["lodge",1,63],"55":["lodge",1,63],"101":["lodge",1,12],"102":["lodge",1,18],"103":["lodge",1,21],"104":["lodge",1,27],"105":["lodge",1,30],"106":["lodge",1,33],"107":["lodge",1,36],"108":["lodge",1,39],"109":["lodge",1,42],"110":["lodge",1,60],"111":["lodge",1,50],"112":["lodge",1,53],"115":["lodge",1,66],"116":["lodge",1,69],"117":["lodge",1,75],"118":["lodge",1,72],"119":["lodge",2,16],"120":["lodge",2,24]}];
// Required products to produce
const PRODUCT_REQUIRE=[{"130":[[0,17,400]],"131":[[0,21,150]],"132":[[0,20,100],[0,10,2]],"133":[[0,19,100],[0,10,2]],"134":[[0,17,400],[0,6,25]],"135":[[0,21,150],[0,6,25]],"136":[[0,2,120]],"137":[[0,1,200]],"138":[[0,1,200],[0,23,30]],"139":[[0,18,150],[0,22,30]],"140":[[0,21,150],[0,22,30]],"141":[[0,26,100],[0,144,3]],"142":[[0,26,100],[0,25,3]],"143":[[0,26,100],[0,25,3],[0,144,3]],"145":[[0,33,300],[0,12,2]],"146":[[0,35,200],[0,10,4],[0,12,2]],"147":[[0,37,60],[0,12,2]],"148":[[0,31,250],[0,26,150],[0,27,7]],"149":[[0,21,300],[0,43,10],[0,22,50],[0,121,4]],"150":[[0,38,60],[0,119,6],[0,17,50]]},{"41":[[1,21,1]],"42":[[1,21,1]],"43":[[1,21,1]],"44":[[1,22,1]],"45":[[1,22,1]],"46":[[1,22,1]],"47":[[1,23,1]],"48":[[1,23,1]],"49":[[1,23,1]],"50":[[1,24,1]],"51":[[1,24,1]],"52":[[1,24,1]],"53":[[1,25,1]],"54":[[1,25,1]],"55":[[1,25,1]],"101":[[1,41,4]],"102":[[1,41,18],[1,42,2]],"103":[[1,44,11]],"104":[[1,42,1],[1,43,5]],"105":[[1,44,20],[1,45,50],[1,46,70]],"106":[[1,49,1]],"107":[[1,46,1]],"108":[[1,47,125],[1,48,65],[1,49,32]],"109":[[1,47,5]],"110":[[1,50,9],[1,51,4]],"111":[[1,52,4]],"112":[[1,50,12],[1,51,7],[1,52,6]],"113":[[1,42,1]],"114":[[1,41,1],[1,43,1]],"115":[[1,53,8],[1,55,2]],"116":[[1,53,120],[1,54,40],[1,55,40]],"117":[[1,53,80],[1,54,65],[1,55,125]],"118":[[1,53,6],[1,54,8]],"119":[[1,54,20],[1,55,25]],"120":[[1,54,35],[1,55,40]]}]; // task_new_picnic_product
// Yielded amount of production
const PRODUCT_YIELD=[,{"1":1,"2":1,"3":1,"4":1,"5":1,"21":1,"22":1,"23":1,"24":1,"25":1,"41":5,"42":3,"43":3,"44":4,"45":2,"46":2,"47":7,"48":3,"49":3,"50":3,"51":2,"52":2,"53":8,"54":4,"55":4,"101":1,"102":1,"103":1,"104":1,"105":1,"106":1,"107":1,"108":1,"109":1,"110":1,"111":1,"112":1,"113":1,"114":1,"115":1,"116":1,"117":1,"118":1,"119":1,"120":1}];

// [farm, forestry, recipes, powerups]
var prodName=new Array();
var prodId=new Array();
var recipeNameToId=null; //TODO maybe rename / save as var
var prodTyp=new Array(); //c:coins, v:plant, e:product, u:garbage, z:deco, f:forestry, d:forestry deco
var prodBlock=new Array(); //c:only by club, u:garbage, l:level too low, t:not tradable, f:forestry, q:lodge quest too low
var prodMinRackInit=new Array(); // initial minimal rack amounts
// integer<0 is possible and means something like "product is produced"
// call: unsafeWindow.prodMinRackAddon.add(type,1,"Mill-Queue",20000);
// call: unsafeWindow.prodMinRackAddon.remove(type,1,"Mill-Queue");
var prodMinRackAddon=new Array(new Array(), new Object()); // additional minimal rack data from addons
unsafeWindow.prodMinRackAddon=new Object();
unsafeWindow.prodMinRackAddon.newdata=new Array();
unsafeWindow.prodMinRackAddon.busy=false;
var prodMinRack=new Array(); // + quest amount - field and powerup amounts
var prodNameSort=new Array(); // sorted by type(cveoz)
var prodStock=new Array();
var prodStockMax=new Array();//if not id is undefined then there is no max
var prodPlantSize=new Array();
var prodYield=new Array();
var prodRequire=new Array();
var prodPoints=new Array();
var prodGrowTime=new Array();
var gut=new Array();
var gutBeob=new Array();
var preisBeob=new Array();
var css_styles=new Object();

// QUESTS["farm"][campaign][nr] , QUESTS["lodge"][campaign][nr] 
// [[[type1,id1,amount1],...],waitdays,points,more]
// more: Array of items:
// [0,money]
// [1,type of gained product,id of gained product,amount]
// [2,number of accessed rack]
// [3,number of accessed farm]
// [4,type of product,id of product,minutes this product grows faster]]
// [5,number of additional farmis ('<img src=GFX+"adbonus.gif" style="border:0;height:15px;">')]
// [6,Erhoehung der Lagerkapazitaet Staemme um x]
// [7,Giessbonus x%]
// [8,id of accessed zone]
// [9,type of accessed product,id of accessed product]
// [10] access to watering of forest
// [11,number of additional farmi slots]
// task_new_quest:
const QUESTS = {"farm":{"1":[,[[[0,17,43],[0,9,1]],1,142,[[0,54]]],[[[0,1,173],[0,9,2]],1,348,[[0,145]]],[[[0,18,192],[0,17,288]],1,255,[[0,73]]],[[[0,18,672],[0,9,10]],1,1883,[[0,608]]],[[[0,17,922],[0,9,19]],1,2304,[[0,890]]],[[[0,20,360],[0,18,960]],1,3300],[[[0,19,540],[0,20,720]],1,6413],[[[0,2,240],[0,21,245]],1,2895],[[[0,20,1440],[0,9,24]],1,11700,[[1,0,47,1]]],[[[0,21,1152],[0,9,48]],1,16200],[[[0,9,72],[0,22,1037]],1,16202],[[[0,20,3456],[0,10,27]],1,25476],[[[0,18,8064],[0,10,48]],1,15660],[[[0,23,3110],[0,9,144]],1,57240],[[[0,10,96],[0,9,180]],1,33930,[[1,0,59,1]]],[[[0,9,240],[0,6,1836]],1,62190],[[[0,10,384],[0,9,144]],1,70920],[[[0,10,192],[0,23,6739]],1,116280,[[2,2]]],[[[0,22,7518],[0,9,216]],1,108956],[[[0,11,150],[[0,10,272],[0,110,112]]],1,34650],[[[0,7,1350],[0,12,50]],1,78375,[[1,0,63,1]]],[[[0,23,15552],[0,9,1008]],1,318600],[[[0,29,6552],[0,25,130]],1,373645,[[3,2]]],[[[0,1,51840],[[0,27,55],[0,111,51]]],1,60579],[[[0,11,280],[0,12,210]],1,138705],[[[[0,10,672],[0,110,276]],[0,12,210]],1,169785],[[[0,1,75600],[0,2,25000]],1,42131,[[1,0,90,1]]],[[[0,11,480],[0,12,272]],1,206760],[[[0,9,2688],[[0,10,1024],[0,110,420]]],1,448320],[[[0,12,320],[0,11,560]],1,242160],[[[0,29,14742],[[0,27,194],[0,111,180]]],1,836328,[[2,3]]],[[[0,20,77760],[0,12,383]],1,620831,[[1,0,78,1]]],[[[0,12,540],[0,32,14600]],1,449550],[[[0,32,50400],[0,25,432]],1,1208880],[[[[0,10,1760],[0,110,722]],[0,11,1000]],1,481800,[[3,3]]],[[[0,9,4800],[0,12,595]],1,749738],[[[0,26,46550],[[0,27,216],[0,111,201]]],1,933756,[[1,0,77,1]]],[[[0,1,259200],[0,30,216]],1,252960],[[[0,23,51840],[0,28,230]],1,856800],[[[0,9,5280],[[0,10,1795],[0,110,736]]],1,849816],[[[0,25,475],[0,30,238]],1,1665576,[[1,0,80,1]]],[[[0,34,64152],[0,28,253]],1,1704780],[[[0,11,1320],[0,12,880]],1,615120],[[[[0,27,238],[0,111,221]],[0,24,30294]],1,576923,[[1,0,76,1]]],[[[[0,10,2304],[0,110,945]],[0,30,259]],1,538272],[[[0,9,5760],[[0,10,2304],[0,110,945]]],1,976320],[[[0,37,13800],[0,25,518]],1,5559806,[[1,0,61,1]]],[[[0,9,5760],[[0,10,1958],[0,110,803]]],1,927072],[[[0,28,276],[0,30,259]],1,417312],[[[0,12,1040],[0,30,281]],1,376253,[[1,0,52,1]]],[[[0,20,72000],[0,12,800]],1,732000,[[4,0,23,15]]],[[[0,12,4000],[[0,10,1920],[0,110,787]]],1,1683600],[[[0,23,64800],[0,9,4800]],1,1395000],[[[0,25,432],[0,28,230]],1,373680,[[4,0,24,15]]],[[[0,24,72000],[[0,27,216],[0,111,201]]],1,1135800],[[[0,7,18000],[[0,10,1920],[0,110,787]]],1,1083600],[[[[0,27,216],[0,111,201]],[0,11,1200]],1,423000,[[4,0,31,15]]],[[[0,31,103700],[0,30,216]],1,2965498],[[[0,11,1200],[0,25,432]],1,478080,[[4,0,21,10]]],[[[0,21,57600],[[0,10,1920],[0,110,787]]],1,813600],[[[0,12,800],[[0,27,216],[0,111,201]]],1,427800,[[4,0,29,15]]],[[[0,29,27300],[0,25,432]],1,1506635],[[[0,4,48000],[0,9,4800]],1,855000],[[[0,28,230],[[0,27,216],[0,111,201]]],1,318600,[[4,0,33,15]]],[[[0,33,43200],[0,25,432]],1,1685880,[[5,1]]],[[[0,9,4800],[0,12,800]],1,822000,[[4,0,22,10]]],[[[0,8,18000],[0,28,230]],1,1792800],[[[[0,10,1920],[0,110,787]],[0,11,1200]],1,550800,[[4,0,34,15]]],[[[0,34,64800],[0,30,216]],1,1704960],[[[0,6,10800],[0,28,230]],1,207000],[[[0,11,1200],[[0,10,1920],[0,110,787]]],1,550800,[[4,0,35,20]]],[[[0,35,12950],[[0,27,216],[0,111,201]]],1,932692],[[[0,25,432],[0,11,1200]],1,478080],[[[0,32,72000],[0,12,800]],1,1722000,[[4,0,36,15]]],[[[0,36,24500],[0,9,4800]],1,3235000],[[[[0,27,216],[0,111,201]],[0,30,216]],1,320760,[[4,0,7,10]]],[[[0,26,66500],[0,28,230]],1,1298451],[[[0,12,800],[[0,10,1920],[0,110,787]]],1,555600,[[4,0,37,30]]],[[[0,37,3833],[0,9,4800]],1,2017431],[[[0,28,230],[0,25,432]],1,373680],[[[0,33,43200],[0,12,800]],1,1767000,[[4,0,38,15]]],[[[0,38,108000],[0,30,216]],1,3594960],[[[0,9,4800],[0,28,230]],1,712800,[[4,0,19,5]]],[[[0,5,72000],[[0,10,1920],[0,110,787]]],1,963600],[[[0,30,216],[0,9,4800]],1,714960,[[4,0,39,30]]],[[[0,39,2867],[0,12,800]],1,1834778],[[[[0,10,1920],[0,110,787]],[0,25,432]],1,474480],[[[0,32,72000],[[0,27,216],[0,111,201]]],1,1585800,[[4,0,40,30]]],[[[0,40,2250],[0,12,800]],1,1782000],[[[0,25,432],[0,11,1200]],1,478080,[[4,0,20,10]]],[[[0,3,64000],[0,30,216]],1,374960],[[[[0,27,216],[0,111,201]],[0,11,1200]],1,423000,[[4,0,41,30]]],[[[0,41,1975],[[0,10,1920],[0,110,787]]],1,1819998],[[[0,11,1200],[[0,27,216],[0,111,201]]],1,423000,[[4,0,8,15]]],[[[0,24,72000],[[0,10,1280],[0,110,787]]],1,1172400,[[5,1]]],[[[0,12,800],[0,9,4800]],1,822000,[[4,0,26,15]]],[[[0,36,24500],[0,28,230]],1,2867800],[[[0,31,103700],[[0,10,1920],[0,110,787]]],1,3064138,[[4,0,42,30]]],[[[0,28,230],[0,25,432]],1,373680],[[[0,42,1680],[0,30,216]],1,1693960,[[4,0,33,15]]],[[[0,4,80000],[0,30,210]],2,722800],[[[0,6,48000],[0,12,300]],2,854400],[[[0,1,800000],[0,25,320]],2,998400,[[4,0,32,10]]],[[[0,35,64000],[0,32,12000]],2,1629600],[[[0,26,108000],[0,11,540]],2,1452600],[[[0,39,12000],[0,9,5600]],2,2160000,[[4,0,43,30]]],[[[0,43,10000],[[0,27,600],[0,111,558]]],2,2556000],[[[0,24,184000],[0,25,480]],2,2248000],[[[0,9,10200],[[0,10,24000],[0,110,9840]]],2,2205600],[[[0,23,108000],[0,91,250]],2,1359600],[[[0,34,36936],[0,37,10580]],2,1959726],[[[0,29,78624],[0,26,5200]],2,2164176],[[[0,44,2016],[0,28,1600]],2,2059245],[[[[0,10,12000],[0,110,4920]],[0,12,1200]],2,1536000],[[[0,30,840]],2,906800],[[[0,40,3240],[0,36,9800]],2,1265312],[[[0,91,750],[0,31,72590]],2,1233972],[[[0,26,113050],[[0,27,600],[0,111,558]]],2,1874430],[[[0,38,7020],[0,42,2352]],2,2134942],[[[0,41,9480],[0,9,28800]],2,1886172,[[5,1]]],[[[0,23,174960],[0,22,98515]],2,2267541],[[[0,8,5040],[0,7,3780]],2,2022804],[[[0,32,27000],[[0,10,24000],[0,110,9840]]],2,2357400],[[[0,39,2580],[0,37,7935]],2,1525641,[[1,0,99,1]]],[[[0,33,51840],[0,35,20720]],2,2464720],[[[0,43,5000],[0,21,146880]],2,2139910],[[[0,31,60664],[0,26,100520]],2,1945541],[[[0,20,100800],[0,9,15360]],2,1216320,[[4,0,44,20]]],[[[[0,10,10080],[0,110,4132]],[0,11,4500]],2,1571400],[[[0,7,18900],[0,38,5400]],2,2239480],[[[0,40,3500],[0,35,12000]],2,1168200],[[[0,91,1000]],2,600000],[[[0,44,4400],[0,26,22400]],2,1284560],[[[0,3,280000],[0,31,40000]],2,1328000],[[[0,12,1200],[0,39,3900]],2,1228860],[[[0,7,9800],[0,2,240000]],2,1003320],[[[0,26,60000],[0,1,275000]],2,1031000],[[[0,11,6400]],2,1088000],[[[0,6,14444],[0,33,34000]],2,1158911],[[[[0,27,625],[0,111,581]]],2,1078125],[[[0,38,8600],[0,41,2900]],2,1056220],[[[0,43,4050],[0,7,5250]],2,1133280],[[[0,9,16200]],2,453600,[[5,1]]],[[[0,25,900],[[0,10,5400],[0,110,2214]]],2,990000],[[[0,37,8600]],2,1016520],[[[0,28,300],[[0,10,7500],[0,110,3075]]],2,1050000],[[[0,30,400],[0,42,3600]],2,1096880],[[[0,29,51000],[0,9,3600]],2,1069800],[[[0,91,175],[0,8,18200]],2,1087560],[[[0,36,10300],[0,41,3800]],2,1312700],[[[0,24,90000],[[0,10,800],[0,110,328]]],2,1028000],[[[0,22,95500],[0,1,300000]],2,930300],[[[0,35,13000],[0,32,33000]],2,1176800],[[[0,17,155000],[0,21,99999]],2,1049993],[[[0,38,13000],[[0,27,250],[0,111,232]]],2,1104650],[[[0,37,4444],[0,39,3333]],2,1083225],[[[0,2,122000],[0,21,122000]],2,1146800],[[[0,20,112000],[[0,10,2800],[0,110,1148]]],2,1097600],[[[0,9,1111],[0,26,66000]],2,1142108],[[[0,11,2320],[0,23,72000]],2,1200800],[[[0,19,116000],[0,25,900]],2,976200,[[5,1]]],[[[0,5,220000],[0,12,720]],2,1049600],[[[0,18,240000],[0,6,50000]],2,1028000],[[[0,41,4400],[0,1,150000]],2,1076640],[[[0,40,3250],[0,30,500]],2,1069300],[[[0,29,45000],[0,20,25000]],2,1050000],[[[0,91,840],[0,1,510000]],2,1014000],[[[0,34,45000],[0,12,680]],2,1190400],[[[0,31,425000],[0,43,2800]],2,1048680],[[[[0,10,7500],[0,110,3075]],[0,3,140000]],2,1048000,[[7,5]]]]
					   ,"2":[,[[[0,8,6500],[0,12,300]],,495000],[[[0,34,18600],[0,111,75]],,496298],[[[0,33,5650],[0,30,315]],,498270],[[[0,26,15600],[0,9,11200]],,506380],[[[0,37,2150],[0,12,530]],,508530],[[[0,18,175000],[0,91,505]],,511250],[[[0,108,6350],[0,7,5400]],,505010],[[[0,35,6530],[0,110,950]],,507946],[[[0,24,19150],[0,27,412]],,511190],[[[0,23,33000],[0,25,480]],,518500,[[3,4]]],[[[0,28,366],[0,46,100]],,516000],[[[0,116,460],[0,11,1400]],,523880],[[[0,21,42000],[0,9,8000]],,534800],[[[0,32,15420],[0,10,3630]],,540204],[[[0,7,5000],[0,30,265]],,550550,[[9,0,117],[9,0,123]]],[[[0,116,480],[0,91,777]],,551640],[[[0,19,84000],[0,110,1255]],,554475],[[[0,117,917],[0,18,277000]],,559816],[[[0,12,625],[0,109,42000]],,560400],[[[0,108,12300],[0,116,670]],,559600],[[[0,5,50500],[0,26,32000]],,564800],[[[0,117,490],[0,9,16000]],,569520],[[[0,29,16600],[0,31,24000]],,574600],[[[0,33,18200],[0,11,1800]],,589560],[[[0,4,40450],[0,116,1560]],,594810,[[9,0,118],[9,0,124]]],[[[0,3,110000],[0,12,515]],,599200],[[[0,17,75000],[0,10,6800]],,605000],[[[0,91,700],[0,34,9900]],,610080],[[[0,2,155000],[0,28,305]],,615000],[[[0,37,3800],[0,118,1450]],,617360,[[8,"20"]]],[[[0,1,172350],[0,111,558]],,622350],[[[0,117,1090],[0,36,5800]],,625320],[[[0,12,900],[0,25,310]],,624400],[[[0,31,38380],[0,118,1800]],,623304],[[[0,38,9200],[0,116,840]],,623304,[[9,0,119],[9,0,125]]],[[[0,65,10],[0,27,680]],,623333],[[[0,36,7500],[0,9,8000]],,627000],[[[0,6,13150],[0,110,2214]],,626620],[[[0,37,2415],[0,11,2000]],,625453],[[[0,119,735],[0,30,360]],,626280],[[[0,21,19000],[0,10,6120]],,630200],[[[0,33,14400],[0,35,4750]],,634970],[[[0,38,8200],[0,111,116]],,640341],[[[0,73,30],[0,28,600]],,650000],[[[0,42,2980],[0,117,430]],,660324,[[9,0,120]]],[[[0,39,2250],[0,12,666]],,696030],[[[0,40,2400],[0,30,286]],,700580],[[[0,41,2200],[0,118,2275]],,702800],[[[0,20,36000],[0,23,38000]],,706400],[[[0,43,1850],[0,120,690]],,709770,[[9,0,121]]],[[[0,108,14000],[0,8,13200]],,715040],[[[0,40,1950],[0,9,14200]],,719600],[[[0,39,1900],[0,116,1540]],,729920],[[[0,27,268],[0,43,1300]],,735580],[[[0,42,2300],[0,109,34850]],,740010],[[[0,112,3300],[0,121,500]],,748000],[[[0,41,2500],[0,111,138]],,754830],[[[0,119,1000],[0,29,22750]],,760250],[[[0,112,3300],[0,22,52300]],,766260],[[[0,32,24799],[0,9,13333]],,766260,[[8,"21"]]],[[[0,113,9100],[0,27,400]],,750000],[[[0,44,1142],[0,144,790]],,755000],[[[0,154,1695],[0,111,210]],,760000],[[[0,24,39500],[0,118,2350]],,765000],[[[0,153,6250],[0,26,22650]],,765000],[[[0,23,39500],[0,28,385]],,770000],[[[0,6,34500],[0,122,37]],,770000],[[[0,32,13400],[0,10,3900]],,775000],[[[0,39,990],[0,38,8400]],,775000],[[[0,144,1150],[0,123,46]],,780000],[[[0,9,7900],[0,151,85]],,780000],[[[0,5,56200],[0,4,41500]],,785000],[[[0,64,15],[0,152,80]],,785000],[[[0,31,28500],[0,91,550]],,790000],[[[0,20,59000],[0,30,720]],,790000,[[8,"22"]]],[[[0,114,15000],[0,29,25000]],,795000],[[[0,120,400],[0,11,4500]],,795000],[[[0,2,150000],[0,6,45000]],,800000],[[[0,40,9000],[0,25,200]],,800000],[[[0,7,28000],[0,30,225]],,805000],[[[0,32,65000],[0,1,190000]],,805000],[[[0,109,125000],[0,108,65000]],,810000],[[[0,22,92000],[0,27,450]],,810000],[[[0,124,1125],[0,21,85000]],,815000],[[[0,36,9500],[0,112,6600]],,815000],[[[0,116,840],[0,24,63000]],,820000],[[[0,26,63000],[0,117,700]],,820000],[[[0,152,120],[0,44,15000]],,825000],[[[0,144,450],[0,113,30000]],,825000],[[[0,125,650],[0,151,550]],,830000,[[8,"23"]]]]
					   }
			   ,"lodge":{"1":[,[[[0,4,3300],[0,19,4500],[0,24,1400]],,51520],[[[0,5,2600],[0,17,8000],[0,91,50]],,50360],[[[0,6,1250],[0,21,6600],[0,18,7300]],,0,[[1,1,1,5],[8,"forest"],[9,1,1],[9,1,21]]],[[[0,22,1400],[0,7,750]],,48630],[[[0,25,64],[0,3,3200],[1,21,8]],,50800],[[[0,8,650],[0,27,85],[0,4,4800],[0,91,25]],,0,[[8,"sawmill"],[9,1,41],[9,1,42],[9,1,43]]],[[[0,10,420],[0,19,1600]],,39360],[[[0,2,6000],[0,22,2100],[0,21,1800]],,38980],[[[0,24,1800],[1,21,12],[1,41,10]],,0,[[1,1,2,5],[9,1,2],[9,1,22],[9,1,44],[9,1,45],[9,1,46]]],[[[0,3,3200],[0,5,3150],[0,20,1900]],,36200],[[[0,27,40],[0,18,7700]],,39240],[[[0,91,60],[1,22,30],[1,44,12]],,0,[[8,"carpentry"],[9,1,101]]],[[[0,8,300],[0,6,2000]],,39600],[[[0,17,16000],[1,22,30],[1,42,10]],,34520],[[[0,11,90],[1,101,6],[1,22,18]],,0,[[10]]],[[[0,22,800],[0,7,430],[0,2,2200]],,32642],[[[0,10,380]],,30400],[[[0,9,460],[1,41,20]],,0,[[9,1,102]]],[[[0,19,2600],[0,3,3000],[0,18,5400],[0,4,1200]],,31740],[[[0,91,15],[0,26,1700]],,31420],[[[0,25,35],[0,5,2800],[1,102,4]],,0,[[9,1,103]]],[[[0,24,1900],[0,6,1400]],,31060],[[[0,20,1350],[0,23,1250],[0,1,4900]],,30230],[[[0,12,75],[0,21,2500],[1,45,15]],,0,[[1,1,3,5],[9,1,3],[9,1,23],[9,1,47],[9,1,48],[9,1,49]]],[[[0,8,310],[0,9,240]],,31520],[[[0,7,130],[0,6,400],[0,27,30]],,32562],[[[0,3,5400],[1,23,18],[1,103,3]],,0,[[9,1,104]]],[[[0,11,185]],,31450],[[[0,22,1900],[0,91,22],[0,2,2600]],,30940],[[[0,10,110],[1,41,32],[1,101,24]],,0,[[9,1,105]]],[[[0,25,55],[1,46,27]],,35025],[[[0,20,2300],[0,23,1350],[1,43,36]],,34485],[[[0,5,2000],[1,104,12],[1,47,72]],,0,[[9,1,106]]],[[[0,26,2100],[0,8,150]],,36600],[[[0,3,2200],[0,18,4500],[0,19,3000],[0,4,1400],[0,17,2800]],,37520],[[[0,9,600],[1,106,20]],,0,[[9,1,107]]],[[[0,7,700]],,37380],[[[0,29,1400],[0,12,40]],,42000],[[[0,1,45000],[1,107,52],[1,48,18]],,0,[[9,1,108]]],[[[0,5,3000],[0,11,240]],,44400],[[[0,3,5800],[0,9,380],[0,21,2400]],,46970],[[[0,6,1600],[1,102,12],[1,23,48]],,0,[[9,1,109]]],[[[0,25,75]],,48500],[[[0,29,1200],[0,8,1300],[0,17,20000],[0,2,5600],[1,49,24]],,50340,[[5,1]]],[[[0,20,5400],[0,10,100],[1,42,35]],,52325],[[[0,26,450],[0,25,45],[0,9,850]],,52510],[[[0,5,18000],[0,4,3600],[1,109,50]],,0,[[1,1,4,5],[9,1,4],[9,1,24],[9,1,50],[9,1,51],[9,1,52]]],[[[0,11,100],[0,3,9200],[1,45,30],[1,103,18]],,52207],[[[0,91,50],[0,22,3300],[0,18,4000],[1,46,45]],,52953],[[[1,101,40],[1,21,80],[1,48,30]],,0,[[9,1,111]]],[[[0,21,3000],[0,23,1600],[0,6,800]],,51960],[[[0,25,50],[0,24,2200],[1,43,60]],,53008],[[[1,104,70],[1,107,55],[1,24,60]],,0,[[9,1,112]]],[[[0,8,500],[0,7,450]],,50730],[[[0,91,35],[0,2,3500],[0,29,1200],[1,23,30]],,52432],[[[0,11,290],[1,52,30]],,50496,[[5,1]]],[[[0,10,360],[0,9,720],[1,106,100]],,52200],[[[0,27,75],[1,112,15]],,50049,[[11,1]]],[[[0,23,2000],[0,12,60],[1,42,50],[1,102,20]],,53630],[[[1,50,65],[1,47,30],[1,111,50]],,0,[[9,1,110]]],[[[0,109,3500],[0,24,2500],[1,48,30]],,50792],[[[0,11,275],[1,22,60]],,51934],[[[0,10,250],[0,12,100],[1,41,50],[1,23,33]],,0,[[1,1,5,5],[9,1,5],[9,1,25],[9,1,53],[9,1,54],[9,1,55]]],[[[0,9,250],[0,23,4000]],,51800],[[[0,25,90],[0,18,6400],[0,21,1000],[1,44,50]],,55282],[[[0,108,7500],[1,53,15],[1,112,5]],,0,[[9,1,115]]],[[[0,6,500],[0,22,6250]],,48650],[[[0,3,9700],[0,17,30000],[0,5,2200],[1,25,36]],,51590],[[[0,91,50],[1,115,26],[1,101,62]],,0,[[9,1,116]]],[[[0,112,2900],[0,12,80],[1,22,32]],,54505],[[[0,108,3700],[0,11,200]],,51020],[[[0,27,125],[1,115,22]],,0,[[9,1,118]]],[[[0,29,2700],[1,104,27]],,54896],[[[0,10,380],[0,19,5100],[1,50,65],[1,109,8]],,52508],[[[0,91,40],[1,118,10],[1,50,80],[1,107,65]],,0,[[9,1,117],[7,5]]]]
						,"2":[,[[[0,111,45],[0,9,380]],,48150],[[[1,21,400]],,,[[6,100]]],[[[0,12,100],[0,5,315]],,49140],[[[1,24,350]],,,[[6,100]]],[[[0,26,3200],[0,9,220],[1,106,30]],,47452],[[[1,22,450]],,,[[6,100]]],[[[0,11,150],[1,111,35]],,51945],[[[1,21,600],[1,41,80]],,,[[6,100]]],[[[0,8,555],[1,44,40],[1,45,30]],,46164],[[[0,91,55],[1,23,550]],,,[[6,100]]],[[[1,25,150]],,103843],[[[1,102,22]],,276206],[[[1,115,45]],,145202],[[[1,21,650],[1,22,100]],,,[[6,100]]],[[[1,110,15]],,124977],[[[1,53,120],[1,55,50],[1,54,50]],,,[[9,1,119]]],[[[0,7,5200],[0,6,1200],[0,24,3500]],,103941],[[[1,21,350],[1,22,300]],,,[[6,100]]],[[[0,10,240],[0,27,85],[0,26,2500]],,135945],[[[1,1,125],[1,2,100],[1,3,90],[1,4,70],[1,5,50]],,138279],[[[1,109,30]],,168612],[[[0,144,40],[0,110,100],[0,12,50]],,,[[6,100]]],[[[1,103,20]],,179495],[[[1,53,210],[1,55,160]],,,[[9,1,120]]],[[[1,41,100],[1,48,75],[1,52,50]],,156645],[[[1,25,190]],,,[[6,100]]],[[[0,11,400]],,125956],[[[1,24,220],[1,47,50],[1,43,85]],,114596],[[[1,118,20]],,221544],[[[1,1,250],[1,2,200],[1,3,180],[1,4,140],[1,5,100]],,,[[6,100]]]]
						}
			   };
unsafeData.QUESTS=QUESTS.clone();
const INIT_questDataItem = {"nr":0,"time":now,"calcTo":0,"state":0,"given":{}};
const INIT_questData = {"farm":{"1":INIT_questDataItem,"2":INIT_questDataItem},"lodge":{"1":INIT_questDataItem,"2":INIT_questDataItem}};
// state: 0:not available, 1:not activated, 2:active
/*
// Generate PRODUCT_QUEST
var new_PRODUCT_QUEST=[];
for(var type in QUESTS){
	if(!QUESTS.hasOwnProperty(type)){ continue; }
	for(var campaign in QUESTS[type]){
		if(!QUESTS[type].hasOwnProperty(campaign)){ continue; }
		for(var nr=1;nr<QUESTS[type][campaign].length;nr++){
			if(QUESTS[type][campaign][nr][3]){
				for(var i=0;i<QUESTS[type][campaign][nr][3].length;i++){
					if(QUESTS[type][campaign][nr][3][i][0]==9){
						if(!new_PRODUCT_QUEST[QUESTS[type][campaign][nr][3][i][1]]){ new_PRODUCT_QUEST[QUESTS[type][campaign][nr][3][i][1]]={}; }
						new_PRODUCT_QUEST[QUESTS[type][campaign][nr][3][i][1]][QUESTS[type][campaign][nr][3][i][2]] = [type,parseInt(campaign,10),nr];
					}
				}
			}
		}
	}
}
for(type=0;type<new_PRODUCT_QUEST.length;type++){
	new_PRODUCT_QUEST[type].sortObj();
}
GM_log("new_PRODUCT_QUEST:\n"+implode(new_PRODUCT_QUEST));
*/
var questData;
top.unsafeData.autoAction=null;

//***********************************************************************************************************
// developer functions
function compareObjectsExistance(obj1,obj2,pre){
	if(typeof(pre)=="undefined") pre="";
	for(i in obj1){
		if(!obj1.hasOwnProperty(i)){ continue; }
		if(typeof obj2[i] == "undefined"){
			GM_log("miss in 2: "+pre+i);
		}else{
			if(typeof obj1[i] == "object"){
				compareObjectsExistance(obj1[i],obj2[i],pre+i+" : ");
			}
		}
	}
	for(i in obj2){
		if(!obj2.hasOwnProperty(i)){ continue; }
		if(typeof obj1[i] == "undefined"){
			GM_log("miss in 1: "+pre+i);
		}else{
			if(typeof obj2[i] == "object"){
				compareObjectsExistance(obj1[i],obj2[i],pre+i+" : ");
			}
		}
	}
}
function compareTexteExistance(lng1,lng2){
	GM_log("compareTexteExistance "+lng1+":"+lng2);
	texte=new Object();
	texte["category"]=new Object();
	texte["hilfe"]=new Object();
	loadTexte(lng1);
	var texte1=texte.clone();

	texte=new Object();
	texte["category"]=new Object();
	texte["hilfe"]=new Object();
	loadTexte(lng2);
	var texte2=texte.clone();

	loadTexte(LNG);
	compareObjectsExistance(texte1,texte2);
	GM_log("compareTexteExistance "+lng1+":"+lng2+" ok");
}
//compareTexteExistance("de","us");

//***********************************************************************************************************
//*********************** FUNCTIONS *************************************************************************
// DOM
function SortableTable (sortRow){
	// Sortable HTML table inspired by http://www.webtoolkit.info/
	// example-call: new SortableTable(x);
	// sorting by value-attribute of td-elements
	// only cols with sortdir-attribute in the thead-cell
	function sortCol(cell){
	try{
		var tableEl=cell;
		while(tableEl.tagName!="TABLE"){ tableEl=tableEl.parentNode; }
		var tbody=tableEl.getElementsByTagName("tbody")[0];
		var sortRow=cell.parentNode;
		var newclass,oldclass,sortdir;
		// clone the rows
	    var newRows=new Array();
	    for(j=0; j < tbody.rows.length; j++){
			newRows[j]=tbody.rows[j];
		}
		//sort them
		newRows.sort(function(a,b){
			aa=parseFloat(a.cells[cell.cellIndex].getAttribute("value"),10);
			if (isNaN(aa)) aa=0;
			bb=parseFloat(b.cells[cell.cellIndex].getAttribute("value"),10);
			if (isNaN(bb)) bb=0;
			return (aa-bb);
		});
		// set classes of headercells
		if (cell.getAttribute("sortdir") == "Asc"){
			newRows.reverse();
			sortdir="Desc";
		}else{
			sortdir="Asc";
		}
		cell.setAttribute("sortdir",sortdir);
		for(var i=0; i<sortRow.cells.length; i++){
			if(typeof(sortRow.cells[i].getAttribute("sortdir"))=="string"){
				oldclass=sortRow.cells[i].getAttribute("class");
				newclass=oldclass.replace(/sortableCol(.*)\b/,"sortableCol"+(i==cell.cellIndex?sortdir:""));
				if(oldclass!=newclass){ sortRow.cells[i].setAttribute("class",newclass); }
			}
		}
		// rebuild table
		for(i=0;i<newRows.length;i++){
			tbody.appendChild(newRows[i]);
		}
		tableEl=null;tbody=null;sortRow=null;newRows=null;
	}catch(err){ GM_log("ERROR sortCol\n"+sortRow.cells[i].innerHTML+"\n"+err); }
 	}
	// constructor actions
	try{
	for(var i=0; i<sortRow.cells.length; i++){
		if(typeof(sortRow.cells[i].getAttribute("sortdir"))=="string"){
			var oldclass=sortRow.cells[i].getAttribute("class");
			sortRow.cells[i].setAttribute("class",(oldclass?oldclass+" ":"")+"sortableCol");
			sortRow.cells[i].addEventListener("click",function (){
				sortCol(this);
				return false;
			},false);
		}
	}
	}catch(err){ GM_log("ERROR SortableTable\n"+err); }
 }
function bar(size,markvalue,maxvalue){
	size=Math.floor(size);
	var mark=Math.floor(size*markvalue/maxvalue);
	var cell=createElement("div",{"style":"border:2px solid black; position:absolute;width:"+size+"px;height:12px;"});
     	createElement("div",{"style":"position:absolute;width:"+mark+"px;height:12px;background-color:#5555FF;"},cell);
	return cell;
}
function setSelRange(inputEl, selStart, selEnd){
 if (inputEl.setSelectionRange){
  inputEl.focus();
  inputEl.setSelectionRange(selStart, selEnd);
 }else if (inputEl.createTextRange){
  var range=inputEl.createTextRange();
  range.collapse(true);
  range.moveEnd('character', selEnd);
  range.moveStart('character', selStart);
  range.select();
 }
}

// Strings
function getKeySymbol(keyCode){
	if((46<keyCode)&&(keyCode<91)){ return String.fromCharCode(keyCode); }
	var codelist={"8":"backspace","9":"tab","13":"enter","16":"shift","17":"ctrl","18":"alt","19":"pause/break","20":"caps lock","27":"escape","33":"page up","34":"page down","35":"end","36":"home","37":"<-","38":"up arrow","39":"->","40":"down arrow","45":"insert","46":"delete","91":"left window key","92":"right window key","93":"select key","96":"numpad 0","97":"numpad 1","98":"numpad 2","99":"numpad 3","100":"numpad 4","101":"numpad 5","102":"numpad 6","103":"numpad 7","104":"numpad 8","105":"numpad 9","106":"*","107":"+","109":"-","110":"decimal point","111":"divide","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","144":"num lock","145":"scroll lock","186":"semi-colon","187":"equal sign","188":",","189":"dash","190":"period","191":"forward slash","192":"grave accent","219":"open bracket","220":"back slash","221":"close braket","222":"single quote"};
	return codelist[keyCode]?codelist[keyCode]:"key("+keyCode+")";
}

// Objects
function splitToFloat(str,del){
	var arr=new Array;
	if (str){
		var c=0;
		arr=str.split(del);
		for(var v=0;v<arr.length;v++){
			c=parseFloat("0"+arr[v],10);
			arr[v]=(isNaN(c)?0:c);
		}
	}
	return arr;
}
function splitToInt(str,del){
	var arr=new Array;
	if (str){
		var c;
		arr=str.split(del);
		for(var v=0;v<arr.length;v++){
			c=parseInt(arr[v],10);
			arr[v]=(isNaN(c)?0:c);
		}
	}
	return arr;
}

// Game
function igm(name,append,betreff){
	var link=createElement("span",{"mouseOverText":texte["nachrichtSchreiben"],"to":name,"subject":(betreff?betreff:""),"class":"link playerMsg"});
	createElement("div",{},link);
	link.addEventListener("click",function(){
		var pagedata=new Object();
		pagedata["to"]=this.getAttribute("to");
		pagedata["subject"]=this.getAttribute("subject");
		window.setTimeout(function(){
			GM_setValue(LNG+"_"+SERVER+"_pagedataNachrichtenNew",implode(pagedata));
			if($top("multiframe")){
				hideToolTip(this);
				$top("multiframe").src="http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/new.php";
				$top("multiframe").style.display="block";
			}else{
				window.open("http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/new.php");
			}
		},0);
	},false);
	link.addEventListener("mouseover",function(event){
		showToolTip(event,this.getAttribute("mouseOverText"),this);
	},false);
	if (append) append.appendChild(link);
	return link;
}
function vertrag(name,append){
	var link=createElement("span",{"to":name,"class":"link playerContract"});
	createElement("div",{},link);
	link.addEventListener("click",function(){
		var pagedata=new Object();
		pagedata["to"]=this.getAttribute("to");
		window.setTimeout(function(){
			GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeNew",implode(pagedata));
			if($top("multiframe")){
				hideToolTip(this);
				$top("multiframe").src="../vertraege/new.php";
				$top("multiframe").style.display="block";
			}else{
				window.open("../vertraege/new.php");
			}
		},0);
	},false);
	link.addEventListener("mouseover",function(event){
		showToolTip(event,texte["vertragSchicken"]);
	},false);
	if (append) append.appendChild(link);
	return link;
}
function stats(name,append){
	var link=createElement("span", {"mouseOverText":texte["statistik"],"class":"link playerStats","href":"../stadt/stats.php?search=1&searchterm="+name});
	createElement("div",{},link);
	if($top("shop")){
		link.addEventListener("click",function(){
			hideToolTip(this);
			showShopframePage(this.getAttribute("href"));
		},false);
	}else{
		link.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
	}
	link.addEventListener("mouseover",function(event){
		showToolTip(event,this.getAttribute("mouseOverText"),this);
	},false);
	if (append) append.appendChild(link);
	return link;
}

function loadProductData(){
	if(DEVMODE_FUNCTION){ GM_log("Begin loadProductData"); }
	gut=explode(GM_getValue(LNG+"_"+SERVER+"_gut"),"loadProductData/gut",[]);
	gutBeob=explode(GM_getValue(LNG+"_"+SERVER+"_gutBeob"),"loadProductData/gutBeob",[]);
	preisBeob=explode(GM_getValue(LNG+"_"+SERVER+"_preisBeob"),"loadProductData/preisBeob",[]); //isNotSent,time,min,max,amount	
	prodName=explode(GM_getValue(LNG+"_"+SERVER+"_prodName"),"loadProductData/prodName",[]);
	prodId=explode(GM_getValue(LNG+"_"+SERVER+"_prodId"),"loadProductData/prodId",[]);
	prodPlantSize=explode(GM_getValue(LNG+"_"+SERVER+"_prodPlantSize"),"loadProductData/err/prodPlantSize",[]);
	prodStock=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock"),"loadProductData/prodStock",[]);
	prodStockMax=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodStockMax"),"loadProductData/prodStockMax",[]);
	prodYield=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodYield"),"loadProductData/prodYield",[]);
	prodRequire=explode(GM_getValue(LNG+"_"+SERVER+"_prodRequire"),"loadProductData/prodRequire",[]);
	prodTyp=explode(GM_getValue(LNG+"_"+SERVER+"_prodTyp"),"loadProductData/prodTyp",[]);//c:coins, v:plant, e:product, u:garbage, z:deco, f:forestry, r:recipe
	prodGrowTime=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodGrowTime"),"loadProductData/prodGrowTime",[]);
	prodPoints=explode(GM_getValue(LNG+"_"+SERVER+"_prodPoints"),"loadProductData/prodPoints",[]);
	prodNameSort=explode(GM_getValue(LNG+"_"+SERVER+"_prodNameSort"),"loadProductData/err/prodNameSort",[]);
	prodBlock=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodBlock"),"loadProductData/err/prodBlock",[]);
	prodMinRackInit=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRackInit"),"loadProductData/err/prodMinRackInit",[]);
	prodMinRack=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRack"),"loadProductData/err/prodMinRack",[]);
	if(DEVMODE_FUNCTION){ GM_log("End loadProductData"); }
}
function updateProductDataFarm(){
	if(DEVMODE_FUNCTION){ GM_log("Begin updateProductDataFarm"); }
	try{
		USERLEVEL=parseInt(unsafeWindow.currentuserlevel,10); // only main.php can pass this
		if(!(prodName instanceof Array)){ prodName=[]; }
		if(!(prodId instanceof Array)){ prodId=[]; }
		if(!(prodPlantSize instanceof Array)){ prodPlantSize=[]; }
		if(!(prodStock instanceof Array)){ prodStock=[]; }
		if(!(prodStockMax instanceof Array)){ prodStockMax=[]; }
		if(!(prodYield instanceof Array)){ prodYield=[]; }
		if(!(prodRequire instanceof Array)){ prodRequire=[]; }
		if(!(prodTyp instanceof Array)){ prodTyp=[]; }
		if(!(prodGrowTime instanceof Array)){ prodGrowTime=[]; }
		if(!(prodPoints instanceof Array)){ prodPoints=[]; }
		if(!(prodNameSort instanceof Array)){ prodNameSort=[]; }
		if(!(prodBlock instanceof Array)){ prodBlock=[]; }
 
		if(!prodName[0]||!(prodName[0] instanceof Array)){ prodName[0]=[]; } 
		if(!prodId[0]||(typeof prodId[0]!="object")||(prodId[0] instanceof Array)){ prodId[0]={}; } 
		if(!prodPlantSize[0]||!(prodPlantSize[0] instanceof Array)){ prodPlantSize[0]=[]; } 
		if(!prodStock[0]||!(prodStock[0] instanceof Array)){ prodStock[0]=[]; } 
		if(!prodStockMax[0]||!(prodStockMax[0] instanceof Array)){ prodStockMax[0]=[]; } 
		if(!prodYield[0]||!(prodYield[0] instanceof Array)){ prodYield[0]=[]; } 
		if(!prodRequire[0]||!(prodRequire[0] instanceof Array)){ prodRequire[0]=[]; } 
		if(!prodTyp[0]||!(prodTyp[0] instanceof Array)){ prodTyp[0]=[]; } 
		if(!prodGrowTime[0]||!(prodGrowTime[0] instanceof Array)){ prodGrowTime[0]=[]; } 
		if(!prodPoints[0]||!(prodPoints[0] instanceof Array)){ prodPoints[0]=[]; } 
		// if(!prodBlock[0]||!(prodBlock[0] instanceof Array)){ prodBlock[0]=[]; } 
		
		//c:only by club, u:garbage, l:level too low, t:not tradable, f:forestry, q:lodge quest too low, r:recipe, p:powerup, b:block recipe/powerup
		prodBlock[0]=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","ct","","ct","","ct","ct","","ct","","","","","","","","","","ct","ct","ct","ct","ct","ct","ct","","","","","","","ct","","ct","","","ct","","","ct","ct","ct","","","","","","","","t","","","","","","","t","","t","t","","","","","","","","","","","","","","","","","","","","","","t","","","","","","","","","","","","","","","","","","","","","","","","","","","","","t"]; // task_new_plant task_new_product
			 /*
			var new_prodBlock=prodBlock[0].clone();
			new_prodBlock[158]="t";
			GM_log(implode(new_prodBlock));
			*/
		prodName[0][0]=texte["coins"];
		prodTyp[0][0]="c";
		prodId[0][prodName[0][0]]=0;
		try{ prodStock[0][0]=parseInt($("coins").innerHTML,10); }catch(err){}
		prodPlantSize[0][0]=1;
		prodGrowTime[0][0]=0;
		prodPoints[0][0]=0;
		//Bugfixes of game data
		if(unsafeWindow.produkt_ernte[145]){ unsafeWindow.produkt_ernte[145]=6; }
		if(unsafeWindow.produkt_ernte[146]){ unsafeWindow.produkt_ernte[146]=4; }
		if(unsafeWindow.produkt_ernte[147]){ unsafeWindow.produkt_ernte[147]=6; }
		if(unsafeWindow.produkt_ernte[148]){ unsafeWindow.produkt_ernte[148]=7; }
		if(unsafeWindow.produkt_ernte[149]){ unsafeWindow.produkt_ernte[149]=4; }
		if(unsafeWindow.produkt_ernte[150]){ unsafeWindow.produkt_ernte[150]=6; }

		var help={"v":[],"e":[],"o":[],"fw1":[],"fw2":[],"fw3":[],"fw4":[],"z":[]};
		// for(var v=1;v<unsafeWindow.produkt_name.length;v++){
		for(var v in unsafeWindow.produkt_name){
			if(!unsafeWindow.produkt_name.hasOwnProperty(v)){continue;}	
			if(isNaN(gut[v])){ gut[v]=0; }
			prodName[0][v]=unsafeWindow.produkt_name[v];
			prodId[0][prodName[0][v]]=v;
			prodPlantSize[0][v]=unsafeWindow.produkt_x[v]*unsafeWindow.produkt_y[v];
			var c=(unsafeWindow.rackElement[v]&&unsafeWindow.rackElement[v].number)?unsafeWindow.rackElement[v].number:0;
			prodStock[0][v]=(c?parseInt(c,10):0);
			prodYield[0][v]=(unsafeWindow.produkt_ernte[v]?unsafeWindow.produkt_ernte[v]:0);
			prodTyp[0][v]=unsafeWindow.produkt_category[v];
			prodRequire[0][v]=PRODUCT_REQUIRE[0][v];
			prodGrowTime[0][v]=PRODUCT_GROWTIME[0][v]; //TODO take from game?
			prodPoints[0][v]=PRODUCT_POINTS[0][v]; //TODO take from game?
			if(prodTyp[0][v]=="u"){
				prodBlock[0][v]="ut";
			}else{
				if(typeof prodBlock[0][v]=="undefined"){
					prodBlock[0][v]="t";
				}
				// Hack: split picnic products in different categories
				if(prodTyp[0][v]=="fw"){ // task_new_picnic_product
					switch(parseInt(v,10)){
					case 130:case 131:case 132:case 133:case 134:case 135:case 145:case 146:case 147:
						prodTyp[0][v]+="1"; break;
					case 136:case 137:case 138:case 139:case 140:case 141:case 142:case 143:case 148:case 149:case 150:
						prodTyp[0][v]+="2"; break;
					default: prodTyp[0][v]+="3";
					}
				}
				if(help[prodTyp[0][v]]){
					help[prodTyp[0][v]].push(v);
				}
				if(USERLEVEL<unsafeWindow.produkt_level[v]){
					prodBlock[0][v]+="l"+unsafeWindow.produkt_level[v];
				}
				if(PRODUCT_QUEST[0][v]&&(questData[PRODUCT_QUEST[0][v][0]][PRODUCT_QUEST[0][v][1]]["nr"]<=PRODUCT_QUEST[0][v][2])){
					prodBlock[0][v]+="q";
				}
			}
		}
		prodNameSort[0]=[0].concat(help["v"],help["e"],help["o"],help["fw1"],help["fw2"],help["fw3"],help["fw4"],help["z"]);
		// quest boni
		for(var v=1;v<questData["farm"]["1"]["nr"];v++){
			if(QUESTS["farm"]["1"][v]&&QUESTS["farm"]["1"][v][3]){
				for(var w=0;w<QUESTS["farm"]["1"][v][3].length;w++){
					if(QUESTS["farm"]["1"][v][3][w][0]==4){
						prodGrowTime[QUESTS["farm"]["1"][v][3][w][1]][QUESTS["farm"]["1"][v][3][w][2]]-=QUESTS["farm"]["1"][v][3][w][3];
					}
				}
			}
		}
	}catch(err){
		GM_log("ERROR updateProductDataFarm\n"+err);
		loadProductData();
	}
	publishProductData();

	if(DEVMODE_FUNCTION){ GM_log("End updateProductDataFarm"); }
}
function updateProductDataForestry(){
	if(DEVMODE_FUNCTION){ GM_log("Begin updateProductDataForestry"); }
	try{
		if(!prodName[1]||(typeof prodName[1]!="object")||(prodName[1] instanceof Array)){ prodName[1]={}; } 
		if(!prodId[1]||(typeof prodId[1]!="object")||(prodId[1] instanceof Array)){ prodId[1]={}; } 
		if(!prodPlantSize[1]||(typeof prodPlantSize[1]!="object")||(prodPlantSize[1] instanceof Array)){ prodPlantSize[1]={}; } 
		if(!prodStock[1]||(typeof prodStock[1]!="object")||(prodStock[1] instanceof Array)){ prodStock[1]={}; } 
		if(!prodStockMax[1]||(typeof prodStockMax[1]!="object")||(prodStockMax[1] instanceof Array)){ prodStockMax[1]={}; } 
		if(!prodYield[1]||(typeof prodYield[1]!="object")||(prodYield[1] instanceof Array)){ prodYield[1]={}; } 
		if(!prodRequire[1]||(typeof prodRequire[1]!="object")||(prodRequire[1] instanceof Array)){ prodRequire[1]={}; } 
		if(!prodTyp[1]||(typeof prodTyp[1]!="object")||(prodTyp[1] instanceof Array)){ prodTyp[1]={}; } 
		if(!prodGrowTime[1]||(typeof prodGrowTime[1]!="object")||(prodGrowTime[1] instanceof Array)){ prodGrowTime[1]={}; } 
		if(!prodPoints[1]||(typeof prodPoints[1]!="object")||(prodPoints[1] instanceof Array)){ prodPoints[1]={}; } 
		if(!prodNameSort[1]||!(prodNameSort[1] instanceof Array)){ prodNameSort[1]=[]; } 
		if(!prodBlock[1]||(typeof prodBlock[1]!="object")||(prodBlock[1] instanceof Array)){ prodBlock[1]={}; } 
 
		var help={"f1":[],"f2":[],"f3":[],"f4":[],"f5":[]};
 		for(var v in unsafeWindow.produkt_name_forestry){
			if(!unsafeWindow.produkt_name_forestry.hasOwnProperty(v)){continue;}	
			prodName[1][v]=unsafeWindow.produkt_name_forestry[v];
			prodId[1][prodName[1][v]]=v;
			prodPlantSize[1][v]=1;
			// prodStock
			// prodStockMax
			prodYield[1][v]=PRODUCT_YIELD[1][v];
			if((v==105)||(v==108)||(v==116)||(v==117)||(v==119)||(v==120)){ prodTyp[1][v]="f5"; } // farmhouse-items from carpentry
			else if(v<20){ prodTyp[1][v]="f1"; } // saplings
			else if(v<40){ prodTyp[1][v]="f2"; } // logs
			else if(v<100){ prodTyp[1][v]="f3"; } // sawmill-products
			else if(v<500){ prodTyp[1][v]="f4"; } // carpentry-products
			else { prodTyp[1][v]="u"; } // useless "products"
			prodRequire[1][v]=PRODUCT_REQUIRE[1][v];
			prodGrowTime[1][v]=PRODUCT_GROWTIME[1][v];
			prodPoints[1][v]=PRODUCT_POINTS[1][v];
			
			if(prodTyp[1][v]=="u"){
				prodBlock[1][v]="qtu";
			}else{
				prodBlock[1][v]="t";
				if((unsafeWindow.forestry_unlock==undefined)||(PRODUCT_QUEST[1][v]&&(questData[PRODUCT_QUEST[1][v][0]][PRODUCT_QUEST[1][v][1]]["nr"]<=PRODUCT_QUEST[1][v][2]))){
					prodBlock[1][v]+="q";
				}
				if(v==113||v==114){ prodBlock[1][v]+="s"; } 
				if(help[prodTyp[1][v]]){
					help[prodTyp[1][v]].push(v);
				}
			}
		}
		prodNameSort[1]=help["f1"].concat(help["f2"],help["f3"],help["f4"],help["f5"]);
		prodName[1].sortObj();
		publishProductData();
	}catch(err){ GM_log("ERROR updateProductDataForestry\n"+err); }
	if(DEVMODE_FUNCTION){ GM_log("End updateProductDataForestry"); }
}
function updateProductDataWindmill(){
	if(DEVMODE_FUNCTION){ GM_log("Begin updateProductDataWindmill"); }
	try{
		if(!prodName[2]||!(prodName[2] instanceof Array)){ prodName[2]=[]; } 
		if(!prodId[2]||(typeof prodId[2]!="object")||(prodId[2] instanceof Array)){ prodId[2]={}; } 
		if(!prodPlantSize[2]||!(prodPlantSize[2] instanceof Array)){ prodPlantSize[2]=[]; } 
		if(!prodStock[2]||!(prodStock[2] instanceof Array)){ prodStock[2]=[]; } 
		if(!prodStockMax[2]||!(prodStockMax[2] instanceof Array)){ prodStockMax[2]=[]; } 
		// if(!prodYield[2]||!(prodYield[2] instanceof Array)){ prodYield[2]=[]; } 
		// if(!prodRequire[2]||!(prodRequire[2] instanceof Array)){ prodRequire[2]=[]; } 
		if(!prodTyp[2]||!(prodTyp[2] instanceof Array)){ prodTyp[2]=[]; } 
		// if(!prodGrowTime[2]||!(prodGrowTime[2] instanceof Array)){ prodGrowTime[2]=[]; } 
		// if(!prodPoints[2]||!(prodPoints[2] instanceof Array)){ prodPoints[2]=[]; } 
		if(!prodBlock[2]||!(prodBlock[2] instanceof Array)){ prodBlock[2]=[]; } 

		prodYield[2]=[];
		prodRequire[2]=[];
		prodGrowTime[2]=[];
		prodPoints[2]=[];
		// GM_log("formulas:\n"+print_r(unsafeWindow.formulas,"",true,"\n"));
		for(var v in unsafeWindow.formulas[0]){
			if(!unsafeWindow.formulas[0].hasOwnProperty(v)){continue;}
			pId=unsafeWindow.formulas[0][v][0];
			// GM_log("updateProductDataWindmill loop formulas v="+v+" pId="+pId);
			prodName[2][pId]="*"+unsafeWindow.formulas[0][v][2];
			prodId[2]["*"+unsafeWindow.formulas[0][v][2]]=pId;
			prodId[2][unsafeWindow.formulas[0][v][2]]=pId;
			prodPlantSize[2][pId]=1;
			if(!prodStock[2][pId]||(typeof prodStock[2][pId]!="number")){ prodStock[2][pId]=0; }
			//1=earn prods,2=earn extra amount,3=earn extra score
			if(unsafeWindow.formulas[0][v][5][0]!=0){ prodTyp[2][pId]="r0"; }
			else if(unsafeWindow.formulas[0][v][5][1]!=0){ prodTyp[2][pId]="r1"; }
			else if(unsafeWindow.formulas[0][v][5][2]!=0){ prodTyp[2][pId]="r2" }
			prodBlock[2][pId]="rt"+(USERLEVEL<unsafeWindow.formulas[0][v][1]?"l":"")+(unsafeWindow.formulas[0][v]["endremain"]<0?"s":"");
		}
		prodTyp[2].sortObj();
		var help={"r0":[],"r1":[],"r2":[]};
		for(var v in prodTyp[2]){
			if(!prodTyp[2].hasOwnProperty(v)){continue;}
			if(help[prodTyp[2][v]]){ help[prodTyp[2][v]].push(v); }
		}
		prodNameSort[2]=help["r0"].concat(help["r1"],help["r2"]);
		publishProductData();
	}catch(err){ GM_log("ERROR updateProductDataWindmill\n"+err); }
	if(DEVMODE_FUNCTION){ GM_log("End updateProductDataWindmill"); }
}
function updateProductDataPowerup(){
	// return false;
	if(DEVMODE_FUNCTION){ GM_log("Begin updateProductDataPowerup"); }
	try{
		if(!prodName[3]||!(prodName[3] instanceof Array)){ prodName[3]=[]; } 
		if(!prodId[3]||(typeof prodId[3]!="object")||(prodId[3] instanceof Array)){ prodId[3]={}; } 
		if(!prodPlantSize[3]||!(prodPlantSize[3] instanceof Array)){ prodPlantSize[3]=[]; } 
		if(!prodStock[3]||!(prodStock[3] instanceof Array)){ prodStock[3]=[]; } 
		if(!prodStockMax[3]||!(prodStockMax[3] instanceof Array)){ prodStockMax[3]=[]; } 
		if(!prodYield[3]||!(prodYield[3] instanceof Array)){ prodYield[3]=[]; } 
		if(!prodRequire[3]||!(prodRequire[3] instanceof Array)){ prodRequire[3]=[]; } 
		if(!prodTyp[3]||!(prodTyp[3] instanceof Array)){ prodTyp[3]=[]; } 
		if(!prodGrowTime[3]||!(prodGrowTime[3] instanceof Array)){ prodGrowTime[3]=[]; } 
		if(!prodPoints[3]||!(prodPoints[3] instanceof Array)){ prodPoints[3]=[]; } 
		if(!prodBlock[3]||!(prodBlock[3] instanceof Array)){ prodBlock[3]=[]; } 
	
		var pId;
		for(var v in unsafeWindow.formulas[0]){
			if(!unsafeWindow.formulas[0].hasOwnProperty(v)){continue;}
			pId=unsafeWindow.formulas[0][v][0];
			// GM_log("updateProductDataPowerup loop formulas v="+v+" pId="+pId);
			prodName[3][pId]=unsafeWindow.formulas[0][v][2];
			prodPlantSize[2][pId]=1;
			prodStock[3][pId]=0;
			prodYield[3][pId]=1;
			prodRequire[3][pId]=[[2,pId,1]];
			for(var i=0;i<unsafeWindow.formulas[0][v][3].length;i++){
				prodRequire[3][pId].push([0,unsafeWindow.formulas[0][v][3][i][0],unsafeWindow.formulas[0][v][3][i][1]]);
			}
			//1=earn prods,2=earn extra amount,3=earn extra score
			if(unsafeWindow.formulas[0][v][5][0]!=0){ prodTyp[3][pId]="p0"; }
			else if(unsafeWindow.formulas[0][v][5][1]!=0){ prodTyp[3][pId]="p1"; }
			else if(unsafeWindow.formulas[0][v][5][2]!=0){ prodTyp[3][pId]="p2"; }
			prodGrowTime[3][pId]=Math.round(unsafeWindow.formulas[0][v][4]/60);
			prodPoints[3][pId]=unsafeWindow.formulas[0][v][8];
			prodBlock[3][pId]="pt"+(USERLEVEL<unsafeWindow.formulas[0][v][1]?"l":"");
		}
		if (unsafeWindow.powerupcontent == null) unsafeWindow.powerupcontent = 0;
		for(var v in unsafeWindow.powerupcontent){
			if(!unsafeWindow.powerupcontent.hasOwnProperty(v)){continue;}
			pId=unsafeWindow.powerupcontent[v][0];
			// GM_log("updateProductDataPowerup loop powerupcontent v="+v+" pId="+pId);
			prodName[3][pId]=unsafeWindow.powerupcontent[v][2];
			prodStock[3][pId]=unsafeWindow.powerupcontent[v]["rack"];
			if(unsafeWindow.powerupcontent[0][v]["endremain"]<0){ prodBlock[3][pId]+="s"; }
		}
		for(var v=0;v<prodName[3].length;v++){
			prodId[3][prodName[3][v]]=v;
		}
		prodTyp[3].sortObj();
		var help={"p0":[],"p1":[],"p2":[]};
		for(var v in prodTyp[3]){
			if(!prodTyp[3].hasOwnProperty(v)){continue;}
			if(help[prodTyp[3][v]]){ help[prodTyp[3][v]].push(v); }
		}
		prodNameSort[3]=help["p0"].concat(help["p1"],help["p2"]);
		publishProductData();
	}catch(err){ GM_log("ERROR updateProductDataPowerup\n"+err); }
	if(DEVMODE_FUNCTION){ GM_log("End updateProductDataPowerup"); }
}
function publishProductData(){
	if(DEVMODE_FUNCTION){ GM_log("Begin publishProductData"); }
	unsafeData.prodName		=prodName.clone();
	unsafeData.prodNameSort	=prodNameSort.clone();
	unsafeData.prodTyp		=prodTyp.clone();
	unsafeData.prodBlock	=prodBlock.clone();
	unsafeData.prodYield	=prodYield.clone();
	unsafeData.prodRequire	=prodRequire.clone();
	unsafeData.prodStock	=prodStock.clone();
	unsafeData.prodStockMax	=prodStockMax.clone();
	unsafeData.prodGrowTime	=prodGrowTime.clone();
	top.unsafeData.prodPlantSize	=prodPlantSize.clone();
	top.unsafeData.prodPoints		=prodPoints.clone();
	top.unsafeData.prodId			=prodId.clone();
	top.unsafeData.gut				=gut.clone();
	window.setTimeout(function(){
		top.unsafeData.preisBeob =explode(GM_getValue(LNG+"_"+SERVER+"_preisBeob","[]"),"publishProductData/preisBeob",[]).clone();
	},0);
	if(DEVMODE_FUNCTION){ GM_log("End publishProductData"); }
}
function saveProductData(){
	if(DEVMODE_FUNCTION){ GM_log("Begin saveProductData"); }
	GM_setValue(LNG+"_"+SERVER+"_prodName",implode(prodName,"saveProductData\prodName"));
	GM_setValue(LNG+"_"+SERVER+"_prodNameSort",implode(prodNameSort,"saveProductData\prodNameSort"));
	GM_setValue(LNG+"_"+SERVER+"_prodId",implode(prodId,"saveProductData\prodId"));
	GM_setValue(LNG+"_"+SERVER+"_prodPoints",implode(prodPoints,"saveProductData\prodPoints"));
	GM_setValue(LNG+"_"+SERVER+"_prodPlantSize",implode(prodPlantSize,"saveProductData\prodPlantSize"));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock,"saveProductData\prodStock"));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodStockMax",implode(prodStockMax,"saveProductData\prodStockMax"));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodYield",implode(prodYield,"saveProductData\prodYield"));
	GM_setValue(LNG+"_"+SERVER+"_prodRequire",implode(prodRequire,"saveProductData\prodRequire"));
	GM_setValue(LNG+"_"+SERVER+"_prodTyp",implode(prodTyp,"saveProductData\prodTyp"));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodGrowTime",implode(prodGrowTime,"saveProductData\prodGrowTime"));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodBlock",implode(prodBlock,"saveProductData\prodBlock"));
	GM_setValue(LNG+"_"+SERVER+"_gut",implode(gut,"saveProductData\gut"));
	GM_setValue(LNG+"_"+SERVER+"_gutBeob",implode(gutBeob,"saveProductData\gutBeob"));
	if(DEVMODE_FUNCTION){ GM_log("End saveProductData"); }
}

function checkRequest(request){
try{
	if((request.readyState==4)&&(request.status==200)){
		var response=request.responseText;
		if(response!=0){
			var result=eval('('+response+')');
			if(result[0]!=0){
				return result;
			}
		}
	}
	return null;
}catch(err){GM_log("ERROR checkRequest\n"+err);return null;}	
}
function showMultiframePage(page){
try{
//GM_log("showMultiframePage:"+page);
    top.window.wrappedJSObject.gclr();
    top.window.wrappedJSObject.clr();
    var i=0,help;
    while (help=$top("kunde"+(i++))){ help.style.display="none"; }
	closeInfoPanel();
    if(help=$top("einkaufszettel")){ help.style.display="none"; }
    if(help=$top("popup_garden")){ help.style.display="block"; }
    if(help=$top("multiframe")){ help.style.display="block"; }
    if(help=$top("multiframe")){ help.src=page; }
}catch(err){GM_log("ERROR showMultiframePage page="+page+"\n"+err);}	
}
function showShopframePage(page){
	var cell=$top("shop");
	if(cell){
		if (top.window.wrappedJSObject.city!=1){
			top.document.addEventListener("gameCity1",function(){
				GM_log("showShopframePage:in stad 1");
				top.document.removeEventListener("gameCity1",arguments.callee,false);
				showShopframePage(page);
			},false);
			click($top("speedlink_city1"));
		}else if (cell.style.display!="block"){
			cell.style.display="block";
			cell.style.visibility="visible";
			cell=$top("transp3");
			cell.style.display="block";
			cell.style.visibility="visible";
			showShopframePage(page);
		}else{
			$top("travel2city").style.display="none";
			$top("shopframe").src=page;
		}
		//closeInfoPanel();
	}else{
		location.href=page;
	}
	cell=null;
}
function showMessage(from,page,msg){
//GM_log("showMessage:"+from+":"+page+":"+msg);
	//click($top("menueimg1"));
	showMultiframePage("http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/read.php?from="+from+"&page="+page+"&msg="+msg+"&mass=0");
}
function showSGH(){
	top.document.addEventListener("gameCity1",function(){
		click($top("cityzone_1_2"));
		top.document.removeEventListener("gameCity1",arguments.callee,false);
	},false);
	click($top("speedlink_city1"));
}
function showLottery(){
	var div=$top("speedlink_city2");
	if(div&&($top("lotterycontainer"))){
		top.document.addEventListener("gameCity2",function(){
			click($top("cityzone_2_8"));
			top.document.removeEventListener("gameCity2",arguments.callee,false);
		},false);
		click(div);
	}
	div=null;
}

function showGoToMarketToolTip(event,prod,add1,add2){
	var str='<table class="white">';
	str += '<tr><th colspan="2" style="border-bottom:1px solid white">'+texte["goToMarketOfX"].replace(/%1%/,prodName[0][prod])+'</th></tr>';
	if(add1){
		str += add1;
		str += '<tr><td colspan="2" style="border-bottom:1px solid white"></td></tr>';
	}
	str += '<tr><td>'+texte["marktpreis"]+'</td><td style="text-align:right;">'+(gut[prod]>=100?moneyFormatInt(gut[prod]):moneyFormat(gut[prod]))+'</td></tr>';
	str += '<tr><td>'+texte["bestand"]+'</td><td style="text-align:right;">'+numberFormat(prodStock[0][prod])+'</td></tr>';
	str += '<tr><td>'+texte["wert"]+'</td><td style="text-align:right;">'+moneyFormatInt(gut[prod]*prodStock[0][prod])+'</td></tr>';
	if(add2){
		str += '<tr><td colspan="2" style="border-bottom:1px solid white"></td></tr>';
		str += add2;
	}
	str += '</table>';
	showToolTip(event,str);
	str=null;
}
function showStatisticFullscreen(pid){
	var valStatistikNpc=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikNpc",true);
	var valStatistikTime=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikTime",120);
	var newdiv=createElement("div",{"style":"position:absolute;top:0;left:0;height:"+window.innerHeight+"px;width:"+window.innerWidth+"px;background-color:white;color:black;z-index:995;"},ALL,texte["loading"]+"...");
	var url="http://www."+STAT_VIEW[LNG]+"/chart.php?w="+window.innerWidth+"&h="+window.innerHeight+"&t=h"+valStatistikTime+"&shownpc="+(valStatistikNpc?1:0)+"&clip=1&server1="+SERVER+"&product1="+pid+"&color1=green";
	var newobject=createElement("object",{"data":url,"type":"type=image/svg+xml","style":"position:absolute;top:0;left:0;","width":window.innerWidth+"px","height":window.innerHeight+"px"},newdiv);
	createElement("param",{"name":"src","value":url},newobject);
	var newimg=createElement("img",{"src":GFX+"close.jpg","class":"link","style":"position:absolute;top:30px;right:10px;z-index:2;"},newdiv);
	newimg.addEventListener("click",function(){removeElement(this.parentNode);},false);
	newimg=createElement("div",{"style":"position:absolute;top:0px;left:40%;padding:5px;z-index:2;border-width:0px 2px 2px 2px;border-style:solid;border-radius:0px 0px 10px 10px;background-color:white;"},newdiv);
	produktPic(0,pid,newimg);
	createElement("span",{"style":"font-weight:bold;"},newimg,prodName[0][pid]);
	newdiv=null;newobject=null;newimg=null;
}

function calcProductionTime(buildingType,productType,productId,bonus,feedTime,feedAmount){
// bonus like 0.85
try{
	var time;
	switch(buildingType){
	case 1:
	case "forest":
		time=calcGrowDuration(prodGrowTime[productType][productId]*60,bonus);
		break;
	case 2:
		var totalTime=prodGrowTime[productType][productId]*60*bonus;
		time=totalTime;
		if(!feedAmount){
			feedAmount=Math.ceil(totalTime/feedTime);
		}
		totalTime*=0.5;
		if(unsafeWindow.premium==0 && USERLEVEL>9){ totalTime+=5; } // hack: non-premiums cant feed completely
		for(var i=1;i<=feedAmount;i++){
			if(time-feedTime>=totalTime){
				time-=feedTime;
			} else { break; }
		}
		totalTime=null;
		time=[time,i-1];
		break;
	case 3:
		time=prodGrowTime[productType][productId]*60*bonus;
		break;
	case "windmill":
		time=parseInt(unsafeWindow.formulas[0][productId][4],10);
		//time*=bonus;
		break;
	case "forest":
		time=calcGrowDuration(prodGrowTime[productType][productId]*60,bonus);
		break;
	case "sawmill":
	case "carpentry":
		time=prodGrowTime[productType][productId]*60*bonus;
		break;
	}
	return time;
}catch(err){GM_log("ERROR calcProductionTime product:"+[productType,productId]+" bonus="+bonus+" \n"+err);return 0;}
}
function calcGrowDuration(growDurationInitial,bonus){
//growDurationInitial in seconds, bonus like 0.85
	var gesamtdauer=0;
	while(growDurationInitial>0){
		growDurationInitial *= bonus;
		var help=Math.min(growDurationInitial,86400);
		growDurationInitial -= help;
		gesamtdauer += help;
	}
	return Math.round(gesamtdauer);
}
function calcGrowTimes(growDurationInitial,period,bonus){
	return period/calcGrowDuration(growDurationInitial,bonus);
}

function getQuestBestAlternative(arr){
// item=[prodType,prodId,amount]. arr=item or arr=[item,item,...]
	if(typeof arr[0]=="object"){
		var returnId,minPrice=null,currPrice;
		for(var k=0;k<arr.length;k++){
			if(arr[k][0]!=0){
				currPrice=0;
			}else if(isNaN(NPC[0][arr[k][1]])){
				currPrice=arr[k][2]*gut[arr[k][1]];
			}else{
				currPrice=arr[k][2]*Math.min(gut[arr[k][1]],NPC[0][arr[k][1]]);
			}
			if((minPrice==null)||(currPrice<minPrice)){
				minPrice=currPrice;
				returnId=k;
			}
		}
		return arr[returnId];
	} if(typeof arr=="object"){
		return arr;
	} else {
		GM_log("WARNING getQuestBestAlternative bad call arr="+implode(arr));
		return [];
	}
}
unsafeData.getQuestBestAlternative=getQuestBestAlternative;
//***********************************************************************************************************



function do_shop(){
	if(pageZusatz["s"]=="3"){
		// Decoration - Shop
		NPCSAISON=explode(GM_getValue(LNG+"_"+SERVER+"_NpcSaison"),"do_shop/NPCSAISON",INIT_NPCSAISON);
		for(var v in NPCSAISON){
			if(!NPCSAISON.hasOwnProperty(v)){ continue; }
			NPCSAISON[v]=(document.getElementsByClassName("s"+v).length>0);
		}
		unsafeData.NPCSAISON=NPCSAISON.clone();
		GM_setValue(LNG+"_"+SERVER+"_NpcSaison",implode(NPCSAISON));
	}
}

function do_stats(){
	var canddiv;
	var currStat="1";
	try{ currStat=pageZusatz["type"]; }
	catch(err){ currStat="1"; }
	if (typeof pageZusatz["search"]!="undefined"){ currStat="0"; }
	GM_addStyle("#rankingcontent{line-height:12px;}");

	if (typeof pageZusatz["guildsearch"]!="undefined"){
		unsafeWindow.initGuildsearch();
		$("guildname").value=pageZusatz["guildsearch"];
		unsafeWindow.stats_searchGuild();
	}

	switch (currStat){
	case "0": // Einzelspieler
		try {
			loadProductData();
			GM_addStyle("div.hoverBgLightblue:hover{background-color:lightblue!important;}");

			var newdiv=$("spielerinfo");
			var newdiv1;
			for(var v=0;v<newdiv.childElementCount;v++){
				newdiv1=createElement("div",{"class":"hoverBgLightblue","style":"height:15px;width:100%;"});
				newdiv.insertBefore(newdiv1,newdiv.children[v]);
				newdiv1.appendChild(newdiv.children[v+1]); // left cell
				newdiv1.appendChild(newdiv.children[v+1]); // right cell
				removeElement(newdiv.children[v+1]); // br node
			}

			canddiv=$("spielerinfo").getElementsByClassName("cright3");
			var thisUser=/(.*?)&nbsp;/.exec(canddiv[0].firstElementChild.innerHTML+"&nbsp;")[1];
			canddiv[0].insertBefore(vertrag(thisUser),canddiv[0].firstElementChild);
			canddiv[0].insertBefore(stats(thisUser),canddiv[0].firstElementChild);
			canddiv[0].insertBefore(igm(thisUser),canddiv[0].firstElementChild);

			var nextQuest=parseInt(canddiv[5].innerHTML,10)+1;
			if(QUESTS["farm"]["1"][nextQuest]){
				canddiv[5].parentNode.setAttribute("nextQuest",nextQuest);
				canddiv[5].parentNode.addEventListener("mouseover",function(event){
					var nextQuest=this.getAttribute("nextQuest");
					var str="<div style='border-bottom:1px solid white'>"+texte["quest"]+"&nbsp;"+nextQuest+"</div>";
					for(var i=0;i<QUESTS["farm"]["1"][nextQuest][0].length;i++){
						if(typeof QUESTS["farm"]["1"][nextQuest][0][i][0]=="object"){
							for(var j=0;j<QUESTS["farm"]["1"][nextQuest][0][i].length;j++){					
								str += "<div>*"+numberFormat(QUESTS["farm"]["1"][nextQuest][0][i][j][2])+"&nbsp;"+prodName[QUESTS["farm"]["1"][nextQuest][0][i][j][0]][QUESTS["farm"]["1"][nextQuest][0][i][j][1]]+"</div>";
							}
						}else{
							str += "<div>"+numberFormat(QUESTS["farm"]["1"][nextQuest][0][i][2])+"&nbsp;"+prodName[QUESTS["farm"]["1"][nextQuest][0][i][0]][QUESTS["farm"]["1"][nextQuest][0][i][1]]+"</div>";
						}
					}
					showToolTip(event,str);
				},false);
			}
			nextQuest=null;
		} catch(err){}
		break;
	// Spielerlisten
	case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "10": case "11":
		if($("rankinghead")){
			canddiv=createElement("input",{"class":"text","maxlength":"5","style":"margin-left:10px;width:40px;"},$("rankinghead"));
			canddiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["geheZuPlatz"]); },false);
			canddiv.addEventListener("change",function(){
				var ranksPerPage=15;
				var targetPage=parseInt(this.value,10);
				if(targetPage>0){
					targetPage=Math.ceil(targetPage/ranksPerPage);
					location.href="stats.php?page="+targetPage+"&type="+currStat;
				}else{
					this.value="";
				}
			},false);
		}

		canddiv=$("rankingcontent").getElementsByClassName("stats_name");
		for(var v=0;v<canddiv.length;v++){
			thisUser=/(.*?)&nbsp;/.exec(canddiv[v].firstElementChild.innerHTML+"&nbsp;")[1];
			thisGuild=/&nbsp;\[(.*?)\]&nbsp;/.exec(canddiv[v].firstElementChild.innerHTML+"&nbsp;");
			var help=canddiv[v].firstElementChild.innerHTML.replace(thisUser,"<a href='stats.php?search=1&searchterm="+thisUser+"'>"+thisUser+"</a>");
			if(thisGuild) help=help.replace(thisGuild[0],"&nbsp;[<a href='stats.php?guildsearch="+thisGuild[1]+"'>"+thisGuild[1]+"</a>]&nbsp;");
			canddiv[v].firstElementChild.innerHTML=help;
			canddiv[v].insertBefore(igm(thisUser),canddiv[v].firstElementChild);
		}
		break;
	}
	canddiv=null;
}

function do_wettbewerb(){ // in .de not used anymore
	var candtd=document.getElementsByTagName("table")[1].getElementsByTagName("td");
	for(var v=6;v<candtd.length;v=v+3){
		var thisUser=/(.*?)&nbsp/.exec(candtd[v].firstElementChild.innerHTML+"&nbsp")[1];
		igm(thisUser,candtd[v]);
	}
	candtd=null;
}

//***********************************************************************************************************

function closeInfoPanel(){
	try{
		$top("infoPanel").setAttribute("mode","");
		$top("infoPanel").style.display="none";
		$top("infoPanelInner").innerHTML="";
		var multiframe=$top("multiframe");
		multiframe.style.zIndex="101";
		if(multiframe.style.display!="block"){ $("transp100").style.display="none"; }
		multiframe=null;
	} catch(err){ GM_log("ERROR closeInfoPanel\n"+err); }
}

function do_main(){
try{
	function buildStockTable(page,prodType,filterCategory,appendTo,fontColor,bgHover){
	try{
		// GM_log("buildStockTable page="+page+" prodType="+prodType+" filterCategory="+filterCategory);
		// loadProductData();
		// updateProductDataFarm(); //TODO fails if called from market
		var bChanged=false;
		var valNimmBeob=GM_getValue(LNG+"_"+SERVER+"_valNimmBeob",false);
		var mode=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeStockTable"),"buildStockTable/mode",{});
		if(!mode||(typeof mode!="object")||(mode instanceof Array)){ mode={}; }
		mode["showAll"]=!!mode["showAll"];
		if(!mode["prodType"]){ mode["prodType"]=0; }
		if(!mode["filterCategories"]){ mode["filterCategories"]=["ve","f1f2f3f4f5","",""]; }
		if(prodType==null){ prodType=mode["prodType"]; }
		else{ mode["prodType"]=prodType; }
		if(filterCategory==null){ filterCategory=mode["filterCategories"][prodType]; }
		else{ mode["filterCategories"][prodType]=filterCategory; }
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeStockTable",implode(mode));
		// if(showAll){
		// 	var help={"v":[],"e":[],"o":[],"z":[]};
		// 	for(var v=1;v<prodName[0].length;v++){ 
		// 		if((!prodBlock[0][v].match(/t/))&&help[prodTyp[0][v]]){
		// 			help[prodTyp[0][v]].push(v); 
		// 		}
		// 	}
		// 	prodNameSort[0]=[0].concat(help["v"],help["e"],help["o"],help["z"]);
		// }
	
		if(prodType>0){ page=2; }
		appendTo.innerHTML="";
		appendTo.setAttribute("page",page);
		appendTo.setAttribute("prodType",prodType);
		appendTo.setAttribute("fontColor",fontColor);
		appendTo.setAttribute("bgHover",bgHover);
		//head line
		var newtable=createElement("table",{"border":"0","cellspacing":"0","style":"width:100%;"},appendTo);
		var newtr=createElement("tr",{},newtable);
		// switch bar prodType
		var newtd=createElement("td",{"align":"left"},newtr);
		var newdiv=createElement("div",{"style":"-moz-user-select:none;"},newtd);
		newdiv.addEventListener("mouseover",function(event){
			showToolTip(event,"Switch type of stock");
		},false);
		newdiv.addEventListener("click",function(event){
			var appendTo=this.parentNode.parentNode.parentNode.parentNode;
			var prodType=parseInt(event.target.getAttribute("prodType"),10);
			buildStockTable(parseInt(appendTo.getAttribute("page"),10),prodType,null,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
			appendTo=null;
		},false);
		var newdiv1;
		for(var i=0;i<prodName.length;i++){
			newdiv1=createElement("div",{"prodType":i,"class":"link hoverBgLightbrown","style":"display:inline-block;width:15px;text-align:center;color:"+fontColor+";font-weight:bold;border:1px inset black;"+(prodType==i?"background-color:lightblue;":"")},newdiv,numberFormat(i));
		}
		// headtext
		createElement("td",{"class":"tnormal","style":"color:"+fontColor+";font-weight:bold;text-align:center;"},newtr,page==1?texte["preise"]:texte["stock"]);
		// switch bar filterCategory
		newtd=createElement("td",{"align":"right"},newtr);
		newdiv=createElement("div",{"style":"-moz-user-select:none;"},newtd);
		newdiv.addEventListener("mouseover",function(event){
			var mouseOverText=event.target.getAttribute("mouseOverText");
			if(mouseOverText){
				mouseOverText='<div>'+texte["click"]+'&nbsp;/&nbsp;'+texte["clickStrg"]+'</div><div>'+mouseOverText+'</div>';
				showToolTip(event,mouseOverText);
			}
		},false);
		newdiv.addEventListener("click",function(event){
			var appendTo=this.parentNode.parentNode.parentNode.parentNode;
			var filterCategory=explode(event.target.getAttribute("filter"),"click/filterCategory",["",""]);
			filterCategory=(event.ctrlKey?filterCategory[1]:filterCategory[0]);
			buildStockTable(parseInt(appendTo.getAttribute("page"),10),parseInt(appendTo.getAttribute("prodType"),10),filterCategory,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
			appendTo=null;
		},false);
		switch(prodType){
		case 0:{
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["v"],"style":"display:inline-block;"},newdiv);
			if (filterCategory.match(/v/)){
				newdiv1.setAttribute("filter",implode(["v",filterCategory.replace(/v/,"")]));
				newdiv1.setAttribute("class","link rackcat1v_active");
			}else{
				newdiv1.setAttribute("filter",implode(["v",filterCategory+"v"]));
				newdiv1.setAttribute("class","link rackcat1v");
			}
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["e"],"style":"display:inline-block;"},newdiv);
			if (filterCategory.match(/e/)){
				newdiv1.setAttribute("filter",implode(["e",filterCategory.replace(/e/,"")]));
				newdiv1.setAttribute("class","link rackcat1e_active");
			}else{
				newdiv1.setAttribute("filter",implode(["e",filterCategory+"e"]));
				newdiv1.setAttribute("class","link rackcat1e");
			}
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["o"],"style":"display:inline-block;"},newdiv);
			if (filterCategory.match(/o/)){
				newdiv1.setAttribute("filter",implode(["o",filterCategory.replace(/o/,"")]));
				newdiv1.setAttribute("class","link rackcat5_active");
			}else{
				newdiv1.setAttribute("filter",implode(["o",filterCategory+"o"]));
				newdiv1.setAttribute("class","link rackcat5");
			}
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["c"]+"<br>"+texte["category"]["z"],"style":"display:inline-block;"},newdiv);
			if (filterCategory.match(/cz/)){
				newdiv1.setAttribute("filter",implode(["cz",filterCategory.replace(/cz/,"")]));
				newdiv1.setAttribute("class","link rackcat10_active");
			}else{
				newdiv1.setAttribute("filter",implode(["cz",filterCategory+"cz"]));
				newdiv1.setAttribute("class","link rackcat10");
			}
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["fw"],"class":"link rackcat20","style":"display:inline-block;"},newdiv);
			if (filterCategory.match(/fw1fw2fw3fw4/)){
				newdiv1.setAttribute("filter",implode(["fw1fw2fw3fw4",filterCategory.replace(/fw1fw2fw3fw4/,"")]));
				newdiv1.setAttribute("class","link rackcat20_active");
			}else{
				newdiv1.setAttribute("filter",implode(["fw1fw2fw3fw4",filterCategory+"fw1fw2fw3fw4"]));
				newdiv1.setAttribute("class","link rackcat20");
			}
		} break;
		case 1:{
			for(var i=1;i<=5;i++){
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["f"+i],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -10px 0px transparent;"},newdiv);
			if (filterCategory.match("f"+i)){
				newdiv1.setAttribute("filter",implode(["f"+i,filterCategory.replace("f"+i,"")]));
				newdiv1.style.backgroundPosition="-10px -20px";
				if (filterCategory == "f"+i){
					newtr.children[1].innerHTML += "&nbsp;"+texte["category"]["f"+i];
				}
			}else{
				newdiv1.setAttribute("filter",implode(["f"+i,filterCategory+"f"+i]));
				newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-10px 0px";},false);
				newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-10px -20px";},false);
			}
			}
		} break;
		case 2:{
			for(var i=0;i<=2;i++){
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["r"+i],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -10px 0px transparent;"},newdiv);
			if (filterCategory.match("r"+i)){
				newdiv1.setAttribute("filter",implode(["r"+i,filterCategory.replace("r"+i,"")]));
				newdiv1.style.backgroundPosition="-10px -20px";
				if (filterCategory == "r"+i){
					newtr.children[1].innerHTML += "&nbsp;"+texte["category"]["r"+i];
				}
			}else{
				newdiv1.setAttribute("filter",implode(["r"+i,filterCategory+"r"+i]));
				newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-10px 0px";},false);
				newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-10px -20px";},false);
			}
			}
		} break;
		case 3:{
			for(var i=0;i<=2;i++){
			newdiv1=createElement("div",{"mouseOverText":texte["category"]["p"+i],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -10px 0px transparent;"},newdiv);
			if (filterCategory.match("p"+i)){
				newdiv1.setAttribute("filter",implode(["p"+i,filterCategory.replace("p"+i,"")]));
				newdiv1.style.backgroundPosition="-10px -20px";
				if (filterCategory == "p"+i){
					newtr.children[1].innerHTML += "&nbsp;"+texte["category"]["p"+i];
				}
			}else{
				newdiv1.setAttribute("filter",implode(["p"+i,filterCategory+"p"+i]));
				newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-10px 0px";},false);
				newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-10px -20px";},false);
			}
			}
		} break;
		}
	
		//the table
		newdiv=createElement("div",{"style":"height:"+(parseInt(window.getComputedStyle(appendTo,null).height,10)-115)+"px;width:100%;font-color:"+fontColor+";overflow:auto;"},appendTo);
		newtable=createElement("table",{"border":"0","cellspacing":"0","style":"width:100%;"},newdiv);
		newtable.addEventListener("mouseover",function(event){
			var node=event.target;
			var mouseOverText=node.getAttribute("mouseOverText");
			while((node!=this)&&(!mouseOverText)){
				node=node.parentNode;
				mouseOverText=node.getAttribute("mouseOverText");
			}
			if(mouseOverText){ showToolTip(event,mouseOverText); }
			node=null;mouseOverText=null;
		},false);
	
		var newtablehead=createElement("thead",{},newtable);
		var newtablebody=createElement("tbody",{},newtable);
	
		newtr=createElement("tr",{},newtablehead);
		newtd=createElement("td",{"colspan":"7","class":"tnormal","align":"center","style":"color:"+fontColor+";font-weight:bold;"},newtr);
	
		var sumwert=0;
		newtr=createElement("tr",{},newtablehead);
		switch(page){
		case 1:{
			var preisBeob=explode(GM_getValue(LNG+"_"+SERVER+"_preisBeob","[]"),"buildPreise/preisBeob",[]); //isNotSent,time,min,max,amount
			if(!(preisBeob instanceof Array)){ preisBeob=new Array(); }
			createElement("td",{"colspan":"2","align":"center", "class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["product"]);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["bestand"]);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,"&nbsp;"+texte["hofpreis"]);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,"&nbsp;"+texte["beobachtet"]);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["marktpreis"]);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["abzglGebuehr"]);
	
			var prevTyp=null;
			var borderStr="";
			for(var w=0;w<prodNameSort[prodType].length;w++){
			try{
				v=prodNameSort[prodType][w];
				if((!prodBlock[prodType][v].match(/t/))&&(mode["showAll"]||((!prodBlock[prodType][v].match(/l/))&&(!prodBlock[prodType][v].match(/q/))))){
					if (filterCategory.search(prodTyp[prodType][v])!=-1){
						if(prodTyp[prodType][v]!="c"){ sumwert += prodStock[prodType][v]*gut[v]; }
						if((prevTyp!=null)&&(prevTyp!=prodTyp[prodType][v])){
							borderStr="border-top:1px dashed "+fontColor+";";
						}else{
							borderStr="";
						}
						prevTyp=prodTyp[prodType][v];
						newtr=createElement("tr",{},newtablebody);
						newtr.addEventListener("mouseover",function(){this.style.backgroundColor=bgHover;},false);
						newtr.addEventListener("mouseout",function(){this.style.backgroundColor="";},false);
		
						newdiv=createElement("td",{"style":borderStr},newtr);
						produktPic(prodType,v,newdiv);
		
						newdiv=createElement("td",{"style":borderStr},newtr);
						newa=createElement("a",{"prodId":v},newdiv,prodName[prodType][v]);
						if(prodBlock[prodType][v].match(/l/)){
							newtr.setAttribute("mouseOverText",texte["levelXneeded"].replace(/%1%/,/l(\d+)/.exec(prodBlock[prodType][v])[1]));
							newa.style.textDecoration="none";
						}else if(prodBlock[prodType][v].match(/t/)){
							newa.style.textDecoration="none";
						}else{
							if(prodType==0){
								newtr.setAttribute("mouseOverText",texte["wert"]+":&nbsp;"+moneyFormatInt(prodStock[prodType][v]*gut[v]));
								newa.setAttribute("mouseOverText",'<table class="white tmenu"><tr><th colspan="2" style="border-bottom:1px solid white">'+texte["goToMarketOfX"].replace(/%1%/,prodName[prodType][v])+'</th></tr><tr><td>'+texte["wert"]+'</td><td style="text-align:right;">'+moneyFormatInt(prodStock[prodType][v]*gut[v])+'</td></table>');
								newa.setAttribute("class","link");
								newa.addEventListener("click",function(){showMarket(this.getAttribute("prodId"));},false);
							}
						}
		
						createElement("td",{"style":"text-align:right;"+borderStr},newtr,prodBlock[prodType][v]?"<span style='color:red;'>---</span>":(prodStock[prodType][v]?numberFormat(prodStock[prodType][v]):"-"));
						newtd=createElement("td",{"style":"text-align:right;"+borderStr},newtr);
						if(NPC[prodType][v]){
							if(!isNaN(NPC[prodType][v])){
								newtd.innerHTML=numberFormat(NPC[prodType][v],2);
							}else if (NPC[prodType][v].match(/^f/)){
								newtd.innerHTML="("+numberFormat(parseFloat(NPC[prodType][v].replace("f",""),10),2)+")";
							}else if (NPC[prodType][v].match(/^c/)){
								coinsFormat(parseInt(NPC[prodType][v].replace("c",""),10),newtd);
							}
							if((NPCSAISON[v]!=undefined)&&(!NPCSAISON[v])){
								newtd.style.textDecoration="line-through";
								newtd.setAttribute("class","hoverNoTextDecoration");
							}
						}else{
							newtd.innerHTML="&nbsp;";
						}
		
						newtd=createElement("td",{"style":"text-align:right;"+borderStr},newtr,(gutBeob[v]?numberFormat(gutBeob[v],2):"&nbsp;"));
						if(preisBeob[v]){
							if(preisBeob[v][4]>0){
								newtd.setAttribute("mouseOverText",getFormattedDateStr(preisBeob[v][1])+"&nbsp;"+getDaytimeStr(preisBeob[v][1])+"<br>"+moneyFormat(preisBeob[v][2])+"&nbsp;-&nbsp;"+moneyFormat(preisBeob[v][3])+"<br>#"+numberFormat(preisBeob[v][4]));
							}else{
								newtd.setAttribute("mouseOverText",getFormattedDateStr(preisBeob[v][1])+"&nbsp;"+getDaytimeStr(preisBeob[v][1])+"<br>#"+numberFormat(preisBeob[v][4]));
								newtd.style.textDecoration="line-through";
								newtd.setAttribute("class","hoverNoTextDecoration");
							}
							if(now-preisBeob[v][1]>259200){ // 3 days
								if(now-preisBeob[v][1]>604800){ // 7 days
									newtd.style.color="red";
								}else{
									newtd.style.color="yellow";
								}
							}
						}else if(!prodBlock[prodType][v]){
							newtd.setAttribute("mouseOverText","---");
						}
		
						newtd=createElement("td",{"style":"text-align:right;"+borderStr},newtr);
						if(valNimmBeob){
							newtd.innerHTML=numberFormat(gut[v],2);
						}else{
							createElement("span",{"style":"font-size:0;"},newtd,numberFormat(gut[v],2));
							newinput=createElement("input",{"id":"inp"+v,"tabindex":parseInt(w,10)+1,"value":numberFormat(gut[v],2),"class":"text","size":"10","maxlength":"10","style":"text-align:right; background-color:transparent; color:"+fontColor+";"},newtd);
							newinput.addEventListener("focus",function(){this.style.backgroundColor=bgHover;},false);
							newinput.addEventListener("blur",function(){
								this.style.backgroundColor="transparent";
								this.value=numberFormat(gut[this.id.replace("inp","")],2);
							},false);
							newinput.addEventListener("change",function(){
								var currId=this.id.replace("inp","");
								var preis=Math.max(0,parseFloat(this.value.replace(regDelimThou,"").replace(regDelimDeci,"."),10));
								var thisNode=this;
								var yesFkt = function(){
									gut[currId]=preis;
									GM_setValue(LNG+"_"+SERVER+"_gut",implode(gut));
									raiseEventTop("gameChangedGut");
									thisNode.value=numberFormat(preis,2);
									thisNode.parentNode.nextSibling.innerHTML=numberFormat(0.9*preis,2);
									thisNode=null;
								};
								var noFkt = function(){
									thisNode.value=numberFormat(gut[currId],2);
									thisNode=null;
								};
								if(preis==0){
									alert2(texte["alertSetPriceNone"].replace(/%PRODUCT%/,prodName[prodType][currId]),texte["yes"],texte["no"],yesFkt,noFkt);
								}else if((!isNaN(NPC[prodType][currId]))&&(preis>NPC[prodType][currId])){
									alert2(texte["alertSetPriceOverNPC"].replace(/%PRODUCT%/,prodName[prodType][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%NPC%/,moneyFormat(NPC[prodType][currId])),texte["yes"],texte["no"],yesFkt,noFkt);
								}else if ((gutBeob[currId]!=undefined)&&(gutBeob[currId]>0)){
									if(preis<0.7*gutBeob[currId]){
										alert2(texte["alertSetPriceUnderObs"].replace(/%PRODUCT%/,prodName[prodType][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%OBS%/,moneyFormat(gutBeob[currId])),texte["yes"],texte["no"],yesFkt,noFkt);
									}else if (1.3*gutBeob[currId]<preis){
										alert2(texte["alertSetPriceOverObs"].replace(/%PRODUCT%/,prodName[prodType][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%OBS%/,moneyFormat(gutBeob[currId])),texte["yes"],texte["no"],yesFkt,noFkt);
									}else{
										yesFkt();
									}
								}else{
									yesFkt();
								}
								this.style.backgroundColor="transparent";
							},false);
						}
						createElement("td",{"style":"text-align:right;"+borderStr},newtr,numberFormat(0.9*gut[v],2));
					}
				}
			}catch(err){ GM_log("ERROR buildStockTable page="+page+" prodType="+prodType+" filterCategory="+filterCategory+"\nv="+v+"\n"+err); }
			}
		break;}
		case 2:{
			var valMinRackMan=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackMan",false);
			createElement("td",{"align":"center","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,"&nbsp;");
			newtd=createElement("td",{"align":"left","class":"headercell link","sortdir":"Desc","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["product"]);
			newtd.addEventListener("mouseover",function(){this.style.backgroundColor=bgHover;},false);
			newtd.addEventListener("mouseout",function(){this.style.backgroundColor="";},false);
			newtd=createElement("td",{"align":"right","class":"headercell link","sortdir":"Asc","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,texte["bestand"]);
			newtd.addEventListener("mouseover",function(){this.style.backgroundColor=bgHover;},false);
			newtd.addEventListener("mouseout",function(){this.style.backgroundColor="";},false);
			newtd=createElement("td",{"align":"right","class":"headercell link","sortdir":"Asc","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";"},newtr,"&nbsp;"+texte["wert"]);
			newtd.addEventListener("mouseover",function(){this.style.backgroundColor=bgHover;},false);
			newtd.addEventListener("mouseout",function(){this.style.backgroundColor="";},false);
			createElement("td",{"align":"right","class":"headercell","style":"color:"+fontColor+";border-bottom:1px dashed "+fontColor+";padding-right:20px"},newtr,"&nbsp;"+texte["minRack"]);
			new SortableTable(newtr);
	
			for(var w=0;w<prodNameSort[prodType].length;w++){
			try{
				v=prodNameSort[prodType][w];
				if(mode["showAll"]||((!prodBlock[prodType][v].match(/l/))&&(!prodBlock[prodType][v].match(/q/)))){
					if (filterCategory.search(prodTyp[prodType][v])!=-1){
						if((prodType==0)&&(prodTyp[prodType][v]!="c")){ sumwert+=prodStock[prodType][v]*gut[v]; }
						newtr=createElement("tr",{"v":v},newtablebody);
						newtr.addEventListener("mouseover",function(){this.style.backgroundColor=bgHover;},false);
						newtr.addEventListener("mouseout",function(){this.style.backgroundColor="";},false);
		
						newdiv=createElement("td",{},newtr);
						produktPic(prodType,v,newdiv);
		
						newdiv=createElement("td",{"value":w},newtr);
						newa=createElement("a",{"prodId":v},newdiv,prodName[prodType][v]);
						if(prodBlock[prodType][v].match(/l/)){
							newtr.setAttribute("mouseOverText",texte["levelXneeded"].replace(/%1%/,/l(\d+)/.exec(prodBlock[prodType][v])[1]));
							newa.style.textDecoration="none";
						}else if(prodBlock[prodType][v].match(/t/)){
							newa.style.textDecoration="none";
						}else{
							if(prodType==0){
								newtr.setAttribute("mouseOverText",texte["marktpreis"]+":&nbsp;"+moneyFormat(gut[v])); 
								newa.setAttribute("mouseOverText",'<table class="white tmenu"><tr><th colspan="2" style="border-bottom:1px solid white">'+texte["goToMarketOfX"].replace(/%1%/,prodName[prodType][v])+'</th></tr><tr><td>'+texte["marktpreis"]+'</td><td style="text-align:right;">'+moneyFormat(gut[v])+'</td></table>');
								newa.setAttribute("class","link");
								newa.addEventListener("click",function(){showMarket(this.getAttribute("prodId"));},false);
							}
						}
		
						if(prodBlock[prodType][v].match(/l/)){
							createElement("td",{"align":"right","value":0},newtr,"<span style='color:red;'>---</span>");
							createElement("td",{"align":"right","value":0},newtr,"<span style='color:red;'>---</span>");
						}else if(prodStock[prodType][v]){
							createElement("td",{"align":"right","value":prodStock[prodType][v]},newtr,numberFormat(prodStock[prodType][v]));
							if(prodType==0&&(!prodBlock[prodType][v].match(/t/))){ createElement("td",{"align":"right","value":prodStock[prodType][v]*gut[v]},newtr,numberFormat(prodStock[prodType][v]*gut[v])); }
							else{ createElement("td",{"align":"right","value":0},newtr,"-"); }
						}else{
							createElement("td",{"align":"right","value":0},newtr,"-");
							createElement("td",{"align":"right","value":0},newtr,"-");
						}
		
						newtd=createElement("td",{"align":"right","style":"padding-right:20px"},newtr);
						if(valMinRackMan){
							newinput=createElement("input",{"tabindex":parseInt(w,10)+1,"value":numberFormat(prodMinRackInit[prodType][v]),"class":"text","size":"10","maxlength":"10","style":"text-align:right; background-color:transparent; color:"+fontColor+";"},newtd);
							newinput.addEventListener("focus",function(){
								this.style.backgroundColor=bgHover;
							},false);
							newinput.addEventListener("blur",function(){
								this.style.backgroundColor="transparent";
								this.value=numberFormat(parseInt(this.value.replace(regDelimThou,""),10));
							},false);
							newinput.addEventListener("change",function(){
								var prodType=this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute("prodType");
								var currId=this.parentNode.parentNode.getAttribute("v");
								prodMinRackInit[prodType][currId]=parseInt(this.value.replace(regDelimThou,""),10);
								GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRackInit",implode(prodMinRackInit));
								raiseEventTop("gameChangedProdMinRackInit");
								this.style.backgroundColor="transparent";
								// var newdiv=$top("t"+currId);
								// if(newdiv){ raiseDOMAttrModified(newdiv); }
								// newdiv=null;
							},false);
						}else{
							createElement("span",{},newtd,numberFormat(prodMinRackInit[prodType][v]));
						}
					}
				}
			}catch(err){ GM_log("ERROR buildStockTable page="+page+" prodType="+prodType+" filterCategory="+filterCategory+"\nv="+v+"\n"+err); }
			}
		break;}
		}
		newtablebody.setAttribute("height",Math.min(361,19*newtablebody.childElementCount)+"px");
	
		//foot line
		newtable=createElement("table",{"border":"0","cellspacing":"0","style":"width:100%;"},appendTo);
		newtr=createElement("tr",{},newtable);
		newtd=createElement("td",{"align":"center","style":"border-top:1px dashed "+fontColor+";"},newtr);
		newdiv=createElement("input",{"type":"checkbox","class":"link","checked":mode["showAll"]},newtd);
		newdiv.addEventListener("click",function(){
			var mode=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeStockTable"),"buildStockTable/mode",null);
			mode["showAll"]=this.checked;
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeStockTable",implode(mode));
			var appendTo=this.parentNode.parentNode.parentNode.parentNode;
			buildStockTable(parseInt(appendTo.getAttribute("page"),10),null,null,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
			appendTo=null;
		},false);
		createElement("span",{},newtd,texte["showAll"]);
	
		newtd=createElement("td",{"align":"center","style":"border-top:1px dashed "+fontColor+";"},newtr);
		if((prodType==0)&&(page==1)&&(!valNimmBeob)){
			newa=createElement("a",{"class":"link2","style":"font-weight:bold;"},newtd,texte["nimmPreise"]);
			newa.addEventListener("click",function(){
				alert2(texte["confirm_NimmBeob"],texte["yes"],texte["no"],function(appendTo){return function(){
					for(var v=0;v<gutBeob.length;v++){
						gut[v]=gutBeob[v];
						if(!isNaN(NPC[0][v])){ gut[v]=Math.min(gut[v],NPC[0][v]); }
					}
					GM_setValue(LNG+"_"+SERVER+"_gut",implode(gut));
					raiseEventTop("gameChangedGut");
					buildStockTable(parseInt(appendTo.getAttribute("page"),10),null,null,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
				}}(this.parentNode.parentNode.parentNode.parentNode));
			},false);
		}
		newtd=createElement("td",{"align":"center","style":"border-top:1px dashed "+fontColor+";font-weight:bold;"},newtr,texte["stockvalue"]+":&nbsp;"+moneyFormatInt(sumwert));
	
		//buttons
		if(prodType==0){
		newdiv=createElement("div",{"id":"marketButton_tablePrices","class":"link2 hoverBlack","style":"position:absolute;bottom:0px;left:425px;width:80px;height:40px;background:url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},appendTo);
		newdiv.addEventListener("click",function(){
			var appendTo=this.parentNode;
			buildStockTable(1,null,null,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
			appendTo=null;
		},false);
		createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;color:white;"},newdiv,texte["preise"]);
		}
		newdiv=createElement("div",{"id":"marketButton_tableStock","class":"link2 hoverBlack","style":"position:absolute;bottom:0px;left:510px;width:80px;height:40px;background:url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},appendTo);
		newdiv.addEventListener("click",function(){
			var appendTo=this.parentNode;
			buildStockTable(2,null,null,appendTo,appendTo.getAttribute("fontColor"),appendTo.getAttribute("bgHover"));
			appendTo=null;
		},false);
		createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;color:white;"},newdiv,texte["stock"]);
	
		newtable=null;newtablehead=null;newtablebody=null;newtr=null;newtd=null;newdiv=null;newdiv1=null;
	}catch(err){ GM_log("ERROR buildStockTable page="+page+" prodType="+prodType+" filterCategory="+filterCategory+"\n"+err); }
	}
	function calcObservedPrice(mode,data){
		// data=[[amount1,price1],[amount2,price2],...]
		switch(mode){
		case 1:{ // normal mode. fast market
			data=data.clone();
			// kick upper 20% quantile
			var sum=0;
			for(var v=0;v<data.length;v++){
				sum += data[v][0];
			}
			sum=Math.floor(0.2*sum);
			for(var v=data.length-1;0<=v;v--){
				if(data[v][0]<sum){
					sum -= data[v][0];
					data.splice(v,1);
				}else{
					data[v][0] -= sum;
					sum=0;
					break;
				}
			}
	
			// calc weighted mean
			var weights=[3,3,3,3,2,2,2,2,1,1,1,1];
			var count1=0;
			var count2=0;
			for(var v=0;v<data.length;v++){
				if (weights[v]!=undefined){
					count1 += weights[v]*data[v][0]*data[v][1];
					count2 += weights[v]*data[v][0];
				}
			}
			if(count2>0){
				return (Math.round(100*count1/count2)/100);
			}else{
				return 0;
			}
		break;}
		case 2:{ // decorations. slow market
			if(data.length>1){
				return data[1][1];
			}else if(data.length==1){
				return data[0][1];
			}else{
				return 0;
			}
		break;}
		}
	}
	
	var err_trace="Session";
	if(DEVMODE){ showInLogBubble("Berater started"); }
	// Check if username is known
	if (!USERNAME){
		GM_log("Username is not known. Login again with running script.")
		location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
		return false;
	}
	// Check if browser is uptodate
	var newdiv,newdiv1;
	if(!createElement("div").children){
		newdiv=createElement("div",{"class":"alertbubble tbig link"},ALL,"Your browser could be too old.<br>This script uses functions which need Gecko&nbsp;1.9.1 (Firefox&nbsp;3.5).<br>You will get errors.");
		newdiv.addEventListener("click",function(){ removeElement(this); },false);
	}
	// Save session-id
	if (unsafeWindow.rid){	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_session",unsafeWindow.rid); }

	// Updatecheck, [time,version on server,last checked version]
	err_trace="Updatecheck";
	var updateCheck=explode(GM_getValue("updateCheck"),"do_main/updateCheck",[0,VERSION,VERSION]);
	if(GM_getValue("valUpdate",true)&&(now-updateCheck[0]>1800)){
		showInLogBubble("Checking for update (Berater)");
		updateCheck[0]=now;
		GM_setValue2("updateCheck",implode(updateCheck),1);
		GM_xmlhttpRequest({
			method: "GET",
			url: USO_Meta,
			onload: function(response){
				if(response.responseText.match(/@version\s+\d+\.\d+\.\d+/)){
					updateCheck[1]=(/@version\s+(\d+\.\d+\.\d+)/).exec(response.responseText)[1];
					if(VERSION==updateCheck[1]){
						// this script is the one of the server
						updateCheck[2]=updateCheck[1];
						GM_setValue2("updateCheck",implode(updateCheck),2);
						showInLogBubble("Update Check Berater: Script is up-to-date");
					}else if (updateCheck[1]!=updateCheck[2]){
						alert2(texte["msgUpdate"]+"<br>("+VERSION+"&nbsp;&rarr;&nbsp;"+updateCheck[1]+")",texte["yes"],texte["no"],function(){
							updateCheck[2]=updateCheck[1];
							GM_setValue2("updateCheck",implode(updateCheck),3);
							window.setTimeout(function(){
								location.href=USO_Source;
							},0);
						},function(){
							updateCheck[2]=updateCheck[1];
							GM_setValue2("updateCheck",implode(updateCheck),4);
						});
					}else{
						showInLogBubble("Update Check Berater: Newer version available, but not wanted");
					}
				}else{
					showInLogBubble("Update Check Berater failed. Bad Response: "+response.responseText);
				}
			}
		});
	}
	// GM_registerMenuCommand("LOG userfarminfos", function(){
	// 	GM_log("userfarminfos=\n"+print_r(unsafeWindow.userfarminfos,"",true,"\n"));
	// });

	// CSS
	err_trace="addStyle";
	GM_addStyle(
		".rackcat1v,.rackcat1e,.rackcat1v_active,.rackcat1e_active{background:url("+GFX+"rack_categories.png);width:30px;height:50px;}\n"
		+".rackcat1v{background-position:0px 0px;}"
		+".rackcat1e{background-position:-30px 0px;}"
		+".rackcat1v_active{background-position:0px -100px;}"
		+".rackcat1e_active{background-position:-30px -100px;}"
		+".rackcat1v:hover{background-position:0px -50px;}"
		+".rackcat1e:hover{background-position:-30px -50px;}"
	);	// Script elements
	GM_addStyle(
		 ".farmiInfo{position:absolute;height:35px;top:-47px;border-radius:5px;padding:5px;color:black;font-size:0.8em;}\n"
		+".farmiMiniInfo{position:absolute;top:45px;right:15px;height:7px;width:7px;display:block;border-radius:5px;}\n"
		+".questboxbarinPoss{position:absolute;top:0px;height:15px;background-color:green;opacity:0.5;}\n"
		+".zonetimer{z-index:3;position:absolute;padding:2px;"+css_styles["timer"][1]+"}\n"
		+".zoneTimerWater{z-index:3;position:absolute;padding:2px;"+css_styles["watertimer"][1]+"}\n"
		+".zonetimer[state=\"ready\"]{"+css_styles["timer_ready"][1]+"}\n"
		+".zonetimer[state=\"hidden\"],.zoneTimerWater[state=\"hidden\"]{display:none;}\n"
		+".beraterButtonIcon{float:left;margin-left:3px;width:30px;height:30px;overflow:hidden;background-color:#936b52;border:1px groove #4d240e;border-radius: 20px;}\n"
		+".leftarrow{height:26px;width:35px;border-radius:15px;background:url('"+strImages["leftarrow"]+"');}\n"
		+".leftarrow:hover{background:url('"+strImages["leftarrow_dark"]+"');}\n"
		+".rightarrow{height:26px;width:35px;border-radius:15px;background:url('"+strImages["rightarrow"]+"');}\n"
		+".rightarrow:hover{background:url('"+strImages["rightarrow_dark"]+"');}\n"
		+".formattedRackItem{position:absolute;top:3px;left:0;width:40px;font-size:7pt;color:#555555;text-align:center;}\n"
		+".lowrack{"+css_styles["lowrack"][1]+"}\n"
		+".farmicart_lowrack td{"+css_styles["farmicart_lowrack"][1]+"}\n"
		+".farmicart_missing td{color:red!important;}\n"
		+".border1 td,.border1 th{border:1px solid black;}\n"
		+".borderTop2 td,.borderTop2 th{border-top:2px solid black;}\n"
		+".borderBottom2 td,.borderBottom2 th{border-bottom:2px solid black;}\n"
		+".fontWeightBold td,.fontWeightBold th{font-weight:bold;}\n"
        +".questlineicon1{background:url('"+GFX+"questlineicons.gif') no-repeat scroll 0 0 transparent;float:left;height:19px;left:2px;position:absolute;top:2px;width:19px;}\n"
		+".questboxlinecontent:hover{background-color:#8F6803;}\n"
	);
	GM_addStyle(
		 "#timeHolder{"+css_styles["timeholder"][1]+"}\n"
		+"#imgNeedWater1,#imgNeedWater2,#imgNeedWater3,#imgNeedWater4,#imgNeedWater5,#imgNeedWater6{position:absolute;right:25px;height:63px;width:63px;}\n"
		+"#zoneinfo1,#zoneinfo2,#zoneinfo3,#zoneinfo4,#zoneinfo5,#zoneinfo6{border:2px solid #6c441e;border-radius:10px;z-index:3;position:absolute;left:120px;top:20px;}\n"
		+"#divErnteInfo{position:relative;float:left;top:120px;left:620px;padding:2px;border:2px inset white;background-color:#FFB876;display:none;}\n"
		+"#zoneNavi{position:absolute;top:9px;right:50px;z-index:25;}\n"
		+"#zoneNavi div{float:left;}\n"
	);
	// Game elements
	GM_addStyle(
		 ".friendslineoptions{width:72px!important;}\n"
		+".forestry_slot_product{margin:15px 0 0 20px!important;}\n"
		+".forestry_sawmill_productbox{width:272px!important;height:208px!important;padding:10px!important;}\n"
		+".rackitem_tt_sack,.rackitem_tt_box,.rackitem_tt_bottle,.rackitem_tt_karton,.rackitem_tt_tupper{z-index:110!important;}\n"
	);
	GM_addStyle(
		 "#cartsubmit{font-weight:bold!important;}\n"
		+"#transp8{display:none!important;}\n"
		+"#destructinfo1,#destructinfo2,#destructinfo3,#destructinfo4,#destructinfo5,#destructinfo6{display:none!important;}\n"
		+"#buildingdestructbutton1,#buildingdestructbutton2,#buildingdestructbutton3,#buildingdestructbutton4,#buildingdestructbutton5,#buildingdestructbutton6{display:none!important;}\n"
		+"#buildinginfo1,#buildinginfo2,#buildinginfo3,#buildinginfo4,#buildinginfo5,#buildinginfo6{display:none!important;}\n"
		+"#buildinginfo_right3,#buildinginfo_right6{display:none!important;}\n"
		+"#buildinginfo_left0,#buildinginfo_left1,#buildinginfo_left2,#buildinginfo_left4,#buildinginfo_left5{display:none!important;}\n"
		+"#updateinfo1,#updateinfo2,#updateinfo3,#updateinfo4,#updateinfo5,#updateinfo6{display:none!important;}\n"
		+"#autoplantinfo1,#autoplantinfo2,#autoplantinfo3,#autoplantinfo4,#autoplantinfo5,#autoplantinfo6{display:none!important;}\n"
		+"#speedupgardenbuttoninfo1,#speedupgardenbuttoninfo2,#speedupgardenbuttoninfo3,#speedupgardenbuttoninfo4,#speedupgardenbuttoninfo5,#speedupgardenbuttoninfo6{display:none!important;}\n"
		+"#bulldozetooltip1,#bulldozetooltip2,#bulldozetooltip3,#bulldozetooltip4,#bulldozetooltip5,#bulldozetooltip6{display:none!important;}\n"
		+"#emptyfieldtooltip1,#emptyfieldtooltip2,#emptyfieldtooltip3,#emptyfieldtooltip4,#emptyfieldtooltip5,#emptyfieldtooltip6{display:none!important;}\n"
		+"#timeevent1,#timeevent2,#timeevent3,#timeevent4,#timeevent5,#timeevent6{display:none!important;}\n"
		// +"#oil_slot1_img_tt,#oil_slot2_img_tt,#oil_slot3_img_tt{display:none!important;}\n"
		+"#friendslist{width:280px!important;}\n"
		+"#friendlistinfoblock li:hover{background-color:#e4b55d;}\n"
		+"#farmlinks,#cityline{display:block!important;}\n"
		+"#rackItems{-moz-user-select:none;}\n"
		+"#traveltransp,#questline,#questlineopener,#farmlinks,#guildlink,#guildlink_tt,#cityline,#farmtooltip1,#farmtooltip2,#farmtooltip3,#citytooltip1,#citytooltip2{z-index:110!important;}\n"
		+"#zone1,#zone2,#zone3,#zone4,#zone5,#zone6{z-index:1;}\n"
		+"#zoneupdatebutton1,#zoneupdatebutton2,#zoneupdatebutton3,#zoneupdatebutton4,#zoneupdatebutton5,#zoneupdatebutton6{position:absolute;left:5px;top:72px;}\n"
		+"#lager_wachsezeit,#lager_ertrag,#lager_ist1,#lager_ist2,#lager_zeit,#lager_ernte{margin:0 0 0 5px!important;}\n"
		+"#memory_pack{left:50px!important;top:10px!important;z-index:2!important;}\n"
		// +"#questboxline{z-index:31!important;}\n"
		+"#questboxlineinfo1,#questboxlineinfo2{display:none!important;}\n"
		+"#game_control{display:none!important;}\n"
		+"#food_cart_products{top:250px!important;}\n"
		+"#reallocatebuilding_symbol{top:150px!important;}\n"
		+"#reallocateanimals_symbol{top:175px!important;}\n"
		+"#gardencancel{right:5px!important;top:5px!important;}\n"
	);

	// Container Divs
	err_trace="Container";
err_trace="Container1";
	var nodes=new Object();
	ALL.style.margin="5px";
	var upjersToolbarHeight=parseInt(($("uptoolbar") && $("uptoolbar").style.display!="none")?"30":"0",10);
	newdiv=createElement("div",{"id":"gameArea","align":"center","style":"margin-top:"+upjersToolbarHeight+"px;"},ALL);
	newdiv1=createElement("div",{"id":"divGame","style":"position:relative;top:0;left:0;"},newdiv);
	var content_table=document.getElementsByClassName("content_table")[0];
	newdiv1.appendChild(content_table);
err_trace="Container2";
	content_table.style.position = "relative";
	createElement("div",{"id":"divStatistik","style":"display:none;"},newdiv);
	createElement("div",{"id":"divSettings","style":"position:relative;"},newdiv);
	//createElement("div",{"id":"divBeraterButtons","style":"position:absolute;bottom:0;left:0;display:block;z-index:100;"},$("garten_komplett"));
	createElement("div",{"id":"transp100","style":"z-index:100;background-color:black;opacity:0.7;position:absolute;top:0;left:0;width:720px;height:640px;display:none;"},$("garten_komplett"));
err_trace="Container3";
	$("multiframe").addEventListener("DOMAttrModified",function(event){
		//GM_log("multiframe DOMAttrModified "+this.style.display);
		if(this.style.display=="none"){
			var infoPanel=$("infoPanel");
			infoPanel.style.zIndex="101";
			if(infoPanel.style.display=="none"){
				$("transp100").style.display="none";
			}else{
				$("transp100").style.display="block";
			}
			infoPanel=null;
		}else{
			$("transp100").style.display="block";
		}
	},false);
	$("shopframe").addEventListener("DOMAttrModified",function(event){
		//GM_log("shopframe DOMAttrModified "+this.parentNode.style.display);
		if(this.parentNode.style.display=="none"){
			$("transp3").style.display="none";
		}else{
			$("transp3").style.display="block";
			$("multiframe").style.display="none";
			closeInfoPanel();
		}
	},false);
	$("gamearea_spacer").innerHTML="";
	if (window.innerWidth<1180){ content_table.style.paddingRight="176px"; }
	if (window.innerHeight>830){ ALL.style.overflowY="hidden"; }
err_trace="Container4";
	if(newdiv=$("errorboxgarden")){
		newdiv.style.left="600px";
		newdiv.style.top="105px";
	}else if(DEVMODE){
		GM_log("WARNING #errorboxgarden not found");
	}
	if(newdiv=$("popup_garden")){
		newdiv.style.top="";
	}else if(DEVMODE){
		GM_log("WARNING #popup_garden not found");
	}

	newdiv=createElement("div",{"style":"position:relative;height:100%;"},$("gamearea_spacer"));
	newdiv=createElement("div",{"id":"divBeraterButtons","style":"position:absolute;bottom:0;left:-9px;display:block;z-index:104;"},newdiv);
	newdiv.addEventListener("mouseover",function(event){
		var node=event.target;
		var mouseOverText=node.getAttribute("mouseOverText");
		while((node!=this)&&(!mouseOverText)){
			node=node.parentNode;
			mouseOverText=node.getAttribute("mouseOverText");
		}
		if(mouseOverText){ showToolTip(event,mouseOverText); }
		node=null;mouseOverText=null;
	},false);
	createElement("div",{"id":"divBeraterButtonsInfo","style":"position:absolute;top:-25px;white-space:nowrap;display:none;z-index:200;","class":"blackbox"},newdiv);

	err_trace="Container - fixedDivRight";
	newdiv=createElement("div",{"id":"fixedDivRight","style":"position:fixed;right:0;top:"+(upjersToolbarHeight)+"px;z-index:500;"},$("divGame"));
	createElement("div",{"id":"timeHolder"},newdiv);
	nodes["containerPowerupSymbols"]=new Object();
	nodes["containerPowerupSymbols"]["node"]=createElement("div",{"id":"containerPowerupSymbols"},newdiv);

	err_trace="Container - headercontainer";
	newdiv=createElement("div",{"style":"position:absolute;top:2px;left:210px;color:#f7bb87;z-index:10;"},$("headercontainer"));
	nodes["serverTime"]=new Object();
	nodes["serverTime"]["node"]=createElement("div",{"id":"serverTime","style":"float:left;margin-left:2px;"},newdiv);
	nodes["serverTime"]["node"].addEventListener("mouseover",function(event){ showToolTip(event,"Server time"); },false); // TODO texte
	function do_relogin(){
		window.setTimeout(function(){
			var help=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"clickListener@divSessionEnd/pagedataLogin",{});
			if(!(help["doserver"]&&(typeof help["doserver"]=="object"))){
				help["doserver"]=new Object();
			}
			help["doserver"][SERVER]=true;
			GM_setValue(LNG+"_pagedataLogin",implode(help));
			if($("logoutbutton")){
				click($("logoutbutton"));
			} else {
				location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
			}
		},0);
	}
	nodes["sessionTimeLeft"]=new Object();
	nodes["sessionTimeLeft"]["node"]=createElement("div",{"id":"sessionTimeLeft","class":"link","style":"float:left;margin-left:2px;"},newdiv);
	nodes["sessionTimeLeft"]["node"].addEventListener("mouseover",function(event){ showToolTip(event,"End of session at "+getDaytimeStr(valSessionEndtime)+"<br>Click to re-login"); },false); // TODO texte
	nodes["sessionTimeLeft"]["node"].addEventListener("click",do_relogin,false);
	nodes["sessionTimeNow"]=new Object();
	nodes["sessionTimeNow"]["node"]=createElement("div",{"id":"sessionTimeNow","style":"float:left;margin-left:2px;"},newdiv);
	nodes["sessionTimeNow"]["node"].addEventListener("mouseover",function(event){ showToolTip(event,"Local time"); },false); // TODO texte

	// Upgrade-data of buildings
	err_trace="Data";
	// BUILDING_UPGRADES[zoneType][levelNr-1][needed level,buildcost,bonus,animalamount]
	const BUILDING_UPGRADES=[,[[1,2000,0.95,0],[15,21500,0.9,0],[21,76000,0.85,0],[27,192300,0.8,0],[33,"c20",0.7,0]],[[2,2500,1,5],[7,15200,1,10],[12,32500,1,15],[23,134500,0.9,20],[29,350800,0.8,20]],[[11,3400,1,2],[13,16300,1,3],[17,50200,1,4],[25,159600,0.9,5],[32,441000,0.8,6]],[[14,6200,1,2],[18,33500,1,3],[20,76000,1,4],[28,210500,0.9,5],[34,482000,0.8,6]],[[19,6800,1,1],[22,44800,1,2],[26,128200,1,3],[31,230600,0.9,4],[35,482000,0.8,4]],[],[[16,5200,1,1],[19,33500,0.95,1],[25,106400,0.9,1],[30,230600,0.85,1],[33,441000,0.8,1]],[[18,6800,1,1],[21,38000,0.95,1],[27,128200,0.9,1],[31,230600,0.85,1],[35,482000,0.8,1]],[[27,8100,1,1],[30,53200,0.95,1],[33,140300,0.9,1],[36,264600,0.85,1],[38,597200,0.8,1]],[[30,9700,1,1],[33,70200,0.95,1],[34,153700,0.9,1],[37,289200,0.85,1],[39,626300,0.8,1]],[[16,10000,1,1],[20,85000,1,3],[24,200000,1,5],[28,"c22",0.9,6],[32,"c38",0.8,6]],[[15,38000,1,2],[17,17200,1,3],[23,54600,1,4],[29,168800,0.9,5],[38,472400,0.8,6]],[[31,16800,1,1],[32,86400,0.95,1],[34,174200,0.9,1],[36,362800,0.85,1],[38,796300,0.8,1]],[[35,19400,1,1],[37,97100,0.95,1],[39,218400,0.9,1],[40,509800,0.85,1],[41,1388600,0.8,1]],[[37,23000,1,1],[37,95300,1,2],[38,198500,1,3],[38,391700,0.9,4],[39,842200,0.8,5]],[[38,97100,1,1],[39,209736,0.95,1],[40,467711,0.9,1],[41,1080413,0.85,1],[42,2538970,0.8,1]],[[10,1000,1,1]]]; // task_new_building
	// produced thing -> production area
	const PRODUCT2BUILDING=[[,1,1,1,1,1,1,1,1,2,3,4,5,,,,,1,1,1,1,1,1,1,1,7,1,8,9,1,10,1,1,1,1,1,1,1,1,1,1,1,1,1,1,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,11,,,,,,1,,,,,,,1,,,1,1,1,12,8,1,1,1,1,13,13,13,13,13,13,14,14,14,14,1,1,1,1,,,,,,,,,,,,,,,7,,,,,,,15,9,1,1,16,16,16,1],{},[],[]];// task_new_plant task_new_product
	unsafeData.PRODUCT2BUILDING=PRODUCT2BUILDING.clone();
		/*
		var new_PRODUCT2BUILDING=PRODUCT2BUILDING.clone();
		new_PRODUCT2BUILDING[0][154]=1;
		GM_log(implode(new_PRODUCT2BUILDING));
		*/
	// produced thing <- production area
	const BUILDING2PRODUCT=[,,[9],[10],[11],[12],,[25,144],[27,111],[28,152],[30],[91],[110],[116,117,118,119,120,121],[122,123,124,125],[151],[155,156,157]]; // task_new_product
	unsafeData.BUILDING2PRODUCT=BUILDING2PRODUCT.clone();
	// zoneTyp -> -/field/stable/factory
	const BUILDINGTYPE=[0,1,2,2,2,2,0,3,3,3,3,2,2,3,3,2,3,0]; // task_new_building
	unsafeData.BUILDINGTYPE=BUILDINGTYPE.clone();
	// Needed input of a zone
	// BUILDING_INPUT[buildTyp]{output}[alternatives]=[[prod1,amount1||reducing time1],...]
	const BUILDING_INPUT=[,,{"9":[[[1,600]],[[2,1200]]]},{"10":[[[3,900]],[[4,1800]]]},{"11":[[[5,2400]],[[6,4800]]]},{"12":[[[7,4800]],[[8,9600]]]},,{"25":[[[9,30]]],"144":[[[21,450]]]},{"27":[[[10,12]]],"111":[[[110,5]]]},{"28":[[[11,8]]],"152":[[[151,5]]]},{"30":[[[12,5]]]},{"91":[[[92,14400]],[[93,28800]]]},{"110":[[[108,3600]],[[109,1800]]]},{"116":[[[2,1980]]],"117":[[[7,550]]],"118":[[[4,1020]]],"119":[[[38,650]]],"120":[[[42,110]]],"121":[[[43,100]]]},{"122":[[[112,130],[116,35]]],"123":[[[113,220],[117,35]]],"124":[[[114,345],[118,35]]],"125":[[[115,80],[119,35]]]},{"151":[[[153,1560]],[[154,3120]]]},{"155":[[[152,5],[28,6]]],"156":[[[152,8],[28,5]]],"157":[[[152,2],[28,9]]]}]; // task_new_product
	unsafeData.BUILDING_INPUT=BUILDING_INPUT.clone();
	// price of an animal. formula: cost=Math.round(ANIMALCOST[zone][0]+nr*ANIMALCOST[zone][1])
	const ANIMALCOST=[,,[309,1000/19],[419,320],[529,320],[1599,2600/3],,,,,,[999,1000],[789,320],,,[2400,1200],,]; // task_new_building
	// sizes of Farmis [width,height,left,top] in px , taken from setFarmis()
	const FARMISIZE=[,[40,60,-1,-5],[30,40,0,0],[30,40,2,0],[33,45,2,0],[33,45,4,2],[40,65,2,-11],[40,65,-2,-20]];
	USERLEVEL=parseInt(unsafeWindow.currentuserlevel,10);
	// Fix(Seberoth) why?
	if ( USERLEVEL >= 8 ) {
		unsafeWindow.cities = 2;
	} else {
		unsafeWindow.cities = 1;
	}
	var show=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_show","{}"),"do_main/show",{}); // buyNotepad,marketoffersNotepad
	if((typeof show!="object")||(show instanceof Array)){ show = new Object(); }
	questData=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_questData"),"questData",INIT_questData);
	// Check structure of questData
	for(var t in questData){
		if(!questData.hasOwnProperty(t)){continue;}
		if(INIT_questData[t]){
			for(var c in questData[t]){
				if(!questData[t].hasOwnProperty(c)){continue;}
				if(!INIT_questData[t][c]){ delete questData[t][c]; }
			}
		}else{
			delete questData[t];
		}
	}
	for(var t in INIT_questData){
		if(!INIT_questData.hasOwnProperty(t)){continue;}
		if(questData[t]){ 
			for(var c in INIT_questData[t]){
				if(!INIT_questData[t].hasOwnProperty(c)){continue;}
				if(!questData[t][c]){ questData[t]=INIT_questData[t]; }
			}
		}else{
			questData[t]=INIT_questData[t];
		}
	}
	// Check quest limits
	if(USERLEVEL<31){ questData["farm"]["2"]["nr"]=0; }
	if(USERLEVEL<20){ questData["lodge"]["1"]["nr"]=0; }
	if(questData["lodge"]["1"]["nr"]<35){ questData["lodge"]["2"]["nr"]=0; }
	unsafeData.questData=questData.clone();
	function setCalcToQuest(type,campaign,nr){
	try{
		// GM_log("setCalcToQuest type="+type+" campaign="+campaign+" nr="+nr);	
		if(QUESTS[type]&&QUESTS[type][campaign]&&questData[type][campaign]){
			questData[type][campaign]["calcTo"] = Math.min(nr,QUESTS[type][campaign].length);
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_questData",implode(questData));
			unsafeData.questData=questData.clone();		
			if(farmiLog){ doFarmis(); } //hack bypass early call
			calcProdMinRack();
		}
	}catch(err){ GM_log("ERROR setCalcToQuest\n"+err); }
	}
	unsafeData.setCalcToQuest=setCalcToQuest;

	for(var t in questData){
		if(!questData.hasOwnProperty(t)){continue;}
		for(var c in questData[t]){
			if(!questData[t].hasOwnProperty(c)){continue;}
			if((0<questData[t][c]["calcTo"])&&(questData[t][c]["calcTo"]<questData[t][c]["nr"])){
				setCalcToQuest(t,c,questData[t][c]["nr"]);
			}
		}
	}
	valServerTimeOffset=GM_getValue(LNG+"_valServerTimeOffset",0);
	todayStr=getDateStr(now,2,false);
	nowServerOff=unsafeWindow.Zeit.Server+valServerTimeOffset;
	todayServerStr=getDateStr(nowServerOff,2,false);

	var buyNotePadShowBlocked=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_buyNotePadShowBlocked",false);//TODO make option
	loadProductData();
	updateProductDataFarm();
	updateProductDataForestry();
	updateProductDataWindmill();
	updateProductDataPowerup();

	err_trace="Show Data";
	// SHOW DATA: BUILDING_INPUT
	/*
	for(var zone=0;zone<BUILDING_INPUT.length;zone++){
		if(!BUILDING_INPUT[zone]){continue;}
		for(var output in BUILDING_INPUT[zone]){
		if(!BUILDING_INPUT[zone].hasOwnProperty(output)){continue;}
			for(var alt=0;alt<BUILDING_INPUT[zone][output].length;alt++){
				var str="Zone "+zone+": ";
				for(var input=0;input<BUILDING_INPUT[zone][output][alt].length;input++){
					if(input>0){ str+=", "; }
					str+=numberFormat(BUILDING_INPUT[zone][output][alt][input][1])+" "+prodName[0][BUILDING_INPUT[zone][output][alt][input][0]]
				}
				str+=" -> "+prodName[0][output];
				GM_log(str);
			}
		}
	}	
	*/

	function plotTableQuests(qType){
	try{
		var container=createElement("div",{"style":"z-index:995;position:absolute;top:0;left:0;background-color:white;height:100%;"},ALL);
		var div=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:0;right:0;width:20px;height:20px;margin:5px;"},container);
		div.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		div=createElement("div",{"style":"height:100%;padding-right:20px;margin-right:30px;overflow:auto;"},container);
		var tr,newtd,table=createElement("table",{"border":"1"},div);
		var questCurr,item;
		for(var t in QUESTS[qType]){
			if(!QUESTS[qType].hasOwnProperty(t)){continue;}
			tr=createElement("tr",{"style":"background-color:orange;color:black;"},table);
			createElement("th",{"colspan":2},tr,"id");
			createElement("th",{"colspan":5},tr,"Input");
			createElement("th",{"colspan":2},tr,"Reward");
			for(var v=1;v<QUESTS[qType][t].length;v++){
				try{
				questCurr=QUESTS[qType][t][v];
				tr=createElement("tr",{},table);
				if(questData[qType][t]["nr"]==v){ tr.style.backgroundColor="#FBB"; }
				createElement("td",{},tr,t);
				createElement("td",{},tr,v);
				for(var i=0;i<5;i++){
					newtd=createElement("td",{"style":"white-space:nowrap;"},tr);
					if(questCurr[0][i]){
						if(typeof questCurr[0][i][0]=="object"){
							for(var j=0;j<questCurr[0][i].length;j++){
								if(j>0){ createElement("span",{},newtd," | "); }
								item=questCurr[0][i][j];
								produktPic(item[0],item[1],newtd);
								createElement("span",{},newtd,numberFormat(item[2])+"&nbsp;"+prodName[item[0]][item[1]]);
							}
						}else{
							item=questCurr[0][i];
							produktPic(item[0],item[1],newtd);
							createElement("span",{},newtd,numberFormat(item[2])+"&nbsp;"+prodName[item[0]][item[1]]);
						}
					}
				}
				// newtd=createElement("td",{},tr,questCurr[1]);
				newtd=createElement("td",{},tr);
					if(questCurr[2]>0){ pointsFormat(questCurr[2],"div",newtd); }
				newtd=createElement("td",{"style":"white-space:nowrap;"},tr);
					if(questCurr[3]){
						for(var w=0;w<questCurr[3].length;w++){
							switch(questCurr[3][w][0]){
							case 0:{
								createElement("div",{},newtd,moneyFormat(questCurr[3][w][1]));
							break;}
							case 1:{
								newdiv=createElement("div",{},newtd);
								produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
								createElement("span",{},newdiv,numberFormat(questCurr[3][w][3])+"&nbsp;"+prodName[questCurr[3][w][1]][questCurr[3][w][2]]);
							break;}
							case 2:{
								createElement("div",{},newtd,questCurr[3][w][1]+". rack accessed"); // TODO texte
							break;}
							case 3:{
								createElement("div",{},newtd,questCurr[3][w][1]+". farm accessed"); // TODO texte
							break;}
							case 4:{
								newdiv=createElement("div",{},newtd);
								produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
								createElement("span",{},newdiv,"-"+questCurr[3][w][3]+"min "+prodName[questCurr[3][w][1]][questCurr[3][w][2]]);
							break;}
							case 5:{
								newdiv=createElement("div",{},newtd);
								createElement("img",{"src":GFX+"adbonus.gif","style":"border:0;height:15px;"},newdiv);
								createElement("span",{},newdiv,"Farmi +"+questCurr[3][w][1]);
							break;}
							case 6:{
								createElement("div",{},newtd,"Log rack-amount +"+questCurr[3][w][1]); // TODO texte
							break;}
							case 7:{
								createElement("div",{},newtd,"Watering bonus "+questCurr[3][w][1]+"%"); // TODO texte
							break;}
							case 8:{
								createElement("div",{},newtd,"zone "+questCurr[3][w][1]+" accessed"); // TODO texte
							break;}
							case 9:{
								newdiv=createElement("div",{},newtd);
								produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
								createElement("span",{},newdiv,prodName[questCurr[3][w][1]][questCurr[3][w][2]]+" accessed");
							break;}
							case 10:{
								createElement("div",{},newtd,"Forest watering accessed"); // TODO texte
							break;}
							case 11:{
								newdiv=createElement("div",{},newtd);
								createElement("img",{"src":GFX+"adbonus.gif","style":"border:0;height:15px;"},newdiv);
								createElement("span",{},newdiv,"Farmi slots +"+questCurr[3][w][1]);
							break;}
							}
						}
					}
				}catch(err){ GM_log("ERROR plotTableQuests row v="+v+" i="+i+" j="+j+" item="+implode(item)+"\n"+err); }
			}
		}
		container=null;div=null;
		table=null;tr=null;newtd=null;
	}catch(err){ GM_log("ERROR plotTableQuests\n"+err); }
	}
	// SHOW Farm QUEST DATA
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Quests Farm",function(){ plotTableQuests("farm"); });
	// SHOW Lodge QUEST DATA
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Quests Forest", function(){ plotTableQuests("lodge"); });
/*	
		var div=createElement("div",{"style":"z-index:950;position:fixed;top:0;background-color:white;height:800px;overflow:auto;padding-right:40px;"},ALL);
		var newimg=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:8px;right:0px;width:20px;height:20px;"},div);
		newimg.addEventListener("click",function(){ removeElement(this.parentNode); },false);

		var tr,td,table=createElement("table",{"border":"1"},div);
		for(var campaign in QUESTS["lodge"]){
		if(!QUESTS["lodge"].hasOwnProperty(campaign)){continue;}	
			for(var v=1;v<QUESTS["lodge"][campaign].length;v++){
				tr = createElement("tr",{},table);
				if(questData["lodge"][campaign]["nr"]==v){ tr.style.backgroundColor="#FBB"; }
				createElement("td",{},tr,campaign);
				createElement("td",{},tr,v);
				for(var w=0;w<6;w++){
					td = createElement("td",{"style":"white-space:nowrap;"},tr);
					if(QUESTS["lodge"][campaign][v][0][w]){
						produktPic(QUESTS["lodge"][campaign][v][0][w][0],QUESTS["lodge"][campaign][v][0][w][1],td);
						createElement("span",{},td,numberFormat(QUESTS["lodge"][campaign][v][0][w][2]));
						td.setAttribute("mouseovertext",numberFormat(QUESTS["lodge"][campaign][v][0][w][2])+" "+prodName[QUESTS["lodge"][campaign][v][0][w][0]][QUESTS["lodge"][campaign][v][0][w][1]]);
						td.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseovertext")); },false);
					}
				}
				createElement("td",{},tr,QUESTS["lodge"][campaign][v][1]);
				td=createElement("td",{},tr);
					if(QUESTS["lodge"][campaign][v][2]){ pointsFormat(QUESTS["lodge"][campaign][v][2],"div",td); }
				td=createElement("td",{},tr);
					if(QUESTS["lodge"][campaign][v][3]){ createElement("div",{},td,implode(QUESTS["lodge"][campaign][v][3])); }
			}
		}
		div=null;newimg=null;
		table=null;tr=null;td=null;
	});
*/
	// SHOW BUILDING DATA
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Buildings", function(){
	try{
		var container=createElement("div",{"style":"z-index:995;position:absolute;top:0;left:0;background-color:white;height:100%;"},ALL);
		var div=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:0;right:0;width:20px;height:20px;margin:5px;"},container);
		div.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		div=createElement("div",{"style":"height:100%;padding-right:20px;margin-right:30px;overflow:auto;"},container);
		var table=createElement("table",{"border":"1"},div);
		var tr=createElement("tr",{},table);
		var td;
		createElement("th",{},tr);
		for(var w=1;w<unsafeWindow.buildinginfos[0][1].length;w++){
			createElement("th",{},tr,w);
		}
		createElement("th",{},tr,"BUILDING_UPGRADES");
		createElement("th",{},tr,"BUILDINGTYPE");
		for(var v in unsafeWindow.buildinginfos[0]){
			if(!unsafeWindow.buildinginfos[0].hasOwnProperty(v)){continue;}		
			tr=createElement("tr",{},table);
			createElement("td",{},tr,v);
			for(var w=1;w<unsafeWindow.buildinginfos[0][v].length;w++){
				createElement("td",{},tr,implode(unsafeWindow.buildinginfos[0][v][w]));
			}
			createElement("td",{},tr,implode(BUILDING_UPGRADES[v]));
			createElement("td",{},tr,implode(BUILDINGTYPE[v]));
		}
		container=null;div=null;
		table=null;tr=null;td=null;
	}catch(err){ GM_log("ERROR show building data\n"+err); }
	});
	
	var valMinRackMan=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackMan",false);
	const INIT_valMinRack={"v":200,"e":50,"o":10,"z":0,"f1":25,"f2":10,"f3":10,"f4":0};
	var valMinRack=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRack"),"do_main/valMinRack",INIT_valMinRack);
	bChanged=false;
	if((typeof valMinRack=="object")&&!(valMinRack instanceof Array)){ 
		for(var v in valMinRack){
			if(!valMinRack.hasOwnProperty(v)){continue;}
			if(INIT_valMinRack[v]==undefined){ delete valMinRack[v];bChanged=true; }
			else if(typeof valMinRack[v]!="number"){ valMinRack[v]=INIT_valMinRack[v];bChanged=true; }
		}
		for(var v in INIT_valMinRack){
			if(!INIT_valMinRack.hasOwnProperty(v)){continue;}
			if(valMinRack[v]==undefined){ valMinRack[v]=INIT_valMinRack[v];bChanged=true; }
		}
	}else{
		valMinRack=INIT_valMinRack;bChanged=true;
	}
	if(bChanged){ GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRack",implode(valMinRack,"valMinRack")); }
	var valMinRackPlantsize=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackPlantsize",false); //Use plant ratio
	var valMinRackFarmis=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackFarmis",true);
	var valMinRackForestryFarmis=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackForestryFarmis",true);
	var valMinRackGrowing=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackGrowing",true);
	var valMinRackRecursive=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackRecursive",false);
	var valFarmiLimits=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valFarmiLimits","[90,100]"),"do_main/valFarmiLimits",[90,100]);
	unsafeData.valFarmiLimits=valFarmiLimits.clone();
	var valFarmiMiniInfo=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valFarmiMiniInfo",true);

	// calcProdMinRackInit: sets base values
	// -> calcProdMinRack: adds quests, farmis, growing, addons, forestry 
	// (calls calcTotalQuest,calcTotalErnte)
	// -> doBuyNotepad, doRack, TODO doFarmis!
	// TODO: switch this logic to: calcTotalX -> calcProdMinRack
	function calcProdMinRackInit(){
		try{
		if(DEVMODE_FUNCTION){ GM_log("begin calcProdMinRackInit"); }
		prodMinRackInit=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRackInit"),"calcProdMinRackInit/prodMinRackInit",[[],{},{},{}]);
		if(!(prodMinRackInit instanceof Array)){ prodMinRackInit=[]; }
		for(var type in prodName){
			if(!prodName.hasOwnProperty(type)){continue;}
			if(type==1){
				if((!prodMinRackInit[type])||(typeof prodMinRackInit[type]!="object")||(prodMinRackInit[type] instanceof Array)){ prodMinRackInit[type]={}; } 
			}else{
				if((!prodMinRackInit[type])||(!(prodMinRackInit[type] instanceof Array))){ prodMinRackInit[type]=[]; } 
			}
			if(!valMinRackMan){ // detail-setting option (else see buildPreise)
				for(var prod in prodName[type]){
					//GM_log("prodName type:"+type+" prod:"+prod);
					if(!prodName[type].hasOwnProperty(prod)){continue;}
					if((!valMinRack[prodTyp[type][prod]])||(prodBlock[type][prod])){ // .match(/t/)
						prodMinRackInit[type][prod]=0;
					}else if(prodTyp[type][prod]=="v"){
						prodMinRackInit[type][prod]=valMinRack[prodTyp[type][prod]]/(valMinRackPlantsize?prodPlantSize[type][prod]:1);
					}else{
						prodMinRackInit[type][prod]=valMinRack[prodTyp[type][prod]];
					}
				}
			}
			prodMinRackInit[type].sortObj();
		}
		GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRackInit",implode(prodMinRackInit,"calcProdMinRackInit\prodMinRackInit"));
		unsafeData.prodMinRackInit=prodMinRackInit.clone();
		calcProdMinRack();
		if(DEVMODE_FUNCTION){ GM_log("end calcProdMinRackInit"); }
		}catch(err){ GM_log("ERROR calcProdMinRackInit\ntype="+type+" prod="+prod+"\n"+err); }
	}
	function calcProdMinRack(caller){
		try{
		if(DEVMODE){ GM_log("begin calcProdMinRack"); }
		prodMinRack=prodMinRackInit.clone();
		// Quest
		var err_trace="quest";
		for(var quTyp in QUESTS){
			if(!QUESTS.hasOwnProperty(quTyp)){ continue; }
			calcTotalQuest(quTyp);
			for(var type in totalQuest[quTyp]){
				if(!totalQuest[quTyp].hasOwnProperty(type)){ continue; }
				for(var prod in totalQuest[quTyp][type]){
					if(!totalQuest[quTyp][type].hasOwnProperty(prod)){ continue; }
					if(!prodMinRack[type][prod]){prodMinRack[type][prod]=0;}
					prodMinRack[type][prod] += totalQuest[quTyp][type][prod];
				}
			}
		}
		// Farmis
		err_trace="farmis";
		if(valMinRackFarmis){
			for(var prod in totalFarmis[0]){
				if(!totalFarmis[0].hasOwnProperty(prod)){ continue; }
				if(!prodMinRack[0][prod]){ prodMinRack[0][prod]=0;}
				prodMinRack[0][prod] += totalFarmis[0][prod];
			}
		}
		if(valMinRackForestryFarmis){
			for(var prod in totalFarmis[1]){
				if(!totalFarmis[1].hasOwnProperty(prod)){ continue; }
				if(!prodMinRack[1][prod]){ prodMinRack[1][prod]=0;}
				prodMinRack[1][prod] += totalFarmis[1][prod];
			}
		}
		// Growing products
		err_trace="growing";
		if(valMinRackGrowing){
			calcTotalErnte();
			for(var type in totalErnte){
				if (!totalErnte.hasOwnProperty(type)){ continue; }
				for(var prod in totalErnte[type]){
					if(!totalErnte[type].hasOwnProperty(prod)){ continue; }
					if(!prodMinRack[type][prod]){prodMinRack[type][prod]=0;}
					prodMinRack[type][prod] -= totalErnte[type][prod];
				}
			}
			for(var prod in totalPowerups){
				if(!totalPowerups.hasOwnProperty(prod)){ continue; }
				if(!prodMinRack[0][prod]){prodMinRack[0][prod]=0;}
				prodMinRack[0][prod] -= totalPowerups[prod];
			}
		}
		// Addons
		err_trace="addons";
		for(var type in prodMinRackAddon){
			if (!prodMinRackAddon.hasOwnProperty(type)){ continue; }
			for(var prod in prodMinRackAddon[type]){
				if(!prodMinRackAddon[type].hasOwnProperty(prod)){ continue; }
				if(prodMinRackAddon[type][prod]){
					for(var k in prodMinRackAddon[type][prod]){
						if(!prodMinRackAddon[type][prod].hasOwnProperty(k)){ continue; }
						if(!prodMinRack[type][prod]){prodMinRack[type][prod]=0;}
						prodMinRack[type][prod] += prodMinRackAddon[type][prod][k];
					}
				}
			}
		}
		err_trace="recursive";
		//GM_log("Before calcTotalRecursive prodMinRack:"+implode(prodMinRack[1]));
		if(valMinRackRecursive){
			calcTotalRecursive(); // recursive need products calculation
			for(var type in totalRecursive){
				if (!totalRecursive.hasOwnProperty(type)){ continue; }
				for(var prod in totalRecursive[type]){
					if(!totalRecursive[type].hasOwnProperty(prod)){ continue; }
					if(!prodMinRack[type][prod]){prodMinRack[type][prod]=0;}
					prodMinRack[type][prod] += totalRecursive[type][prod];
				}
			}
		}
		//GM_log("After calcTotalRecursive totalRecursive:"+implode(totalRecursive));
		//GM_log("After calcTotalRecursive prodMinRack:"+implode(prodMinRack[1]));
		//GM_log("After calcTotalRecursive prodStock:"+implode(prodStock[1]));
		
		// delete wrong values
		err_trace="QA";
		for(var type in prodMinRack){
			if (!prodMinRack.hasOwnProperty(type)){ continue; }
			for(var prod in prodMinRack[type]){
				if(!prodMinRack[type].hasOwnProperty(prod)){ continue; }
                try{ 
					if(prodMinRack[type][prod]<0){ // delete negatives
						prodMinRack[type][prod]=0;
					}else if((type==0)&&(prodBlock[0][prod].match(/l/))){ // delete non-availables
						prodMinRack[type][prod]=0;
					}
				}catch(err){}
			}
		}

		err_trace="save";
		unsafeData.prodMinRack=prodMinRack.clone();
		unsafeData.prodMinRackSettings = {"valMinRackGrowing":valMinRackGrowing,"valMinRackFarmis":valMinRackFarmis,"valMinRackFarmis":valMinRackFarmis,"valMinRackRecursive":valMinRackRecursive};
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRack",implode(prodMinRack));
		doBuyNotepad();
		doRack();
		doFarmis();
		raiseEvent("gameCalcProdMinRack");
		if(DEVMODE){ GM_log("end calcProdMinRack"); }
		}catch(err){ GM_log("ERROR calcProdMinRack ("+err_trace+")\ntype="+type+" prod="+prod+"\n"+err); }
	}
	/*
	for(var v=0;v<prodName[0].length;v++){
		GM_log(v+":"+prodName[0][v]+":NPC "+NPC[0][v]+":typ "+prodTyp[0][v]+":block "+prodBlock[0][v]);
	}
	*/
	unsafeWindow._createAdvancedProductResponse=unsafeWindow.createAdvancedProductResponse;
	unsafeWindow.createAdvancedProductResponse=function(request,position){
	try{
		unsafeWindow._createAdvancedProductResponse(request,position);
	}catch(err){ GM_log("ERROR _createAdvancedProductResponse\n"+err); }
	try{
		var result=checkRequest(request);
		if(result&&result[0]!=0){
			raiseEvent("gameStartFactory");
		}
	}catch(err){ GM_log("ERROR createAdvancedProductResponse\n"+err); }
	};
	// Farmis
	err_trace="Farmis";
	$("customerstats").setAttribute("class","link");
	$("customerstats").addEventListener("click",function(){buildInfoPanel("farmiLog");},false);
	// farmiLog[farmiId]=[date,money,{prod1:amount,...}]
	var farmiLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_farmiLog","{}"),"do_main/farmiLog",{});
	// kick farmis older than 1 month, set this value optional?
	var dayLastMonth=new Date();
	dayLastMonth=Math.round(((new Date(dayLastMonth.getFullYear(),dayLastMonth.getMonth()-1,dayLastMonth.getDate())).getTime())/1000);
	for(var v in farmiLog){
		if(!farmiLog.hasOwnProperty(v)){ continue; }
		if (getTime(farmiLog[v][0])<=dayLastMonth){
			delete farmiLog[v];
		}
	}

	unsafeWindow._handleFarmiResponse=unsafeWindow.handleFarmiResponse;
	unsafeWindow.handleFarmiResponse = function(request,farmi,status){
		unsafeWindow._handleFarmiResponse(request,farmi,status);
		var result=checkRequest(request);
		if(result&&result[0]!=0){
			// unsafeWindow.farmisinfo[0][farmi]["sold"]=1;
			window.setTimeout(function(){
				calcFarmiCost();
				calcTotalFarmis();
				doFarmis();
				raiseEvent("gameFarmiResponse");
			},0);
		}
	};
	function calcFarmiCost(){ //done on price change, on load and on a new farmi
	try{
		if(DEVMODE_FUNCTION){GM_log("begin calcFarmiCost"); }
		// calculate costs of the farmis
		for(var farmiNr in unsafeWindow.farmisinfo[0]){
			if(!unsafeWindow.farmisinfo[0].hasOwnProperty(farmiNr)){ continue; }
			var wert=0;
			var priceMissing=0;
			for(var i=1;i<=7;i++){ // 7=max-amount of products per farmi
				var pid=unsafeWindow.farmisinfo[0][farmiNr]["p"+i];
				var amount=parseInt(unsafeWindow.farmisinfo[0][farmiNr]["a"+i],10);
				if((pid>0)&&(amount>0)){
					if(gut[pid]>0){
						wert += amount*gut[pid];
					}else{
						priceMissing++;
					}
				}
			}
			unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]=(priceMissing>0?null:(100*parseFloat(unsafeWindow.farmisinfo[0][farmiNr]["price"],10)/wert));
			unsafeWindow.farmisinfo[0][farmiNr]["marketValue"]=(priceMissing>0?0:wert);
		}
		if(DEVMODE_FUNCTION){GM_log("end calcFarmiCost"); }
	}catch(err){ GM_log("ERROR calcFarmiCost\n"+err); }
	}
	function doFarmis(){
	try{
		if(DEVMODE_FUNCTION){GM_log("begin doFarmis"); }
		// TODO: Questproduct is not calculated in at first run. Fixed now I believe
		//this can't go in the above loop because the amountMinRack are needed to be calculated first
		var missing,belowMinRack,belowMinRackInit;
		for(var farmiNr=0;farmiNr<$("customerline").childElementCount;farmiNr++){
			missing=0;belowMinRack=0;belowMinRackInit=false;
			for(var i=1;i<=7;i++){ // 7=max-amount of products per farmi
				var pid=unsafeWindow.farmisinfo[0][farmiNr]["p"+i];
				var amount=parseInt(unsafeWindow.farmisinfo[0][farmiNr]["a"+i],10);
				if((pid > 0) && (amount > 0)){
					if(prodStock[0][pid]<amount){ missing++; }
					if((prodStock[0][pid]-amount)<prodMinRack[0][pid]-((valMinRackFarmis&&totalFarmis[0]&&totalFarmis[0][pid])?totalFarmis[0][pid]:0)){ belowMinRack++; }
					if((prodStock[0][pid]-amount)<prodMinRackInit[0][pid]){ belowMinRackInit++; }
				}
			}
			unsafeWindow.farmisinfo[0][farmiNr]["missing"]=missing;
			unsafeWindow.farmisinfo[0][farmiNr]["belowMinRack"]=belowMinRack;
			unsafeWindow.farmisinfo[0][farmiNr]["belowMinRackInit"]=belowMinRackInit;
		}
		missing=null;belowMinRack=null;belowMinRackInit=null;
		var cell, info;
		if(unsafeWindow.farm==1){
			var str;
			for(var farmiNr=0;farmiNr<$("customerline").childElementCount;farmiNr++){
				if (!$("farmiInfo"+farmiNr)){ // assure that this code is run only once per farmi. else eventlisteners are stacked
					// prepare the additional farmi-info-bubble
					createElement("div",{"id":"farmiInfo"+farmiNr,"class":"farmiInfo"},$("blase"+farmiNr));
					createElement("div",{"id":"farmiMiniInfo"+farmiNr,"class":"farmiMiniInfo"},$("kunde_"+farmiNr));
					//createElement("div",{"id":"farmiInfo"+farmiNr,"style":"position:absolute;height:35px;top:-47px;border-radius:5px;padding:5px;color:black;font-size:0.8em;"},$("blase"+farmiNr));
					//createElement("div",{"id":"farmiMiniInfo"+farmiNr,"style":"position:absolute;top:45px;right:15px;height:7px;width:7px;display:block;border-radius:5px;"},$("kunde_"+farmiNr));
					// fill the bubble when shown
					$("kunde_"+farmiNr).addEventListener("mouseover",function(event){
						var farmiNr=this.id.replace("kunde_","");
						// showToolTip(event,print_r(unsafeWindow.farmisinfo[0][farmiNr],"",true));
						var cash=parseFloat(unsafeWindow.farmisinfo[0][farmiNr]["price"],10);
						var wert = parseFloat(unsafeWindow.farmisinfo[0][farmiNr]["marketValue"],10);
						var cell=$("blase"+farmiNr).firstElementChild.firstElementChild;
						var ppid, amount;
						for(var i=1;i<=7;i++){ // 7=maxanzahl produkte pro farmi
							if(cell.style.clear=="both"){ // line break after 4 products
								cell=cell.nextElementSibling;
								if(!cell){ break; }
							}
							pid=unsafeWindow.farmisinfo[0][farmiNr]["p"+i];
							amount=parseInt(unsafeWindow.farmisinfo[0][farmiNr]["a"+i],10);
							if((pid>0)&&(amount>0)){
								if(prodStock[0][pid]<amount){
									// not enough in rack
									cell.setAttribute("style",css_styles["prod_border_missing"][1]+"overflow:hidden; margin-right:2px; marign-bottom:2px; float:left; width:15px; height:15px;border-radius:4px;");
								}else if(prodStock[0][pid]-amount<prodMinRack[0][pid]-((valMinRackFarmis&&totalFarmis[0]&&totalFarmis[0][pid])?totalFarmis[0][pid]:0)){
									// selling this farmi will push the rack below the min-value
									cell.setAttribute("style",css_styles["prod_border_lowamount"][1]+"overflow:hidden; margin-right:2px; marign-bottom:2px; float:left; width:15px; height:15px;border-radius:4px;");
								}else{
									cell.style.border="1px solid white";
									//css_styles["prod_border_none"][[],"1px solid white","1px solid white"];
									//cell.setAttribute("style",css_styles["prod_border_none"][1]+"overflow:hidden; margin-right:2px; marign-bottom:2px; float:left; width:15px; height:15px;border-radius:4px;");
								}
							}
							cell=cell.nextElementSibling;
							if(!cell){ break; }
						}
						cell=$("farmiInfo"+farmiNr);
						if(!unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]){
							// a price is missing. can't calculate, so display white
							cell.innerHTML=moneyFormatInt(cash);
							cell.setAttribute("style",css_styles["cloud_back_noprice"][1]+css_styles["cloud_border_noprice"][1]);
						}else if(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]<valFarmiLimits[0]){
							// low case
							cell.innerHTML=moneyFormatInt(cash)+"<br>"+numberFormat(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"],1)+"&nbsp;%<br>"+moneyFormatInt(cash-wert)+"&nbsp;|&nbsp;"+moneyFormatInt(cash-0.9*wert);
							cell.setAttribute("style",css_styles["cloud_back_below"][1]+css_styles["cloud_border_below"][1]);
						}else if(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]<valFarmiLimits[1]){
							// middle case
							cell.innerHTML=moneyFormatInt(cash)+"<br>"+numberFormat(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"],1)+"&nbsp;%<br>"+moneyFormatInt(cash-wert)+"&nbsp;|&nbsp;+"+moneyFormatInt(cash-0.9*wert);
							cell.setAttribute("style",css_styles["cloud_back_between"][1]+css_styles["cloud_border_between"][1]);
						}else{
							// high case
							cell.innerHTML=moneyFormatInt(cash)+"<br>"+numberFormat(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"],1)+"&nbsp;%<br>+"+moneyFormatInt(cash-wert)+"&nbsp;|&nbsp;+"+moneyFormatInt(cash-0.9*wert);
							cell.setAttribute("style",css_styles["cloud_back_above"][1]+css_styles["cloud_border_above"][1]);
						}
						cell=null;
					},false);
					// farmi is new=not in the FarmiLog

					if (farmiLog[unsafeWindow.farmisinfo[0][farmiNr]["id"]]==undefined){
						raiseEvent("gameFarmiNew");
						//todayStr=getDateStr(now,2,false);
						// add this new farmi
						farmiLog[unsafeWindow.farmisinfo[0][farmiNr]["id"]]=[todayStr,parseFloat(unsafeWindow.farmisinfo[0][farmiNr]["price"],10),{}];
						for(var w=1;w<8;w++){
							if (unsafeWindow.farmisinfo[0][farmiNr]["p"+w]!="0"){
								farmiLog[unsafeWindow.farmisinfo[0][farmiNr]["id"]][2][unsafeWindow.farmisinfo[0][farmiNr]["p"+w]]=parseInt(unsafeWindow.farmisinfo[0][farmiNr]["a"+w],10);
							}
						}
						farmiLog.sortObj(function(a,b){return (getTime(a[1][0])-getTime(b[1][0]));},true);
						if(levelLog[todayServerStr]==undefined){ levelLog[todayServerStr]=[0,null,0,0,0]; }
						levelLog[todayServerStr][4] += farmiLog[unsafeWindow.farmisinfo[0][farmiNr]["id"]][1];
						levelLog[todayServerStr][4]=Math.round(100*levelLog[todayServerStr][4])/100;
						// saving
						GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_farmiLog",implode(farmiLog));
						GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog));
						window.setTimeout(doBuyNotepad,0);
					}
				}
				if(valFarmiMiniInfo){
					// Price
					if(!unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]){ // unknown case
						str = css_styles["farmi_price_unknown"][1];
					}else if(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]<valFarmiLimits[0]){ // low case
						str = css_styles["farmi_price_low"][1];
					}else if(unsafeWindow.farmisinfo[0][farmiNr]["costQuotient"]<valFarmiLimits[1]){ // middle case
						str = css_styles["farmi_price_between"][1];
					}else{ // high case
						str = css_styles["farmi_price_above"][1];
					}
					// Rackamount
					if(unsafeWindow.farmisinfo[0][farmiNr]["missing"]>0){
						str += ' '+ css_styles["farmi_amount_missing"][1];
					}else if(unsafeWindow.farmisinfo[0][farmiNr]["belowminvalue"]>0){
						str += ' '+ css_styles["farmi_amount_low"][1];
					}else{
						str += ' '+ css_styles["farmi_amount_above"][1];
					}
					
					cell=$("farmiMiniInfo"+farmiNr);
					if(cell.getAttribute("style")!=str){ cell.setAttribute("style",str); }
				}
			}
			// 
			if((unsafeWindow.customerstats)&&(unsafeWindow.customerstats["adstart"])&&(unsafeWindow.adrun)){
                var endDay = getDateStr(getTime(unsafeWindow.customerstats["adstart"])+4*86400-1);
			    if((unsafeWindow.customerstats[endDay])&&(parseInt(unsafeWindow.customerstats[endDay]["count"],10)>=(farmiZahl+2*unsafeWindow.adrun))){
					cell=$("alertAdvertEnd");
					if(!cell){
						createElement("div",{"id":"alertAdvertEnd","style":"position:absolute;top:65px;left:0;color:white;font-weight:bold;background-color:red;padding:2px;white-space:nowrap;"},$("customerstats"),texte["adEnds"]);
						window.setTimeout(function(){
							var newdiv;
							if(newdiv=$("alertAdvertEnd")){ removeElement(newdiv); }
							newdiv=null;
						},1000*(getTime(getDateStr(now,2,false))+86400-now)); // time till midnight
					}
				}else{
					cell=$("alertAdvertEnd");
					if(cell){ removeElement(cell); }
				}
				endDay = null;
			}else{
				cell=$("alertAdvertEnd");
				if(cell){ removeElement(cell); }
			}
			str=null;
		}else{
			cell=$("alertAdvertEnd");
			if(cell){ removeElement(cell); }
		}
		cell=null;
	}catch(err){ GM_log("ERROR doFarmis\n"+err); }
	}
	// Foodworld
	err_trace="Foodworld";
	// Foodworld-Farmi
	unsafeWindow._showFoodworldFarmiCart=unsafeWindow.showFoodworldFarmiCart;
	unsafeWindow.showFoodworldFarmiCart=function(id){
		unsafeWindow._showFoodworldFarmiCart(id);
		try{
			var newdiv, sum=0, prodId;
			if(newdiv=$("food_cart_products")){
				for(var i=0;i<newdiv.childElementCount;i++){
					prodId=parseInt(newdiv.children[i].firstElementChild.getAttribute("class").replace(/\D+/g,""),10);
					newdiv.children[i].setAttribute("prodId",prodId);
					newdiv.children[i].setAttribute("class","link");
					newdiv.children[i].addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prodId")); },false);
					newdiv.children[i].addEventListener("click",function(event){ showMarket(this.getAttribute("prodId")); },false);
					sum+=gut[prodId]*unsafeWindow.foodworldfarmis[id]["products"][prodId];
				}
			}
			if(newdiv=$("food_cart_cost")){
				newdiv.innerHTML="100%:&nbsp;"+moneyFormatInt(sum)+"&nbsp;|&nbsp;90%:&nbsp;"+moneyFormatInt(0.9*sum);
			}
			newdiv=null;
		}catch(err){ GM_log("ERROR showFoodworldFarmiCart\n"+err); }
	}
	if(newdiv=$("food_cart")){
		createElement("div",{"style":"position:absolute;bottom:130px;left:135px;font-size:12px;color:#463824;","id":"food_cart_cost"},newdiv);
	
	}
	// Foodworld-Zones
	function doFoodworld(){
	try{
		gameLocation=["foodworld",null];
		unsafeData.gameLocation=gameLocation.clone();
		var nowServer=unsafeWindow.Zeit.Server;
		var zoneNrF,zoneNrS,tempZoneProductionData,tempZoneProductionDataSlot;
		// GM_log("forestry_slots:\n"+print_r(unsafeWindow.forestry_slots,"",true,"\n"));
		// Buildings
		var err_trace="Buildings";
		if(unsafeWindow.foodworldbuildings){
			var res,iProd,iTime,iSlotCount;
			for(var building in unsafeWindow.foodworldbuildings){
				if(!unsafeWindow.foodworldbuildings.hasOwnProperty(building)){continue;}
				res=unsafeWindow.foodworldbuildings[building];
				zoneNrF="foodworld-"+building;
				zoneBlock[zoneNrF]=(unsafeWindow.foodworldbuildings[building]["cost"]?"b":""); // foodworld building locked due to missing payment
				zoneBlock[zoneNrF]+=(unsafeWindow.foodworldbuildings[building]["block"]?"l":""); // foodworld building locked due to level requirement				
				if(isMultiSlotZone(zoneNrF)){
					iSlotCount=3;
					if(zoneBlock[zoneNrF]){
						for(var slot=1;slot<=3;slot++){
							zoneBlock[zoneNrF+"."+slot]=true;
						}
					}else{
						for(var slot=1;slot<=3;slot++){
							zoneBlock[zoneNrF+"."+slot]=!!(res["slots"]&&res["slots"][slot]&&res["slots"][slot]["block"]);
						}
					}
				}else{
					iSlotCount=0;
				}
				if(!zoneBlock[zoneNrF]){
					zoneBonus[zoneNrF]=0; // TODO // unsafeWindow.forestry_user_buildings[building]["boni"]?unsafeWindow.forestry_user_buildings[building]["boni"]:0;
					res=(unsafeWindow.foodworldbuildings[building]&&unsafeWindow.foodworldbuildings[building]["slots"])?unsafeWindow.foodworldbuildings[building]["slots"]:{};
					
					tempZoneProductionData=[[{},{}],0,0,true];
					for(var slot=1;slot<=(iSlotCount==0?1:iSlotCount);slot++){
						if(DEVMODE){ GM_log("doFoodworld zoneNrF="+zoneNrF+" slot="+slot+" res["+slot+"]="+implode(res[slot],"res")); }
						if(iSlotCount>0){
							zoneNrS=zoneNrF+"."+slot;
						}else{
							zoneNrS=zoneNrF;
						}
						if(!zoneBlock[zoneNrS]){
							tempZoneProductionDataSlot=[[{},{}],0,0,true];
							if(res[slot]){
								iProd=(res[slot]["pid"]?parseInt(res[slot]["pid"],10):null);
								if(isNaN(iProd)){ iProd=null; }
								if((iProd!=null)&&(res[slot]["ready"])){ // production ready
									iTime=nowServer;
								}else if((iProd!=null)&&(res[slot]["remain"])){ // production busy
									iTime=nowServer+res[slot]["remain"]; 
								}else{
									iTime=NEVER;
									tempZoneProductionData[1]++;
									tempZoneProductionDataSlot[1]++;
								}
								// iAmount=(res[slot]["amount"]?res[slot]["amount"]:null);
								tempZoneProductionData[2]++;
								tempZoneProductionDataSlot[2]++;
								if(iProd!=null){
									if(!tempZoneProductionData[0][0][iProd]){ tempZoneProductionData[0][0][iProd]=[]; }
									tempZoneProductionData[0][0][iProd].push([1,iTime,NEVER]);
									if(!tempZoneProductionDataSlot[0][0][iProd]){ tempZoneProductionDataSlot[0][0][iProd]=[]; }
									tempZoneProductionDataSlot[0][0][iProd].push([1,iTime,NEVER]);
								}
							}
							if(iSlotCount>0){
								zoneProductionData[zoneNrS]=tempZoneProductionDataSlot.clone();
								processZoneProductionData(zoneNrS);
							}
						}
					}
					zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
					processZoneProductionData(zoneNrF);
					//auto-cropping
					// if(iSlotCount=0){
					// 	var div;
					// 	if((top.unsafeData.autoAction==null) && valAutoCrop["forestry"] && (zoneEndTimes[zoneNrF]<=unsafeWindow.Zeit.Server) && (div=$("forestry_building_click"+building))){
					// 		top.unsafeData.autoAction="berater: forestry building crop";
					// 		document.addEventListener("gameOpenGlobalCommitBox",function(){
					// 			document.removeEventListener("gameOpenGlobalCommitBox",arguments.callee,false);
					// 			window.setTimeout(function(){ 
					// 				click($("globalcommitboxfooter").firstElementChild);
					// 				top.unsafeData.autoAction=null;
					// 			},500);
					// 		});
					// 		window.setTimeout(function(div){ click(div); },500,div);
					// 	}
					// 	div=null;
					// }
					makeZoneTimers(zoneNrF,"zonetimer","position:absolute;top:-20px;left:0px;",$("food_pos"+building));
				}
			}
			building=null;res=null;iProd=null;iTime=null;maxCapacity=null;zones=null;
		}

		zoneNrF=null;tempZoneProductionData=null;tempZoneProductionDataSlot=null;

		err_trace="saving";
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonus",implode(zoneBonus,"doFoodworld/zoneBonus"));
		unsafeData.zoneBonus=zoneBonus.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock,"doFoodworld/zoneBlock"));
		unsafeData.zoneBlock=zoneBlock.clone();
		publishProductData();
	}catch(err){GM_log("ERROR doFoodworld ("+err_trace+")\n"+err);}
	}
	unsafeWindow._foodworldActionResponse=unsafeWindow.foodworldActionResponse;
	unsafeWindow.foodworldActionResponse=function(request,action,id,table,chair){
		unsafeWindow._foodworldActionResponse(request,action,id,table,chair);
		var result = unsafeWindow._chkRequest(request);
		if((result!=0)&&(result[0]!=0)){
			doFoodworld();
			if ($("food_buildinginner").style.display != "block"){ // raise event only when theres no open building window
				raiseEvent("gameOpenFoodworld");
			} else {
				raiseEvent("gameOpenFoodworld-" + id);
	//   showInLogBubble("gameLocation = " + gameLocation + "id = " + id);
			}			
		}
		result=null;
	}
		
	// Addons
	err_trace="Addons";
	// TODO remove
	document.addEventListener("gameBotStarted",function(){
		try{
			valAutoWater["farm"]=unsafeData.botConfigData[0];
			valAutoCrop["farm"]=unsafeData.botConfigData[1];
			valWaterNeeded["farm"]=unsafeData.botConfigData[2];
			for(var z in unsafeData.readyZone){
				if(!unsafeData.readyZone.hasOwnProperty(z)){continue;}
				unsafeData.readyZone[z][2]=true;
			}
		}catch(err){}
	},false);
	document.addEventListener("gameBotStopped",function(){
		window.setTimeout(function(){
		try{
			valAutoWater=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoWater"),"valAutoWater",{"farm":false,"forestry":true});
			valAutoCrop=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoCrop"),"valAutoCrop",{"farm":false,"forestry":true});
			valWaterNeeded=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valWaterNeeded"),"valWaterNeeded",{"farm":true,"forestry":true});
		}catch(err){}
		},0);
	},false);	
	unsafeWindow.prodMinRackAddon.add = function(type,pid,reason,amount){
	try{
		type=parseInt(type,10);
		pid=parseInt(pid,10);
		amount=parseInt(amount,10);
		if(isNaN(type)||isNaN(pid)||isNaN(amount)){
			GM_log("prodMinRackAddon.add wrong arguments:");
			GM_log([type,pid,reason,amount]);
			return false;
		}
		unsafeWindow.prodMinRackAddon.newdata.push([type,pid,reason,amount]);
		raiseEvent("gameChangedProdMinRackAddon");
	}catch(err){ GM_log("ERROR prodMinRackAddon.add\n"+err); }
	};
	unsafeWindow.prodMinRackAddon.remove = function(type,pid,reason){
	try{
		unsafeWindow.prodMinRackAddon.newdata.push([type,pid,reason,null]);
		raiseEvent("gameChangedProdMinRackAddon");
	}catch(err){ GM_log("ERROR prodMinRackAddon.remove\n"+err); }
	};
	unsafeWindow.prodMinRackAddon.removeAll = function(type,reason){
	try{
		for(var p in prodMinRackAddon[type]){
			if(!prodMinRackAddon[type].hasOwnProperty(p)){ continue; }
			if(prodMinRackAddon[type][p]&&prodMinRackAddon[type][p][reason]){
				unsafeWindow.prodMinRackAddon.newdata.push([type,parseInt(p,10),reason,null]);
			}
		}
		raiseEvent("gameChangedProdMinRackAddon");
	}catch(err){ GM_log("ERROR prodMinRackAddon.removeAll\n"+err); }
	};
	document.addEventListener("gameChangedProdMinRackAddon",function(){
	try{
		// test if calculation is running
		if(unsafeWindow.prodMinRackAddon.busy){ return false; }
		// set flag
		unsafeWindow.prodMinRackAddon.busy=true;
		// get data inside
		var helper=unsafeWindow.prodMinRackAddon.newdata;
		unsafeWindow.prodMinRackAddon.newdata=new Array();
		// calculate
		var type,prod,reason,amount;
		for(var k=0;k<helper.length;k++){
			type  =helper[k][0];
			prod=helper[k][1];
			reason=helper[k][2];
			amount=helper[k][3];
			if(prodMinRackAddon[type][prod]){
				if(prodMinRackAddon[type][prod][reason]){
					if(amount==null){ // delete existing entry
						delete prodMinRackAddon[type][prod][reason];
					}else if(prodMinRackAddon[type][prod][reason]!=amount){ // update existing entry
						prodMinRackAddon[type][prod][reason]=amount;
					} // else the entry is correct
				}else if(amount!=null){
					prodMinRackAddon[type][prod][reason]=amount;
				}
			}else if(amount!=null){ // create new entry
				prodMinRackAddon[type][prod]=new Object();
				prodMinRackAddon[type][prod][reason]=amount;
			} // else a non-existing entry should be deleted
		}
		calcProdMinRack();
		// remove flag
		unsafeWindow.prodMinRackAddon.busy=false;
		// restart if new data meanwhile arrived
		if(unsafeWindow.prodMinRackAddon.newdata.length>0){
			arguments.callee();
		}
	}catch(err){ GM_log("ERROR listener gameChangedProdMinRackAddon\n"+err); }
	},false);

	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_farmname",FARMNAME);
	const DOCTITLE=" - "+FARMNAME+" - s"+SERVER+" - "+document.title;
	var gameLocation=[null,null];
	unsafeData.gameLocation=gameLocation.clone();
	var lastGiess=null;
	var lastErnte=null;
	var aktivAutomat=false;

	var zoneTyp=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneTyp","[]"),"do_main/zoneTyp",[]);
	if(!(zoneTyp instanceof Array)){ zoneTyp = []; }
	/*
		 0: empty
		 1: Field
		 2: Stable  - Chickens
		 3: Stable  - Cows
		 4: Stable  - Sheep
		 5: Stable  - Bees
		 6: Clubhouse
		 7: Factory - Cheese
		 8: Factory - Mayo
		 9: Factory - Whool
		10: Factory - Bonbons
		11: Stable  - Fishs
		12: Stable  - Goats
		13: Factory - Oil
		14: Factory - Special-Oil
	*/
	function isMultiSlotZone(zoneNrF){
	try{
		if(isNaN(zoneNrF)){
			if((zoneNrF=="sawmill")||(zoneNrF=="carpentry")||(zoneNrF=="foodworld-1")||(zoneNrF=="foodworld-2")){
				return true;
			}else{
				return false;
			}
		}else if((zoneTyp[zoneNrF]==13)||(zoneTyp[zoneNrF]==14)){
			return true;
		}else{
			return false;
		}
	}catch(err){ GM_log("ERROR isMultiSlotZone\n"+err);return false; }
	}
	function calcAllSlots(){
	try{
		ALL_SLOTS={};
		for(var i in ALL_ZONES){
			if(!ALL_ZONES.hasOwnProperty(i)){ continue; }
			for(var j=0;j<ALL_ZONES[i].length;j++){
				if(isMultiSlotZone(ALL_ZONES[i][j])){
					for(var slot=1;slot<=3;slot++){
						ALL_SLOTS[ALL_ZONES[i][j]+"."+slot]=i;
					}
				}else{
					ALL_SLOTS[ALL_ZONES[i][j]]=i;
				}
			}
		}
		unsafeData.ALL_SLOTS=ALL_SLOTS.clone();
	}catch(err){ GM_log("ERROR calcAllSlots\n"+err); }
	}
	function getLocation(zoneNr){
	try{
		var zoneNrF=zoneNr.toString().replace(/\.\d+$/g,"");
		if(isNaN(zoneNrF)){
			switch(zoneNrF){
			case "windmill":
				return "windmill";
			break;
			case "forest":case "sawmill":case "carpentry":
				return "forestry";
			break;
			case "foodworld-1":case "foodworld-2":case "foodworld-3":case "foodworld-4":
				return "foodworld";
			break;
			default:
				GM_log("WARNING getLocation returns null\nzoneNr="+zoneNr);
				return null;
			}
		}else{
			return Math.floor((parseInt(zoneNrF,10)-1)/6);
		}
	}catch(err){ GM_log("ERROR getLocation\n"+err);return null; }
	}
	var zoneBlock =explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock","{}"),"do_main/zoneBlock",{});
	if((typeof zoneBlock!="object")||(zoneBlock instanceof Array)){ zoneBlock = new Object(); }
	var bChanged=false;
	for(var i in ALL_ZONES){
		if(!ALL_ZONES.hasOwnProperty(i)){ continue; }
		for(var j=0;j<ALL_ZONES[i].length;j++){
			if((undefined==zoneBlock[ALL_ZONES[i][j]])||(typeof zoneBlock[ALL_ZONES[i][j]]!="string")){
				zoneBlock[ALL_ZONES[i][j]]="blpqs";
				bChanged=true;
			}
		}
	}
	for(var j=0;j<ALL_ZONES["farm"].length;j++){
		// GM_log(ALL_ZONES["farm"][j]+":"+(zoneBlock[ALL_ZONES["farm"][j]])+":"+unsafeWindow.farmamount+":"+Math.ceil(ALL_ZONES["farm"][j]/6));
		if((!zoneBlock[ALL_ZONES["farm"][j]].match(/b/))&&(unsafeWindow.farmamount<Math.ceil(ALL_ZONES["farm"][j]/6))){
			GM_log("zoneBlock farmamount too low: "+ALL_ZONES["farm"][j]);
			zoneBlock[ALL_ZONES["farm"][j]]+="b";
			bChanged=true;
		}
	}
	calcAllSlots();
	for(var i in ALL_SLOTS){
		if(!ALL_SLOTS.hasOwnProperty(i)){ continue; }
		if(undefined==zoneBlock[i]){
				zoneBlock[i]="blpqs";
				bChanged=true;
		}
	}
	if(unsafeWindow.cities&&(unsafeWindow.cities>1)&&zoneBlock["windmill"]){
		zoneBlock["windmill"]="l";
		bChanged=true;
	}
	if(bChanged){ GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock,"do_main/zoneBlock")); }
	var zoneAnimals	=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneAnimals","[]"),"do_main/zoneAnimals",[]);
	if(!(zoneAnimals instanceof Array)){ zoneAnimals = []; }
	var totalAnimals=[,,0,0,0,0,,,,,,0,0];
	for(var i=1;i<ALL_ZONES["farm"].length;i++){
		if(zoneAnimals[ALL_ZONES["farm"][i]]>0){
			totalAnimals[zoneTyp[ALL_ZONES["farm"][i]]] += zoneAnimals[ALL_ZONES["farm"][i]];
		}
	}
	var zoneBonus =explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonus","[]"),"do_main/zoneBonus",{});
	if((typeof zoneBonus != "object")||(zoneBonus instanceof Array)){ zoneBonus = new Object(); }
	var zoneBonusSpecialProduct	=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialProduct","[]"),"do_main/zoneBonusSpecialProduct",[]);
	if(!(zoneBonusSpecialProduct instanceof Array)){ zoneBonusSpecialProduct = []; }
	var zoneBonusSpecialAmount=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialAmount","[]"),"do_main/zoneBonusSpecialAmount",[]);
	if(!(zoneBonusSpecialAmount instanceof Array)){ zoneBonusSpecialAmount = []; }
	function goToFarmZone(zoneNrF){
	try{
		zoneNrF=parseInt(zoneNrF,10);
		var farmNr=Math.floor((zoneNrF-1)/6);
		if((gameLocation[0]=="farm")&&(gameLocation[1]==farmNr)){
			var div=$("zone"+(zoneNrF-6*farmNr));
			if(div){ 
				div=div.querySelector(".bm"+zoneTyp[zoneNrF]); 
				if(div){ click(div); }
			}
			div=null;
		}else{
			var div=$("speedlink_farm"+(1+farmNr));
			if(div){
				document.addEventListener("gameUpdateFarm",function(zoneNrF){
				return function(){
					document.removeEventListener("gameUpdateFarm",arguments.callee,false);
					goToFarmZone(zoneNrF);
				}
				}(zoneNrF),false);
				click(div); 
			}
			div=null;
		}
	}catch(err){GM_log("ERROR goToFarmZone zoneNrF="+zoneNrF+"\n"+err);}
	}

	var zoneEndTimes=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndTimes"),"do_main/zoneEndTimes",{});//TODO name change
	var zoneEndProducts=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndProducts"),"do_main/zoneEndProducts",{}); //TODO name change
	/*
	for(var j=0;j<zoneEndProducts.length;j++){
		if(typeof zoneEndProducts[j] != "number"){
			try{ zoneEndProducts[j] = parseInt(zoneEndProducts[j],10); }
			catch(err){ zoneEndProducts[j] = undefined; }
			if(isNaN(zoneEndProducts[j])){ zoneEndProducts[j] = undefined; }
		}
	}
	*/
	var zoneWaterTimes=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneWaterTimes","{}"),"do_main/zoneWaterTimes",{}); //TODO name change
	var zoneAddToGlobalTime=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobalTimeAdd","{}"),"do_main/zoneAddToGlobalTime",{}); //TODO name change

	var zoneMainprod=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneMainprod"),"do_main/zoneMainprod",{});
	if((typeof zoneMainprod != "object")||(zoneMainprod instanceof Array)){ zoneMainprod = new Object(); }
	/* TODO
	if(!(zoneMainprod instanceof Array)){ zoneMainprod = []; }
	if(zoneMainprod.length>1+ALL_ZONES["farm"].length){ zoneMainprod = zoneMainprod.slice(0,1+ALL_ZONES["farm"].length); }
	for(var j=0;j<zoneMainprod.length;j++){
		if(typeof zoneMainprod[j] != "number"){
			try{ zoneMainprod[j] = parseInt(zoneMainprod[j],10); }
			catch(err){ zoneMainprod[j] = null; }
			if(isNaN(zoneMainprod[j])){ zoneMainprod[j] = null; }
		}
	}
	*/
	//zoneErnte[zoneNr]={"prodId1":[amount1,points1],"prodId2":[amount2,points2],...}
	var zoneErnte=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneErnte"),"do_main/zoneErnte",{}); 
	if((typeof zoneErnte != "object")||(zoneErnte instanceof Array)){ zoneErnte = new Object(); }
	
	function processZoneProductionData(zoneNr){
	try{
		if(DEVMODE_FUNCTION){ GM_log("Begin processZoneProductionData zoneNr="+zoneNr+"\nzoneProductionData="+implode(zoneProductionData[zoneNr],"processZoneProductionData\zoneProductionData["+zoneNr+"]")) }
		// showInLogBubble("processZoneProductionData zoneNr:"+zoneNr+" zoneProductionData:"+implode(zoneProductionData[zoneNr],"processZoneProductionData\zoneProductionData["+zoneNr+"]"));
		var err_trace="begin";
		var nowServer=unsafeWindow.Zeit.Server;
		var iZoneTyp = (isNaN(zoneNr)?(zoneNr.toString().replace(/\.\d+$/g,"")):(zoneTyp[zoneNr]));
		var iGarden=getLocation(zoneNr);
		if(!isNaN(iGarden)){ iGarden="farm"; }
		var zoneErnteCurr=new Object();
		zoneErnte[zoneNr]=new Array();
		zoneEndTimes[zoneNr]=NEVER;
		zoneWaterTimes[zoneNr]=NEVER;
		var c=0,item;
		zoneMainprod[zoneNr]=null;
		zoneEndProducts[zoneNr]=null;
		if(!zoneBlock[zoneNr]){
			err_trace="product loop";
			for(var iType=0;iType<zoneProductionData[zoneNr][0].length;iType++){
				for(var iProdStr in zoneProductionData[zoneNr][0][iType]){
					if(!zoneProductionData[zoneNr][0][iType].hasOwnProperty(iProdStr)){ continue; }
					var iProd = parseInt(iProdStr,10);
					if((prodTyp[iType][iProd]!="u")&&(prodTyp[iType][iProd]!="z")){ // only products
						item=zoneProductionData[zoneNr][0][iType][iProdStr];
						for(var i=0;i<item.length;i++){
							var z=item[i][1];
							var w=item[i][2];
							if (zoneMainprod[zoneNr]==iProd){ c += item[i][0]*prodPlantSize[iType][iProd]; }
							else{ c -= item[i][0]*prodPlantSize[iType][iProd]; }
							if (c<1){
								zoneMainprod[zoneNr]=iProd;
								c=item[i][0]*prodPlantSize[iType][iProd];
							}
	
							if (!zoneErnteCurr[iType]){ zoneErnteCurr[iType]={}; }
							if (!zoneErnteCurr[iType][iProdStr]){ zoneErnteCurr[iType][iProdStr]=[0,0]; }
							if(iType==0){
								// TODO? powerup at EndTime[zoneNr] could be different
								zoneErnteCurr[iType][iProdStr][0] += item[i][0]*(prodYield[iType][iProd]+((currentPowerup[iProdStr]&&(z<currentPowerup[iProdStr][0]))?currentPowerup[iProdStr][1]:0)); 
								zoneErnteCurr[iType][iProdStr][1] += item[i][0]*(iZoneTyp==1?1:prodYield[iType][iProd])*(prodPoints[iType][iProd]+((currentPowerup[iProdStr]&&(z<currentPowerup[iProdStr][0]))?currentPowerup[iProdStr][2]:0));
							}else{
								zoneErnteCurr[iType][iProdStr][0] += item[i][0]*prodYield[iType][iProd];
								zoneErnteCurr[iType][iProdStr][1] += item[i][0]*(iZoneTyp==1?1:prodYield[iType][iProd])*prodPoints[iType][iProd];
							}
	
							if(w){
								zoneWaterTimes[zoneNr]=Math.min(zoneWaterTimes[zoneNr],w);
								if(valAssumeWater[iGarden]&&(zoneBonus[zoneNr]>0)&&(nowServer<=z)&&(w<=z)){
									// calculate future watering
									// w<nowServer means that now can be watered. because it isnt watered, assume that watering is not wanted
									// if (nowServer<=w){
									w=Math.max(0,Math.min(86400,w-nowServer)); // time till watering
									z -= nowServer; // remaining time
									z=nowServer+w+calcGrowDuration(z-w,(100-zoneBonus[zoneNr]-(iProd==zoneBonusSpecialProduct[zoneNr]?zoneBonusSpecialAmount[zoneNr]:0))/100);
								}
							}
	
							if (z < zoneEndTimes[zoneNr]){
								zoneEndTimes[zoneNr]=z;
								zoneEndProducts[zoneNr]=iProd;
							}
						}
					}
				}
			}
			for(var iTypeStr in zoneErnteCurr){
				if(!zoneErnteCurr.hasOwnProperty(iTypeStr)){ continue; }
				for(var iProdStr in zoneErnteCurr[iTypeStr]){
					if(!zoneErnteCurr[iTypeStr].hasOwnProperty(iProdStr)){ continue; }
					zoneErnteCurr[iTypeStr][iProdStr][0] = zoneErnteCurr[iTypeStr][iProdStr][0] / 10; // Fix Seberoth
					zoneErnte[zoneNr].push([parseInt(iTypeStr,10),parseInt(iProdStr,10)].concat(zoneErnteCurr[iTypeStr][iProdStr]));
				}
			}
			// too many empty fields
			err_trace="empty fields";
			if(now<zoneEndTimes[zoneNr]){
				switch(iZoneTyp){
				case "forest":
					if(zoneProductionData[zoneNr][1]>valLimitEmptyFields["forest"]){
						zoneEndTimes[zoneNr]=NEVER;
						zoneEndProducts[zoneNr]=null;
					}
				break;
				case 1:
					if(zoneProductionData[zoneNr][1][1]>valLimitEmptyFields["field"]){
						zoneEndTimes[zoneNr]=NEVER;
						zoneEndProducts[zoneNr]=null;
					}
				break;
				default:
					if(valGlobaltimeShowCroppedZone[iGarden]&&(zoneProductionData[zoneNr][1]>0)){
						zoneEndTimes[zoneNr]=NEVER;
						zoneEndProducts[zoneNr]=null;
					}
				}
			}
		}
		// Check if readyZone is still correct
		err_trace="readyZone";
		if(unsafeData.readyZone[zoneNr]){
			if(zoneEndTimes[zoneNr]==NEVER){
				if(unsafeData.readyZone[zoneNr][1]!="e"){ unsafeData.readyZone[zoneNr][1]="e"; }
				if(!unsafeData.readyZone[zoneNr][2]){ unsafeData.readyZone[zoneNr][2]=true; }
			}else if(zoneEndTimes[zoneNr]<nowServer){
				if(unsafeData.readyZone[zoneNr][1]!="r"){ unsafeData.readyZone[zoneNr][1]="r"; }
				if(!unsafeData.readyZone[zoneNr][2]){ unsafeData.readyZone[zoneNr][2]=true; }
			}else if(valWaterNeeded[iGarden]&&(zoneWaterTimes[zoneNr]<nowServer)){
				if(unsafeData.readyZone[zoneNr][1]!="w"){ unsafeData.readyZone[zoneNr][1]="w"; }
				if(!unsafeData.readyZone[zoneNr][2]){ unsafeData.readyZone[zoneNr][2]=true; }
			}else{
				delete unsafeData.readyZone[zoneNr];
			}
		}
		// Global time
		err_trace="globalTime";
		var zoneNrF;
		zoneEndTimes[0]=NEVER;
		for(var i in ALL_ZONES){
			if(!ALL_ZONES.hasOwnProperty(i)){ continue; }
			for(var j=0;j<ALL_ZONES[i].length;j++){
				try{
					zoneNrF=ALL_ZONES[i][j];
					if((!zoneBlock[zoneNrF])&&(zoneTyp[zoneNrF]!=0)&&((i=="farm")||zoneAddToGlobalTime[zoneNrF])){
						if(zoneEndTimes[zoneNrF]==NEVER){
							if(valGlobaltimeShowCroppedZone[i]){
								zoneEndTimes[0]=-1;
							}
						}else{
							zoneEndTimes[0]=Math.min(zoneEndTimes[0],zoneEndTimes[zoneNrF]);
							if(valWaterNeeded[i]){
								zoneEndTimes[0]=Math.min(zoneEndTimes[0],zoneWaterTimes[zoneNrF]);
							}
						}
					}
				}catch(err){ GM_log("WARNING processZoneProductionData globalTime zoneNr="+zoneNr+"\ni="+i+" j="+j+" zoneNrF="+zoneNrF+"\n"+err); }
			}
		}
		// GM_log("zoneNr="+zoneNr);		
		// GM_log("zoneProductionData="+implode(zoneProductionData[zoneNr]));		
		// GM_log("zoneEndTimes="+implode(zoneEndTimes[zoneNr]));		
		// GM_log("zoneWaterTimes="+implode(zoneWaterTimes[zoneNr]));		
		// GM_log("zoneEndProducts="+implode(zoneEndProducts[zoneNr]));		
		// GM_log("zoneErnte="+implode(zoneErnte[zoneNr]));		
		// GM_log("zoneMainprod="+implode(zoneMainprod[zoneNr]));		
		// saving
		err_trace="saving";
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneProductionData",implode(zoneProductionData,"processZoneProductionData\zoneProductionData"));
		unsafeData.zoneProductionData=zoneProductionData.clone();		
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndTimes",implode(zoneEndTimes,"processZoneProductionData\zoneEndTimes"));
		unsafeData.zoneEndTimes=zoneEndTimes.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneWaterTimes",implode(zoneWaterTimes,"processZoneProductionData\zoneWaterTimes"));
		unsafeData.zoneWaterTimes=zoneWaterTimes.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndProducts",implode(zoneEndProducts,"processZoneProductionData\zoneEndProducts"));
		unsafeData.zoneEndProducts=zoneEndProducts.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneErnte",implode(zoneErnte,"processZoneProductionData\zoneErnte"));
		unsafeData.zoneErnte=zoneErnte.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneMainprod",implode(zoneMainprod,"processZoneProductionData\zoneMainprod"));
		unsafeData.zoneMainprod=zoneMainprod.clone();
		if(DEVMODE_FUNCTION){ GM_log("End processZoneProductionData zoneNr:"+zoneNr);}
	}catch(err){GM_log("ERROR processZoneProductionData ("+err_trace+") zoneNr="+zoneNr+" iProdStr="+iProdStr+" \n"+err);}
	}
	var zoneProductionData=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_zoneProductionData"),"do_main/zoneProductionData",{});
	// zoneProductionData[zoneNr][0][i]={"id":item,...}
	// i = product-type
	// case production : item=[[amount,endtime,nextwatertime],...]
	// - amount : count of productions with these times
	// - endtime : time of cropping (without future waterings)
	// - nextwatertime : NEVER if not possible to water in future
	// case deco : item=[[amount1,time1],[amount2,time2],...]
	// case garbage : item=amount
	// zoneProductionData[zoneNr][1]=[,int,int,,int]||int : free places for currently planting with that size
	// zoneProductionData[zoneNr][2]=[,int,int,,int]||int : free places for possibly planting with that size (cropped field)
	// zoneProductionData[zoneNr][3]=true||false : flag if data is ready
	if((typeof zoneProductionData!="object")||(zoneProductionData instanceof Array)){ zoneProductionData = new Object(); }
	var totalErnte=new Array(new Object(),new Object(),new Object()); // Value of products the farm currently produces
	var totalFarmis=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_totalFarmis","[{},{}]"),"do_main/totalFarmis",[{},{}]); // Value of products the farmis want
	var totalPowerups=new Object(); // Value of powerups creating products
	var totalQuest=new Object(); // Value of products the quests need: totalQuest[questType][prodType][prodId]=amount
	var totalRecursive=new Array(new Object(), new Object());
	//var totalRecursiveThisRun=new Array(new Object(), new Object());
	
	/*
	function findRecursiveNeededProducts(type,iProd,amount,addto){ //addto=new Array(new Object(), new Object());
		if(prodRequire[type]&&prodRequire[type][iProd]){
			//if(DEVMODE_FUNCTION){GM_log("Begin findRecursiveNeededProducts name:"+prodName[type][iProd]+" iProd:"+iProd+" amount:"+amount+" totalRecursive:"+implode(totalRecursive,"findRecursiveNeededProducts\totalRecursive"));}
			var help;
			for(var i in prodRequire[type][iProd]){
				if (!prodRequire[type][iProd].hasOwnProperty(i)){ continue; }
				help=prodRequire[type][iProd][i];
				if (help[0]==type&&help[1]==iProd){continue;}
				pAmount = Math.ceil((parseInt(help[2],10)*amount)/(prodYield[type][iProd]?prodYield[type][iProd]:1));
				if(!addto){
					if(!totalRecursive[help[0]][help[1]]){totalRecursive[help[0]][help[1]]=0;}
					totalRecursive[help[0]][help[1]]+=pAmount;
				}else{
					if(!addto[help[0]][help[1]]){addto[help[0]][help[1]]=0;}
					addto[help[0]][help[1]]+=pAmount;
				}
				if(prodRequire[help[0]][help[1]]){//&&!(help[0]==type&&help[1]==iProd)){
					findRecursiveNeededProducts(help[0],parseInt(help[1],10),pAmount,addto);
				}
			}
			help=null;
			//if(DEVMODE_FUNCTION){GM_log("End findRecursiveNeededProducts name:"+prodName[type][iProd]+" iProd:"+iProd+" amount:"+amount+" totalRecursive:"+implode(totalRecursive,"findRecursiveNeededProducts/totalRecursive"));}
		}
	}
	*/
	function calcRecursiveNeededProducts(recursionCount,type,iProd,amount){
	try{
		if(recursionCount>100){throw("TOO MUCH RECURSION")}
		var returnn=[];
		if(typeof prodRequire[type][iProd]=="object"){
			for(var i=0;i<prodRequire[type][iProd].length;i++){
				returnn.push([prodRequire[type][iProd][i][0],prodRequire[type][iProd][i][1],amount*prodRequire[type][iProd][i][2]]);
				returnn=returnn.concat(calcRecursiveNeededProducts(++recursionCount,prodRequire[type][iProd][i][0],prodRequire[type][iProd][i][1],amount*prodRequire[type][iProd][i][2]));
			}
		}
		return returnn;
	}catch(err){ GM_log("ERROR calcRecursiveNeededProducts\ntype="+type+" iProd="+iProd+" amount="+amount+"\n"+err); }
	}
	function calcTotalRecursive(){
	try{
		if(DEVMODE_FUNCTION){ GM_log("begin calcTotalRecursive"); }
		totalRecursive=new Array(new Object(), new Object());
		var help;
		for(var type in prodMinRack){
			if (!prodMinRack.hasOwnProperty(type)){ continue; }
			for(var iProd in prodMinRack[type]){
				if (!prodMinRack[type].hasOwnProperty(iProd)){ continue; }
				if(prodMinRack[type][iProd]>prodStock[type][iProd]){
					help=calcRecursiveNeededProducts(0,type,iProd,prodMinRack[type][iProd]-prodStock[type][iProd]);
					for(var i=0;i<help.length;i++){
						if(!totalRecursive[help[i][0]][help[i][1]]){totalRecursive[help[i][0]][help[i][1]]=0;}
						totalRecursive[help[i][0]][help[i][1]]+=help[i][2];
					}
				}
			}
		}
		//GM_log("calcTotalRecursive totalRecursive:"+implode(totalRecursive,"calcTotalRecursive\totalRecursive"));
		if(DEVMODE_FUNCTION){ GM_log("end calcTotalRecursive"); }
	}catch(err){ GM_log("ERROR calcTotalRecursive\n"+err); }
	}
 	function calcTotalErnte(){
		try{
			totalErnte=new Array(new Object(),new Object(),new Object(),new Object());
			for(var i in ALL_ZONES){
				if(!ALL_ZONES.hasOwnProperty(i)){ continue; }
				for(var j=0;j<ALL_ZONES[i].length;j++){
					try{
						var zoneNrF=ALL_ZONES[i][j];
						if(zoneErnte[zoneNrF]){
							for(var k=0;k<zoneErnte[zoneNrF].length;k++){
								if(!totalErnte[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]]){ totalErnte[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]]=0; }
								totalErnte[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]] += zoneErnte[zoneNrF][k][2];
							}
						}
					}catch(err){ GM_log("ERROR calcTotalErnte loop\ni="+i+" j="+j+" zoneNrF="+zoneNrF+" zoneErnte="+implode(zoneErnte[zoneNrF])+"\n"+err); }
				}
			}
			//GM_log("calcTotalErnte totalErnte:"+implode(totalErnte));
		}catch(err){ GM_log("ERROR calcTotalErnte\nzoneNrF="+zoneNrF+"\n"+err); }
	}
	function calcTotalFarmis(){
		try{
			totalFarmis[0]=new Object();
			var farmiNr=-1;
			// GM_log("farmisinfo:\n"+print_r(unsafeWindow.farmisinfo,"",true,"\n"));		
			// GM_log("farmilist:\n"+print_r(unsafeWindow.farmilist,"",true,"\n"));		
			if(top.window.wrappedJSObject.farmisinfo&&top.window.wrappedJSObject.farmisinfo[0]){
				for(var farmiNr in top.window.wrappedJSObject.farmisinfo[0]){ // loop through all farmis...
					if(!top.window.wrappedJSObject.farmisinfo[0].hasOwnProperty(farmiNr)){continue;}
					if(top.window.wrappedJSObject.farmilist[farmiNr]==1){ // ...which are waiting...
						// {"id":integer(string),"pic":integer(string),"verkauft":"0","price":float(string),"p1":prod(string),"a1":amount(string),...,"p7":...,"a7":...}
						if(valFarmiLimits[0]<=top.window.wrappedJSObject.farmisinfo[0][farmiNr]["costQuotient"]){ // ...and pay enough
							for(var i=1 ; i <= 7 ; i++){ // 7=max-amount of products per farmi
								var pid=top.window.wrappedJSObject.farmisinfo[0][farmiNr]["p"+i];
								var amount=parseInt(top.window.wrappedJSObject.farmisinfo[0][farmiNr]["a"+i],10);
								if((pid > 0) && (amount > 0)){
									if (totalFarmis[0][pid]) totalFarmis[0][pid] += amount;
									else totalFarmis[0][pid]=amount;
								}
							}
						}
					}
				}
				totalFarmis[0].sortObj();
			}
		}catch(err){GM_log("ERROR calcTotalFarmis \n"+err);}
		//GM_log("calcTotalFarmis totalFarmis:"+implode(totalFarmis[0]));
		//calcProdMinRack(); //TODO possible security error this in wrappedJSObject .. and the calcProMinRack/doBuyNotePad is in unsafeWindow
	}
	function calcTotalPowerups(){
	try{
		totalPowerups=new Object();
		if(unsafeWindow.powerupcontent){
			for(var v=0;v<unsafeWindow.powerupcontent.length;v++){
				if(unsafeWindow.powerupcontent[v][5] && unsafeWindow.powerupcontent[v][5][0]){ //problem in the game made this visible
					var k=parseInt(unsafeWindow.powerupcontent[v][5][0][0],10);
					totalPowerups[k]=parseInt(unsafeWindow.powerupcontent[v]["rack"],10)*parseInt(unsafeWindow.powerupcontent[v][5][0][1],10);
				}
			}
		}
		//GM_log("calcTotalPowerups totalPowerups:"+implode(totalPowerups));
	}catch(err){ GM_log("ERROR calcTotalPowerups\n"+err); }
	}
	calcTotalPowerups();
	function calcTotalQuest(quTyp){
		try{
			// GM_log("calcTotalQuest quTyp="+quTyp);
			totalQuest[quTyp]=new Array(new Object(),new Object());
			var questCurr;
			for(var camp in questData[quTyp]){
				if (!questData[quTyp].hasOwnProperty(camp)){ continue; }
				// GM_log("calcTotalQuest camp="+camp);
				// GM_log("questData["+quTyp+"]["+camp+"]="+implode(questData[quTyp][camp]));
				if(questData[quTyp][camp]["calcTo"]>0){
					questCurr=questData[quTyp][camp]["data"];
					// GM_log("calcTotalQuest questCurr="+implode(questCurr));
					if(questCurr&&questCurr[0]){
						for(var j=0;j<questCurr[0].length;j++){
							if(questCurr[0][j][3]){
								if(!totalQuest[quTyp][questCurr[0][j][0]][questCurr[0][j][1]]){ totalQuest[quTyp][questCurr[0][j][0]][questCurr[0][j][1]]=0; }
								totalQuest[quTyp][questCurr[0][j][0]][questCurr[0][j][1]]+=questCurr[0][j][2];
							}
						}				
					}				
					for(var pTyp in questData[quTyp][camp]["given"]){
						if (!questData[quTyp][camp]["given"].hasOwnProperty(pTyp)){ continue; }
						for(var p in questData[quTyp][camp]["given"][pTyp]){
							if (!questData[quTyp][camp]["given"][pTyp].hasOwnProperty(p)){ continue; }
							if(totalQuest[quTyp][pTyp]&&totalQuest[quTyp][pTyp][p]){
								totalQuest[quTyp][pTyp][p]=Math.max(0,totalQuest[quTyp][pTyp][p]-questData[quTyp][camp]["given"][pTyp][p]);
							}
						}
					}
					for(var q=questData[quTyp][camp]["nr"]+1;q<=questData[quTyp][camp]["calcTo"];q++){
						// GM_log("calcTotalQuest q="+q);
						if(QUESTS[quTyp][camp][q]){
							for(var j=0;j<QUESTS[quTyp][camp][q][0].length;j++){
								questCurr=getQuestBestAlternative(QUESTS[quTyp][camp][q][0][j]);
								if(!totalQuest[quTyp][questCurr[0]][questCurr[1]]){ totalQuest[quTyp][questCurr[0]][questCurr[1]]=0; }
								totalQuest[quTyp][questCurr[0]][questCurr[1]]+=questCurr[2];
							}
						}
					}
				}
			}
			// GM_log("totalQuest["+quTyp+"]="+implode(totalQuest[quTyp]));
		}catch(err){ GM_log("ERROR calcTotalQuest quTyp="+quTyp+" camp="+camp+" q="+q+"\n"+err); }
		// GM_log("calcTotalQuest END");
	}
	// Value of active powerup for a field
	// currentPowerup[plantNr]=[time,+value,+points]
	var currentPowerup=new Object;
	function calcCurrentPowerup(){
	try{
		currentPowerup=new Object;
		if(unsafeWindow.powerupcontent){
			for(var i=0 ; i < unsafeWindow.powerupcontent.length ; i++){
				var item=unsafeWindow.powerupcontent[i];
				if((item[5])&&(item["remain"]>0)){
					if(item[5][1]){
						currentPowerup[item[5][1][0]]=[item["remain"]+unsafeWindow.Zeit.Server,item[5][1][1],0];
						var newdiv=$("powerupSymbol"+item["0"]);
						if(!newdiv){
							newdiv=createElement("div",{"id":"powerupSymbol"+item["0"],"style":"position:relative;width:60px;height:87px;margin-bottom:5px;","end":item["remain"]+unsafeWindow.Zeit.Server},nodes["containerPowerupSymbols"]["node"]);
							newdiv.addEventListener("mouseover",function(event){
								var end=parseInt(this.getAttribute("end"),10);
								var endDay=countDays(now,end);
								showToolTip(event,(texte["day"+endDay]?texte["day"+endDay]:(new Date(1000*end).toLocaleString()))+"<br>"+getDaytimeStr(end));
							},false);
							createElement("img",{"src":GFX+"powerup2.png","border":"0"},newdiv);
							createElement("div",{"style":"position:absolute;top:3px;left:6px;","class":"kp"+item[5][1][0]},newdiv);
							createElement("div",{"style":"position:absolute;top:3px;left:22px;font-weight:bold;color:black;"},newdiv,"+"+item[5][1][1]);
							createElement("div",{"style":"position:absolute;top:64px;right:0;font-weight:bold;","class":"blackbox"},newdiv,getTimeStr(item["remain"]));
						}
						newdiv=null;
					}
					if(item[5][2]){
						currentPowerup[item[5][2][0]]=[item["remain"]+unsafeWindow.Zeit.Server,0,item[5][2][1]];
						var newdiv=$("powerupSymbol"+item["0"]);
						if(!newdiv){
							newdiv=createElement("div",{"id":"powerupSymbol"+item["0"],"style":"position:relative;width:60px;height:87px;margin-bottom:5px;","end":item["remain"]+unsafeWindow.Zeit.Server},nodes["containerPowerupSymbols"]["node"]);
							newdiv.addEventListener("mouseover",function(event){
								var end=parseInt(this.getAttribute("end"),10);
								var endDay=countDays(now,end);
								showToolTip(event,(texte["day"+endDay]?texte["day"+endDay]:(new Date(1000*end).toLocaleString()))+"<br>"+getDaytimeStr(end));
							},false);
							createElement("img",{"src":GFX+"powerup3.png","border":"0"},newdiv);
							createElement("div",{"style":"position:absolute;top:3px;left:6px;","class":"kp"+item[5][2][0]},newdiv);
							createElement("div",{"style":"position:absolute;top:3px;left:22px;font-weight:bold;color:black;"},newdiv,"+"+item[5][2][1]);
							createElement("div",{"style":"position:absolute;top:64px;right:0;font-weight:bold;","class":"blackbox"},newdiv,getTimeStr(item["remain"]));
						}
						newdiv=null;
					}
				}
			}
		}
		unsafeData.currentPowerup=currentPowerup.clone();
	}catch(err){ GM_log("ERROR calcCurrentPowerup\n"+err); }
	}
	calcCurrentPowerup();

	// powerup-data is updated
	unsafeWindow._fillPowerupsResponse=unsafeWindow.fillPowerupsResponse;
	unsafeWindow.fillPowerupsResponse = function(request){
	try{
		unsafeWindow._fillPowerupsResponse(request);
	}catch(err){ GM_log("ERROR _fillPowerupsResponse\n"+err); }
	try{
		var result=checkRequest(request);
		if(result){
			if(!result[1]){ unsafeWindow.powerupcontent=new Array(); }
			calcTotalPowerups();
			updateProductDataPowerup();
			window.setTimeout(saveProductData,0);
			raiseEvent("gamePowerupcontentUpdated");
		}
	}catch(err){ GM_log("ERROR fillPowerupsResponse\n"+err); }
	};

	unsafeWindow._activatePowerup=unsafeWindow.activatePowerup;
	unsafeWindow.activatePowerup = function(formula){
	try{
		unsafeWindow._activatePowerup(formula);
	}catch(err){ GM_log("ERROR _activatePowerup\n"+err); }
	try{
		document.addEventListener("gamePowerupcontentUpdated",function(){
		try{
			calcCurrentPowerup();
			for(var v=1;v<ALL_ZONES["farm"].length;v++){ processZoneProductionData(v); } //TODO
			calcProdMinRack();
			raiseEvent("gamePowerupActivated");
			this.removeEventListener("gamePowerupcontentUpdated",arguments.callee,false);
		}catch(err){ GM_log("ERROR listener gamePowerupcontentUpdated\n"+err); }
		},false);
	}catch(err){ GM_log("ERROR activatePowerup\n"+err); }
	};

	var valAutoWater=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoWater"),"valAutoWater",{"farm":false,"forestry":true}); // TODO set true when automat handles it
	unsafeData.valAutoWater=valAutoWater;
	var valWaterNeeded=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valWaterNeeded"),"valWaterNeeded",{"farm":true,"forestry":true});
	unsafeData.valWaterNeeded=valWaterNeeded;
	var valAssumeWater=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valAssumeWater"),"valAssumeWater",{"farm":true,"forestry":true});
	var valAutoCrop=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoCrop"),"valAutoCrop",{"farm":false,"forestry":true});
	unsafeData.valAutoCrop=valAutoCrop;
	var valErnteMsg=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valErnteMsg",false);
	var valLimitEmptyFields=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valLimitEmptyFields"),"valLimitEmptyFields",{"field":3,"forest":1});
	if(typeof GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit",110)=="number"){ GM_deleteValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit"); }
	var valKauflimit=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit","[[85,'990000'],110]"),"do_main/valKauflimit",[[85,'990000'],110]);
	var valStatistik=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistik",true);
	var valClickErrorbox=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valClickErrorbox",false);
	var valSpoilerZoneUpdate=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valSpoilerZoneUpdate",true);
	var valGlobaltimeShowCroppedZone=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobaltimeShowCroppedZone"),"valGlobaltimeShowCroppedZone",{"farm":true,"windmill":true,"forestry":true});
	if(!valGlobaltimeShowCroppedZone||(typeof valGlobaltimeShowCroppedZone!="object")||(valGlobaltimeShowCroppedZone instanceof Array)){ valGlobaltimeShowCroppedZone={"farm":true,"windmill":true,"forestry":true}; } 
	
	unsafeData.readyZone=new Object;
	unsafeData.zoneEndTimes=zoneEndTimes.clone();
	unsafeData.zoneWaterTimes=zoneWaterTimes.clone();
	unsafeData.zoneEndProducts=zoneEndProducts.clone();
	unsafeData.zoneAddToGlobalTime=zoneAddToGlobalTime.clone();
	unsafeData.zoneAnimals=zoneAnimals.clone();
	unsafeData.zoneBonus=zoneBonus.clone();
	unsafeData.zoneBonusSpecialProduct=zoneBonusSpecialProduct.clone();
	unsafeData.zoneBonusSpecialAmount=zoneBonusSpecialAmount.clone();
	unsafeData.zoneErnte=zoneErnte.clone();
	unsafeData.zoneProductionData=zoneProductionData.clone();
	unsafeData.zoneTyp=zoneTyp.clone();
	unsafeData.zoneBlock=zoneBlock.clone();
	unsafeData.zoneMainprod=zoneMainprod.clone();

	// Werbung
	err_trace="Advertisement";
	var upjersWerbung=new Array();
	for(var v in unsafeWindow.welcomeblurb){
		if(!unsafeWindow.welcomeblurb.hasOwnProperty(v)){ continue; }
		if(v!="1"){
			upjersWerbung.push(unsafeWindow.welcomeblurb[v]);
			delete unsafeWindow.welcomeblurb[v];
		}
	}
	unsafeWindow.gclr();
	newdiv=createElement("img",{"style":"position:absolute;top:0;right:0;height:15px;width:15px;","class":"link","src":GFX+"points.gif"},$("headercontainer"));
	newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["upjersWerbung"]); },false);
	newdiv.addEventListener("click",function(){ buildInfoPanel("upjersWerbung"); },false);
	$("notepad").style.zIndex=111; // Notizen on top
	unsafeWindow.shredderCommit = function(){return;}; // Schredder weg

	// Dragging
	err_trace="Dragging";
	if(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valDrag",false)){
		$("gameArea").style.position="absolute";
		$("gameArea").style.top="5px";
		$("gameArea").style.left="5px";
		makeDraggable($("notepad"));
		makeDraggable($("divGame"),true,false);
		//makeDraggable("gardenmaincontainer");
		//makeDraggable("innermaincontainer");
		$("globaltransp").style.height="0";
		//$("transp").style.height="0";
	}

	// Button-Leiste
	newbutton=createElement("button",{"id":"berateroptionen","type":"button","class":"link2","style":"margin-left:3px;"},$("divSettings"),texte["optionen"]);
	newbutton.addEventListener("click",function(){buildInfoPanel("options");},false);

	// Farmlinks
	err_trace="Farmlinks";
	if(unsafeWindow.premium!=1){
		unsafeWindow.speedLinks = function () { // taken from game-js and modified to run without premium
		try{
			if ( unsafeWindow.tutorial > 0) { // !premium ||
				unsafeWindow.hideDiv("speedlinks")
			} else {
				unsafeWindow.showDiv("speedlinks");
				var a = ["farm1", "farm2", "farm3", "farm4", "city1", "city2", "guild", "forestry", "foodworld"];
				for (var b = 0; b <= a.length; b++) {
					if ($("speedlink_" + a[b])) {
						unsafeWindow.hideDiv($("speedlink_" + a[b]));
						$("speedlink_" + a[b]).className = "speedlink link speedlink_" + a[b];
						$("speedlink_" + a[b]).onclick = new Function("")
					}
				}
				for (var b = 1; b <= unsafeWindow.farmamount; b++) {
					if (unsafeWindow.farm == b) {
						$("speedlink_farm" + b).classList.remove("speedlink_farm" + b);
						$("speedlink_farm" + b).classList.add("speedlink_farm" + b + "_active")
					}
					unsafeWindow.showDiv("speedlink_farm" + b);
					$("speedlink_farm" + b).onclick = new Function("unsafeWindow.farm=" + b + ", unsafeWindow.initZones(" + b + "); unsafeWindow.showMain();")
				}
				for (var b = 1; b <= unsafeWindow.cities; b++) {
					if (unsafeWindow.city == b) {
						$("speedlink_city" + b).classList.remove("speedlink_city" + b);
						$("speedlink_city" + b).classList.add("speedlink_city" + b + "_active")
					}
					unsafeWindow.showDiv("speedlink_city" + b);
					if(unsafeWindow.premium==1){
						$("speedlink_city" + b).onclick = new Function("unsafeWindow.city=" + b + "; unsafeWindow.initCity(" + b + ");")
					}else if(b == 1){
						$("speedlink_city" + b).onclick = new Function("unsafeWindow.initCity(" + b + ");")
					}else{
						$("speedlink_city" + b).onclick = new Function("unsafeWindow.travel2City2();")
					}
				}
				if (unsafeWindow.player_guild) {
					if (unsafeWindow.inguild) {
						$("speedlink_guild").classList.remove("speedlink_guild");
						$("speedlink_guild").classList.add("speedlink_guild_active")
					}
					unsafeWindow.showDiv("speedlink_guild");
					$("speedlink_guild").onclick = new Function("unsafeWindow.inguild=1; unsafeWindow.showMain(); unsafeWindow.initZones(1); unsafeWindow.initGuild();")
				}
				if (unsafeWindow.forestry_unlock == 1) {
					if (unsafeWindow.forestry_quicknavi) {
						$("speedlink_forestry").classList.remove("speedlink_forestry");
						$("speedlink_forestry").classList.add("speedlink_forestry_active")
					}
					unsafeWindow.showDiv("speedlink_forestry");
					$("speedlink_forestry").onclick = new Function("unsafeWindow.farm=0; unsafeWindow.city=0; unsafeWindow.forestry_quicknavi=1; unsafeWindow.initForestry();")
				}
				if (unsafeWindow.currentuserlevel >= 11) {
					if (unsafeWindow.foodworld_quicknavi) {
						$("speedlink_foodworld").classList.remove("speedlink_foodworld");
						$("speedlink_foodworld").classList.add("speedlink_foodworld_active")
					}
					unsafeWindow.showDiv("speedlink_foodworld");
					if(unsafeWindow.premium==1){
						$("speedlink_foodworld").onclick = new Function("unsafeWindow.farm=0; unsafeWindow.city=0; unsafeWindow.foodworld_quicknavi=1; unsafeWindow.foodworldAction('init');");
					}else{
						$("speedlink_foodworld").onclick = new Function("unsafeWindow.travel2picknick();")
					}
				}
			}
		}catch(err){ GM_log("ERROR speedLinks\nfarm="+unsafeWindow.farm+"\n"+err); }
		}
		unsafeWindow.speedLinks();
		/*
		unsafeWindow.createFarmLinks = function (){
		try{
			var err_trace=1;
			var content='';
			for(var i=1 ; i <= unsafeWindow.farmamount; i++)
			{
				var useid='farmlinkitem';
				if(unsafeWindow.farm == i){
					useid='farmlinkitemactivate';
				}
				var onclick='initZones(' + i + '); showMain();';
				if(unsafeWindow.forestry_unlock==undefined){
					content += '<div class="link" id="' + useid + '" onclick="' + onclick + '" ';
				}else{
					content += '<div class="link ' + useid + '" id="quicknavifarm' + i + '" onclick="' + onclick + '" ';
				}
				content += 'onmouseover="showDiv(\'farmtooltip' + i + '\');" onmouseout="hideDiv(\'farmtooltip' + i + '\');">';
				content += i;
				content += '<div id="farmtooltip' + i + '" onmouseover="showDiv(\'farmtooltip' + i + '\');" onmouseout="hideDiv(\'farmtooltip' + i + '\');">' + unsafeWindow.farmname + i + '</div>';
				content += '</div>';
			}
	
			err_trace=2;
			if(unsafeWindow.forestry_unlock!=undefined){
				content += '<div id="quicknavifarmforestry" class="link" style="float:left; background:url(' + GFX + ')forestrylink.png) top left no-repeat; width:40px; height:29px; margin-left:5px;" ';
				content += 'onclick="initForestry()" onmouseover="showDiv(\'forestrytooltip\');" onmouseout="hideDiv(\'forestrytooltip\');">';
				content += '<div id="forestrytooltip">' + unsafeWindow.cityzone_quicknavi + '</div>';
				content += '</div>';
			}
	
			content += '<div style="clear:both;"></div>';

			err_trace=3;
			$("farmlinks").innerHTML=content;
	
			err_trace=4;
			if(unsafeWindow.forestry_unlock!=undefined){
				if(unsafeWindow.forestry_quicknavi == 1){
					for(var i = 1 ; i <= unsafeWindow.farmamount ; i++){
						if($('quicknavifarm' + i)) $('quicknavifarm' + i).className = 'link farmlinkitem';
					}
					if($('quicknavifarmforestry')) $('quicknavifarmforestry').style.background = 'url(' + GFX + 'forestryactivate.png) no-repeat';
				}else{
					if($('quicknavifarmforestry')) $('quicknavifarmforestry').style.background = 'url(' + GFX + 'forestrylink.png) no-repeat';  // hier forestry deaktivieren
				}
				if(unsafeWindow.forestry_unlock){
					unsafeWindow.showDiv('quicknavifarmforestry');
				}else{
					unsafeWindow.hideDiv('quicknavifarmforestry');
				}
			}
		}catch(err){ GM_log("ERROR CreateFarmLinks ("+err_trace+")\nfarm="+unsafeWindow.farm+"\n"+err); }
		};
		unsafeWindow.createFarmLinks();
		unsafeWindow.createGuildLinks = function(){
			if(unsafeWindow.userfarminfos[unsafeWindow.farm]){
				if(unsafeWindow.userfarminfos[unsafeWindow.farm]['guild'] > 0){
					if(unsafeWindow.farm == 1){
						unsafeWindow.showDiv('guildbicycle');
						if(unsafeWindow.userfarminfos[unsafeWindow.farm]['guildquest']){
							var questaniimg='guildpassagequestani.gif';
							$('guildpassagequestani').style.backgroundImage='url(' + GFX + questaniimg + ')';
							unsafeWindow.showDiv('guildpassagequestani');
						}else{
							unsafeWindow.hideDiv('guildpassagequestani');
						}
					}else{
						unsafeWindow.hideDiv('guildbicycle');
						unsafeWindow.hideDiv('guildpassagequestani');
					}
					if(unsafeWindow.inguild == 1) $('guildlink').style.backgroundImage="url(" + GFX + "guildlink.png)";
					else $('guildlink').style.backgroundImage="url(" + GFX + "guildlink_off.png)";
					unsafeWindow.showDiv('guildlink');
				}else{
					unsafeWindow.hideDiv('guildbicycle');
					unsafeWindow.hideDiv('guildlink');
					unsafeWindow.hideDiv('guildpassagequestani');
				}
			}
		};
		unsafeWindow.createGuildLinks();
		unsafeWindow.createCityLinks = function (){
			var content='';
			for(var i=1 ; i <= unsafeWindow.cities ; i++)
			{
				var onclick='initCity(' + i + ');';
				var bgimage='citylink.png';
				if(i == unsafeWindow.city) bgimage='citylinkactivate.png';
				var name=unsafeWindow.cityname1;
				if(i == 2){
					name=unsafeWindow.cityname2;
					if(unsafeWindow.premium!=1) onclick='travel2City2();';
				}
	
				content += '<div class="link" id="citylineitem' + i + '" style="background:url(' + GFX + bgimage + ') left top no-repeat;" ';
				content += 'onclick="' + onclick + '" onmouseover="showDiv(\'citytooltip' + i + '\');" onmouseout="hideDiv(\'citytooltip' + i + '\');">';
				content += i;
				content += '<div id="citytooltip' + i + '" onmouseover="showDiv(\'citytooltip' + i + '\');" onmouseout="hideDiv(\'citytooltip' + i + '\');">' + name + '</div>';
				content += '</div>';
			}
			content += '<div style="clear:both;"></div>';
			$('cityline').innerHTML=content;
			if(unsafeWindow.forestry_unlock!=undefined){
				if(unsafeWindow.forestry_quicknavi == 1){
					for(var i = 1 ; i <= unsafeWindow.cities ; i++){
						if($('citylineitem' + i)) $('citylineitem' + i).style.background = 'url(' + GFX + 'citylink.png) no-repeat';
					}
				}
				if(unsafeWindow.forestry_unlock){
					unsafeWindow.showDiv('quicknavifarmforestry');
				}else{
					unsafeWindow.hideDiv('quicknavifarmforestry');
				}
			}
		};
		unsafeWindow.createCityLinks();
		*/
		unsafeWindow.travel2City2 = function(){
			switch(unsafeWindow.city){
				case 2:
				case 1: unsafeWindow.initCity(2); break;
				default: {
					document.addEventListener("gameCity1",function(){
						unsafeWindow.initCity(2);
						document.removeEventListener("gameCity1",arguments.callee,false);
					},false);
					unsafeWindow.initCity(1);
				}
			}
		};
		unsafeWindow.travel2picknick = function(){
			switch(unsafeWindow.city){
				case 2: unsafeWindow.foodworldAction('init'); break;
				case 1: 
					document.addEventListener("gameCity2",function(){
						unsafeWindow.foodworldAction('init');
						document.removeEventListener("gameCity2",arguments.callee,false);
					},false);
					unsafeWindow.initCity(2);
					break;
				default: {
					document.addEventListener("gameCity1",function(){
						unsafeWindow.initCity(2);
						document.removeEventListener("gameCity1",arguments.callee,false);
					},false);
					document.addEventListener("gameCity2",function(){
						unsafeWindow.foodworldAction('init');
						document.removeEventListener("gameCity2",arguments.callee,false);
					},false);
					unsafeWindow.initCity(1);
				}
			}
		};			
	}
	// andere ServerAccounts
	err_trace="Other accounts on server";
	var farmNamen=explode(GM_getValue(LNG+"_"+SERVER+"_farmNamen","{}"),"do_main/farmNamen",{});
	farmNamen[USERNAME]=FARMNAME;
	if(farmNamen[USERNAME].toLowerCase()!=USERNAME){
		newdiv=createElement("div",{"class":"userinfositem link","style":"font-weight: bold;"});
		newdiv.innerHTML="("+USERNAME+")";
		newdiv1=$("userinfoscontainer");
		newdiv1.insertBefore(newdiv,newdiv1.children[1]);
	}
	GM_setValue(LNG+"_"+SERVER+"_farmNamen",implode(farmNamen));

	var otherAccs=new Array();
	var min=[NEVER,];
	try{
		var help=explode(GM_getValue("logindata","[]"),"do_main/logindata",[]);
		for(var v=0;v<help.length;v++){
			help[v][3]=v;
			if((help[v][4]) && (help[v][0]==LNG) && (help[v][1]==SERVER)){
				if(help[v][2].toLowerCase()==USERNAME){
					help[v][3]=-1; // this account
				}else{
					try{
						help[v][5]=explode(GM_getValue(help[v][0]+"_"+help[v][1]+"_"+help[v][2].toLowerCase()+"_zoneEndTimes"),"do_main/[2]/zoneEndTimes")[0];
					}catch(err){
						help[v][5]=NEVER;
					}
					if(help[v][5]<min[0]){
						min[0]=help[v][5];
						min[1]=v;
					}
				}
				otherAccs.push(help[v]);
			}
			if(!farmNamen[help[v][2]]){ farmNamen[help[v][2]]=help[v][2]; }
		}
	}catch(err){}

	function testOtherAccReady(){
	try{
		var found=-1;
		for(var v=0;v<otherAccs.length;v++){ if(otherAccs[v][3]>-1){
			if (otherAccs[v][5]+unsafeWindow.Zeit.Verschiebung<now){
				found=v;
				break;
			}
		}}
		if(found>-1){
			var cell=$("bubble_adtext");
			if(!cell){ cell=$("sprcontent"); }
			cell.innerHTML="";
			cell=createElement("a",{"id":"linkOtherAccReady","class":"link","dologin":otherAccs[found][3],"href":"#","style":"font-weight:bold;"},createElement("div",{"style":"height:50px;"},cell),farmNamen[otherAccs[found][2]]+" "+texte["fertig"].toLowerCase()+"!");
			cell.addEventListener("click",function(){
			try{
				var dologin=parseInt(this.getAttribute("dologin"),10);
				window.setTimeout(function(dologin){
				try{
					var help=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"testOtherAccReady/pagedataLogin",{});
					if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
						help["dologin"]=new Object();
					}
					help["dologin"][dologin]=true;
					GM_setValue(LNG+"_pagedataLogin",implode(help));
					if($("logoutbutton")){
						click($("logoutbutton"));
					} else {
						location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
					}
				}catch(err){ GM_log("ERROR listener linkOtherAccReady.click\n"+err); }
				},0,dologin);
			}catch(err){ GM_log("ERROR listener linkOtherAccReady.click\n"+err); }
			},false);
			cell=null;
			raiseEvent("gameOtherAccReady");
		}else{
			window.setTimeout(testOtherAccReady,5000);
		}
	}catch(err){ GM_log("ERROR testOtherAccReady\n"+err); }
	}
	if (otherAccs.length>1){
		newdiv=createElement("div",{"id":"divOtherAccountsTimes","class":"blackbox","style":"position:absolute;top:5px;right:150px;border:2px solid black;padding:2px;z-index:300;display:none;"},$("headercontainer"));
		newdiv.addEventListener("mouseout",function(){this.style.display="none";},false);
		newdiv.addEventListener("mouseover",function(){this.style.display="";},false);
		newdiv=createElement("div",{"style":"position:absolute;top:4px;right:220px;font-size:11px;color:#f7bb87;","class":"link"},$("headercontainer"));
		createElement("div",{"style":"display:inline-block;margin-bottom:2px;margin-right:2px;text-decoration:underline;vertical-align:top;font-size:11px;"},newdiv,texte["umloggen"]);
		newdiv1=createElement("div",{"style":"display:inline-block;"},newdiv);
		createElement("img",{"border":"0","src":GFX+"menu/logout.gif"},newdiv1);
		newdiv.addEventListener("mouseout",function(){$("divOtherAccountsTimes").style.display="none";},false);
		function fillDivOtherAccountsTimes(){
			divOtherAccountsTimes=$("divOtherAccountsTimes");
			if(divOtherAccountsTimes.style.display=="none"){
				divOtherAccountsTimes.innerHTML="";
			}else{
				var newtable=createElement("table",{},newdiv);
				var newtr;
				for(var v=0;v<otherAccs.length;v++){
					if(otherAccs[v][3]>-1){
						newtr=createElement("tr",{"class":"link hoverBgCc9","dologin":otherAccs[v][3]},newtable);
						newtr.addEventListener("click",function(){
							var dologin=parseInt(this.getAttribute("dologin"),10);
							window.setTimeout(function(dologin){
								var help=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"fillDivOtherAccountsTimes/pagedataLogin",{});
								if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
									help["dologin"]=new Object();
								}
								help["dologin"][dologin]=true;
								GM_setValue(LNG+"_pagedataLogin",implode(help));
								if($("logoutbutton")){
									click($("logoutbutton"));
								} else {
									location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
								}
							},0,dologin);
						},false);
					}else{
						newtr=createElement("tr",{"class":"fontWeightBold"},newtable);
						otherAccs[v][5]=zoneEndTimes[0];
					}
					createElement("td",{},newtr,farmNamen[otherAccs[v][2]]);
					var help=unsafeWindow.Zeit.Verschiebung+otherAccs[v][5];
					if (help>now){ createElement("td",{},newtr,getTimeStr(help-now)); }
					else{ createElement("td",{},newtr,texte["fertig"].toLowerCase()+"!"); }
				}
				divOtherAccountsTimes.innerHTML="";
				divOtherAccountsTimes.appendChild(newtable);
				newtable=null;newtr=null;
				window.setTimeout(fillDivOtherAccountsTimes,1000);
			}
			divOtherAccountsTimes=null;
		}
		newdiv.addEventListener("mouseover",function(){
			$("divOtherAccountsTimes").style.display="";
			fillDivOtherAccountsTimes();
		},false);
		if(min[0]<NEVER){
			window.setTimeout(testOtherAccReady,Math.max(0,min[0]+unsafeWindow.Zeit.Verschiebung-now));
		}
	}

	// SessionEnd
	err_trace="SessionEnd";
	//window.setTimeout('top.location.href="main.php?page=logout";','4457000');  in the gamepage
	function timerSessionEnd(sec){
	try{
		if(sec<1){
			var help=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"timerSessionEnd/pagedataLogin",{});
			if(!(help["doserver"]&&(typeof help["doserver"]=="object"))){
				help["doserver"]=new Object();
			}
			help["doserver"][SERVER]=true;
			GM_setValue(LNG+"_pagedataLogin",implode(help));
			if($("logoutbutton")){
				click($("logoutbutton"));
			} else {
				location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
			}
		}else{
			window.setTimeout(function(){ timerSessionEnd(sec-1); },1000);
			$("divSessionEndTime").innerHTML=getTimeStr(sec);
		}
	}catch(err){ GM_log("ERROR timerSessionEnd\n"+err); }
	}
	var valSessionEndtime=null;
	if (unsafeWindow.logout_remain){
		valSessionEndtime=Math.floor(now+unsafeWindow.logout_remain);
		window.setTimeout(function(){
			var newdiv=createElement("div",{"id":"divSessionEnd","class":"alertbubble tbig link"},ALL,texte["relogin"].replace(/%1%/,"<span id='divSessionEndTime'>0</span>"));
			newdiv.addEventListener("click",do_relogin,false);
			timerSessionEnd(Math.max(0,valSessionEndtime-now-30));
			newdiv=null;
			raiseEvent("gameSessionEnds");
		},Math.max(1,1000*unsafeWindow.logout_remain-getRandom(600000,1800000)));
	}

	// Statistik
	err_trace="Statistic";
	if (STAT_SERVER[LNG]){
		function buildStatistik(mode){
		try{
			loadProductData();
			updateProductDataFarm();//TODO check correct call
			var container=$("divStatistik");
			container.innerHTML="";

			// Header
			var newdiv=createElement("div",{"style":"width:100%;margin-bottom:3px;border:2px solid black;color:black;background-color:#ccf;"},container);
			var newselect=createElement("select",{"class":"link","style":"margin-right:20px;"},newdiv);
			createElement("option",{"value":"24"},newselect,texte["stat_days1"]);
			createElement("option",{"value":"72"},newselect,texte["stat_days3"]);
			createElement("option",{"value":"120"},newselect,texte["stat_days5"]);
			createElement("option",{"value":"168"},newselect,texte["stat_days7"]);
			var valStatistikTime=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikTime",120);
			newselect.value=valStatistikTime;
			newselect.addEventListener("change",function(){
				GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikTime",parseInt(this.value,10),6);
				buildStatistik(mode);
			},false);

			var valStatistikNpc=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikNpc",true);
			var newbutton=createElement("input",{"type":"checkbox","class":"link","checked":valStatistikNpc},newdiv);
			newbutton.addEventListener("click",function(){
				GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistikNpc",this.checked,7);
				buildStatistik(mode);
			},false);
			createElement("span",{"style":"margin-right:20px;"},newdiv,texte["NPC"]);

			var help={};
			for (var v=0;v<prodBlock[0].length;v++){
				if((!prodBlock[0][v].match(/t/))&&(!prodBlock[0][v].match(/l/))){
					help[prodTyp[0][v]]=true;
				}
			}
			for(var v in help){
				if(!help.hasOwnProperty(v)){ continue; }
				newbutton=createElement("button",{"type":"button","class":"link2","style":"width:150px","name":v},newdiv,texte["category"][v]);
				newbutton.addEventListener("click",function(){ buildStatistik(this.getAttribute("name")); },false);
				if (mode==v){ newbutton.style.backgroundColor="lightblue";}
			}

			// Body
			newdiv=createElement("div",{"style":"width:100%;height:"+(window.innerHeight-70-upjersToolbarHeight)+"px;overflow-y:auto;overflow-x:hidden;border:2px solid black;color:black;background-color:#ccf;"},container);
			if (mode!=""){
				var newdiv1,newimg,newobject;
				for(var v in prodName[0]){
					if(!prodName[0].hasOwnProperty(v)){ continue; }
					if ((prodTyp[0][v]==mode)&&(!prodBlock[0][v].match(/t/))&&(!prodBlock[0][v].match(/l/))){
						newdiv1=createElement("div",{"id":"stat"+v,"class":"link","style":"position:relative;float:left;height:214px;margin:5px;background-color:#bbe;"},newdiv);
						createElement("div",{"style":"height:14px;font-weight:bold;"},newdiv1,prodName[0][v]+", "+numberFormat(prodStock[0][v],0)+", "+moneyFormat(gut[v])+", "+moneyFormat(gutBeob[v]));
						var url="http://www."+STAT_SERVER[LNG]+"/chart.php?w=400&h=200&t=h"+valStatistikTime+"&shownpc="+(valStatistikNpc?1:0)+"&clip=1&lng1="+LNG+"&server1="+SERVER+"&product1="+v+"&color1=green";
						newobject=createElement("object",{"data":url,"type":"type=image/svg+xml","width":"400px","height":"200px"},newdiv1);
						createElement("param",{"name":"src","value":url},newobject);
						createElement("div",{"class":"v"+v,"style":"position:absolute;bottom:10px;left:10px;z-index:2;"},newdiv1);
						createElement("div",{"style":"position:absolute;top:0;left:0;width:100%;height:100%;z-index:2;"},newdiv1);
						newdiv1.addEventListener("click",function(){
							//buildStatistik(this.id.replace("stat",""));
							showStatisticFullscreen(this.id.replace("stat",""));
						},false);
					}
				}
				/*
				if (isNaN(mode)){
				}else{
					newdiv1=createElement("div",{"style":"margin:5px;"},newdiv);
					createElement("div",{"style":"font-weight:bold"},newdiv1,prodName[0][mode]+", "+numberFormat(prodStock[0][mode],0)+", "+moneyFormat(gut[mode])+", "+moneyFormat(gutBeob[mode]));
					var breit=(window.innerWidth-60);
					var hoch=(window.innerHeight-130);
					var url="http://www."+STAT_SERVER[LNG]+"/chart.php?w="+breit+"&h="+hoch+"&t=h"+time+"&shownpc="+(valStatistikNpc?1:0)+"&clip=1&lng1="+LNG+"&server1="+SERVER+"&product1="+mode+"&color1=green";
					newobject=createElement("object",{data:url,"type":type="image/svg+xml","width":breit+"px","height":hoch+"px"},newdiv1);
					createElement("param",{"name":"src","value":url},newobject);
					createElement("div",{"class":"v"+mode,"style":"position:relative;top:-40px;left:10px;z-index:2"},newdiv1);
				}
				*/
				newdiv1=null;newimg=null;newobject=null;
			}
			container=null;newdiv=null;newselect=null;newselect=null;newbutton=null;
		}catch(err){ GM_log("ERROR buildStatistik\nmode="+mode+"\n"+err); }
		}
		function sendStatData (){
		try{
			var prodStr="";
			var preisBeob=explode(GM_getValue(LNG+"_"+SERVER+"_preisBeob","[]"),"sendStatData/preisBeob",[]); //isNotSent,time,min,max,amount
			var bChanged=false;
			if(!(preisBeob instanceof Array)){
				preisBeob=new Array();
				bChanged=true;
			}
			gutBeob=explode(GM_getValue(LNG+"_"+SERVER+"_gutBeob","[]"),"sendStatData/gutBeob",[]);
			var c=0;
			var neededTime=now-300; // Data max 5min old
			for(var v=0;v<preisBeob.length;v++){
				if(preisBeob[v] && preisBeob[v][0] && (neededTime<preisBeob[v][1]) && (0<preisBeob[v][2]) && (preisBeob[v][2]<=gutBeob[v]) && (gutBeob[v]<=preisBeob[v][3])){
					prodStr += ',\"product'+(++c)+'\":{\"product_id\":'+v+',\"avg_price\":'+gutBeob[v]+',\"min_price\":'+preisBeob[v][2]+',\"max_price\":'+preisBeob[v][3]+'}';
					preisBeob[v][0]=false;
					bChanged=true;
				}
			}
			if(bChanged){
				GM_setValue2(LNG+"_"+SERVER+"_preisBeob",implode(preisBeob),8);
				raiseEventTop("gameChangedBeobPrice");
			}

			if (c>0){
				showInLogBubble("sendStatData: sending "+c+" observed prices to server");
				//GM_log("sendStatData sending: " + 'json={\"server\":'+SERVER+',\"lng\":'+LNG+',\"productcount\":'+c+prodStr+'}')
				GM_xmlhttpRequest({
				method: "POST",
				url: "http://www."+STAT_SERVER[LNG]+"/add.php",
				data: 'json={\"server\":'+SERVER+',\"lng\":\"'+LNG+'\",\"productcount\":'+c+prodStr+'}',
				headers: {
					"Content-Type": "application/x-www-form-urlencoded"
				},
				onload: function(response){
					showInLogBubble("sendStatData: "+response.responseText);
				}
				});
			}
		}catch(err){ GM_log("ERROR sendStatData\n"+err); }
		}
		if(STAT_VIEW && STAT_VIEW[LNG]){
			newbutton=createElement("button",{"type":"button","class":"link2","style":"margin-left:3px;"},$("divSettings"),texte["stat_stats"]);
			newbutton.addEventListener("click",function(){
				if ($("divGame").style.display==""){
					$("divGame").style.display="none";
					$("divStatistik").style.display="";
					this.innerHTML=texte["stat_gamefield"];
					buildStatistik("");
				}else{
					$("divGame").style.display="";
					$("divStatistik").style.display="none";
					this.innerHTML=texte["stat_stats"];
				}
			},false);
		}
		if (valStatistik && STAT_SERVER && STAT_SERVER[LNG]){
			sendStatData();
			window.setInterval(function (){
				sendStatData();
			},310000);
		}
	}
	
	err_trace="Rack bottom";
	if(newdiv=$("canvassracklink")){
		newdiv.style.height = "55px";
	}
	if(newdiv=$("forumracklink")){
		newdiv.style.height = "55px";
	}
	if(newdiv=$("rackBottom")){
		// Spieler suchen
		newinput=createElement("input",{"value":texte["spielerSuchen"],"class":"text","style":"position:absolute;top:60px;left:125px;width:85px;background:transparent;border:1px solid black;"},newdiv);
		newinput.addEventListener("click",function(){this.value="";},false);
		newinput.addEventListener("blur",function(){this.value=texte["spielerSuchen"];},false);
		newinput.addEventListener("keyup",function(event){
			try{
				if (event.keyCode==13){
					showShopframePage("http://s"+SERVER+"."+GAMEPAGES[LNG]+"/stadt/stats.php?search=1&searchterm="+this.value);
				}
			}catch(err){ GM_log("ERROR listener searchPlayer.keyup\n"+err); }
		},false);
		// Farmpedia
		newinput=createElement("a",{"href":texte["farmpediaUrl"],"target":"_blank","style":"position:absolute;top:55px;left:100px;z-index:2;","class":"link"},newdiv);
		createElement("img",{"style":"width:25px;height:25px;border:none;","src":GFX+"points.gif"},newinput);
		newinput.addEventListener("mouseover",function(event){ showToolTip(event,texte["zurFarmpedia"]); },false);
	}

	// InfoPanel
	err_trace="InfoPanel";
	newdiv=createElement("div",{"id":"infoPanel","mode":"","style":"position:absolute;top:50px;left:20px;width:660px;height:580px;background-color:#b8a789;z-index:100;display:none;"},$("garten_komplett"));
	createElement("img",{"src":GFX+"guild/help_back.jpg","style":"position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;"},newdiv);
	createElement("div",{"id":"infoPanelInner","class":"tnormal","style":"position:absolute;width:90%;height:89%;margin:5%;overflow:auto;"},newdiv);
	var newimg=createElement("img",{"id":"infoPanelClose","class":"link","src":GFX+"close.jpg","style":"position:absolute;top:8px;right:8px;width:20px;height:20px;"},newdiv);
	newimg.addEventListener("click",closeInfoPanel,false);
	if ($("farmlinks")) $("farmlinks").addEventListener("click",closeInfoPanel,false);
	if ($("cityline")) $("cityline").addEventListener("click",closeInfoPanel,false);
	function buildInfoPanel(mode,mode2){
	try{
		if(typeof mode2=="undefined"){ mode2=""; }
		var newdiv=$("infoPanel");
		if((newdiv.style.zIndex=="101")&&(mode==newdiv.getAttribute("mode"))&&(implode(mode2)==newdiv.getAttribute("mode2"))){
			closeInfoPanel();
		}else{
			loadProductData();
			updateProductDataFarm();//TODO check correct call
			var newtable,newthead,newtbody,newtfoot,newtr,newtd,newtd1,newdiv1,newinput;

			newdiv.setAttribute("mode",mode);
			newdiv.setAttribute("mode2",implode(mode2));
			newdiv.style.display="block";
			newdiv.style.zIndex="101";

			infoPanelInner=$("infoPanelInner");
			infoPanelInner.innerHTML="";
			infoPanelInner.style.width="595px"; //~90%
			infoPanelInner.style.background="";

			$("multiframe").style.zIndex="99";
			$("transp100").style.display="block";
			//$("transp").style.display="block";
			//newdiv=$("transp3");
			//newdiv.style.display="block";
			//newdiv.style.visibility="visible";

			switch(mode){
			case "level":{
				newdiv=createElement("div",{"style":"height:400px;overflow:auto;color:black;"},infoPanelInner);
				//todayStr=getDateStr(now,2,false);
				if(levelLog[todayServerStr]==undefined){ levelLog[todayServerStr]=[0,null,0,0,0]; }
				levelLog[todayServerStr][0]=parseInt($("pkt").innerHTML.replace(/\D/g,""),10);
				var totalumsatz=[0,0,[0,0]];

				newtable=createElement("table",{"border":"1"},newdiv); //scrollTable
				newthead=createElement("thead",{},newtable);
				newtbody=createElement("tbody",{"class":"hoverRowBgCc9","style":"height:348px;"},newtable);
				newtfoot=createElement("tfoot",{},newtable);

				newtr=createElement("tr",{"class":"borderBottom2"},newthead);
				createElement("th",{"class":"link","sortdir":"Asc","style":"border-right:2px solid black;"},newtr,texte["tag"]);
				createElement("th",{"class":"link","sortdir":"Asc"},newtr,texte["punkte"]);
				createElement("th",{"class":"link","sortdir":"Asc"},newtr,"+");
				createElement("th",{"class":"link","sortdir":"Asc","style":"border-right:2px solid black;"},newtr,texte["platz"]);
				createElement("th",{"class":"link","sortdir":"Asc"},newtr,texte["markt"]);
				createElement("th",{"class":"link","sortdir":"Asc"},newtr,texte["vertrag"]);
				createElement("th",{"class":"link","sortdir":"Asc"},newtr,unsafeWindow.customerarecalled.replace(/%FARMI%/,""));
				new SortableTable(newtr);

				var firstDay=null;
				var secondDay=null;
				var prevDay=null;
				for(var v in levelLog){
					if(!levelLog.hasOwnProperty(v)){ continue; }
					if(firstDay==null){
						firstDay=v;
					}else if(secondDay==null){
						secondDay=v;
					}
					if(v.match(/^\d+\.\d+$/)){
						var day=("1."+v).split(/\./);
						var days=(new Date(parseInt(day[2],10),parseInt(day[2],10),0)).getDate();
					}else{
						var day=v.split(/\./);
						var days=1;
						if(levelLog[v.replace(/^(\d+\.)/,"")]!=undefined){ days=0; } // doubling with month-entry
					}

					newtr=createElement("tr",{"align":"right"},newtbody);

					// Sundays
					if ((new Date(parseInt(day[2],10),parseInt(day[1],10)-1,parseInt(day[0],10)).getDay())==0){
						newtr.setAttribute("class","borderBottom2");
					}

					createElement("td",{"value":levelLog[v][0],"style":"text-align:right;border-right:2px solid black;"},newtr,v==todayStr?texte["day0"]:v);
					createElement("td",{"value":levelLog[v][0]},newtr,numberFormat(levelLog[v][0]));
					if(prevDay==null){
						createElement("td",{"value":0},newtr);
					}else{
						createElement("td",{"value":(levelLog[v][0]-levelLog[prevDay][0])},newtr,numberFormat(levelLog[v][0]-levelLog[prevDay][0]));
					}
					createElement("td",{"value":levelLog[v][1],"style":"border-right:2px solid black;"},newtr,levelLog[v][1]?numberFormat(levelLog[v][1]):"");
					for(var w=0;w<=1;w++){
						createElement("td",{"value":levelLog[v][w+2]},newtr,numberFormat(levelLog[v][w+2]));
						totalumsatz[w] += levelLog[v][w+2];
					}
					if(levelLog[v][4]>0){
						createElement("td",{"value":levelLog[v][4]},newtr,numberFormat(levelLog[v][4]));
						totalumsatz[2][0] += days;
						totalumsatz[2][1] += levelLog[v][4];
					}else{
						createElement("td",{"value":0},newtr,"-");
					}
					prevDay=v;
				}
				newtbody.scrollTop=newtbody.scrollHeight;
				//if (newdiv.scrollTop ==0) newdiv.scrollTop=(newdiv.scrollHeight < newdiv.clientHeight)?0:newdiv.scrollHeight - newdiv.clientHeight;

				newtr=createElement("tr",{"class":"borderTop2","align":"right"},newtfoot);
				createElement("td",{"style":"border-right:2px solid black;"},newtr,sign_average);
				createElement("td",{},newtr);
				if(secondDay){
					var daycount=1+Math.round((now-getTime(secondDay))/86400);
					createElement("td",{},newtr,numberFormat((levelLog[prevDay][0]-levelLog[firstDay][0])/daycount));
				}else{
					createElement("td",{},newtr);
				}
				createElement("td",{"style":"border-right:2px solid black;"},newtr);
				var daycount=1+Math.round((now-getTime(firstDay))/86400);
				for(var w=0;w<2;w++){
					createElement("td",{},newtr,numberFormat(totalumsatz[w]/daycount));
				}
				createElement("td",{},newtr,numberFormat(totalumsatz[2][1]/totalumsatz[2][0]));

				newdiv=createElement("div",{"style":"height:106px;margin-top:10px;overflow:auto;color:black;"},infoPanelInner);
				for(var w=0;w<prodNameSort[0].length;w++){
					var v=prodNameSort[0][w];
					if((!prodBlock[0][v].match(/t/))&&(buyNotePadShowBlocked||((!prodBlock[0][v].match(/l/))&&(!prodBlock[0][v].match(/q/))))){
						if(0<prodMinRack[0][v]){
							if (prodStock[0][v]==0){
								newdiv1=createElement("div",{"class":"link hoverBgCc9","prod":v,"style":"line-height:16px;"},newdiv);
								newdiv1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
								newdiv1.addEventListener("click",function(){ showMarket(this.getAttribute("prod")); },false);
								produktPic(0,v,newdiv1);
								createElement("span",{"style":"font-weight:bold;"},newdiv1,texte["lagerFehlt"].replace(/%1%/,prodName[0][v]));
							}else if(prodStock[0][v]<prodMinRack[0][v]){
								newdiv1=createElement("div",{"class":"link hoverBgCc9","prod":v,"style":"line-height:16px;"},newdiv);
								newdiv1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
								newdiv1.addEventListener("click",function(){ showMarket(this.getAttribute("prod")); },false);
								produktPic(0,v,newdiv1);
								createElement("span",{"style":"font-weight:bold;"},newdiv1,texte["lagerNiedrig"].replace(/%1%/,prodName[0][v])+" ("+numberFormat(prodStock[0][v])+")");
							}
						}
					}
				}
			}
			break;
			case "options":{
				//$("infoPanelInner").style.width="600px";
				createElement("div",{"id":"infoPanelT","align":"center","style":"line-height:30px;"},infoPanelInner);
				newdiv=createElement("div",{"id":"infoPanelL","style":"position:absolute;top:30px;left:0;width:105px;overflow:auto;height:485px;border-right:2px solid #685338;"},infoPanelInner);
				newdiv.addEventListener("click",function(event){
					if((event.target.parentNode==this)&&(event.target.getAttribute("class").match(/(\s|^)link(\s|$)/))){
						for(var v=0;v<this.childElementCount;v++){
							this.children[v].style.backgroundColor=(event.target==this.children[v])?"lightblue":"";
						}
					}
				},false);
				createElement("div",{"style":"padding-top:5px;border-bottom:1px solid #685338;font-weight:bold;"},$("infoPanelL"),texte["berater"]);
				createElement("div",{"id":"infoPanelR","style":"position:absolute;top:30px;left:110px;width:480px;overflow:auto;height:485px;"},infoPanelInner);

				newdiv=createElement("div",{"class":"link hoverBgLightbrown","style":"padding-top:5px;border-bottom:1px solid #685338;"},$("infoPanelL"),texte["optionen"]);
				newdiv.addEventListener("click",function(){
					var newdiv=$("infoPanelT");
					newdiv.innerHTML="<span><b>"+texte["optionen"]+"</b>&nbsp;-&nbsp;"+texte["berater"]+"&nbsp;"+VERSION+"</span>";
					if(VERSION!=updateCheck[1]){
						newdiv=createElement("span",{"class":"link","style":"margin-left:4px;"},newdiv,"(&rarr;"+updateCheck[1]+")");
						newdiv.addEventListener("click",function(){
							location.href=USO_Source;
						},false);
					}
					$("infoPanelR").innerHTML="";
					var newtable=createElement("table",{"style":"width:100%;","border":"1","class":"hoverRowBgCc9"},$("infoPanelR"));
					var newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					var newtd=createElement("th",{"colspan":"3"},newtr,texte["farm"]);
					var newTd1;

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					var newinput=createElement("input",{"type":"checkbox","class":"link","checked":valAutoWater["farm"]},newtd);
					newinput.addEventListener("click",function(){
						valAutoWater["farm"]=this.checked;
						unsafeData.valAutoWater=valAutoWater;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoWater",implode(valAutoWater),9);
					},false);
					createElement("td",{},newtr,texte["valAutoWater"][0]);
					createElement("td",{},newtr,texte["valAutoWater"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valAutoCrop["farm"]},newtd);
					newinput.addEventListener("click",function(){
						valAutoCrop["farm"]=this.checked;
						unsafeData.valAutoCrop=valAutoCrop;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoCrop",implode(valAutoCrop),11);
					},false);
					createElement("td",{},newtr,texte["valAutoCrop"][0]);
					createElement("td",{},newtr,texte["valAutoCrop"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valAssumeWater["farm"]},newtd);
					newinput.addEventListener("click",function(){
						valAssumeWater["farm"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAssumeWater",implode(valAssumeWater),10);
					},false);
					createElement("td",{},newtr,texte["valAssumeWater"][0]);
					createElement("td",{},newtr,texte["valAssumeWater"][1]);
					
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valWaterNeeded["farm"]},newtd);
					newinput.addEventListener("click",function(){
						valWaterNeeded["farm"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valWaterNeeded",implode(valWaterNeeded),12);
					},false);
					createElement("td",{},newtr,texte["valWaterNeeded"][0]);
					createElement("td",{},newtr,texte["valWaterNeeded"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalErnteMsg","type":"checkbox","class":"link","checked":valErnteMsg},newtd);
					newinput.addEventListener("click",function(){
						valErnteMsg=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valErnteMsg", valErnteMsg,13);
					},false);
					createElement("td",{},newtr,texte["valCropMsg"][0]);
					createElement("td",{},newtr,texte["valCropMsg"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"value":valLimitEmptyFields["field"],"class":"text","maxlength":"2","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var help=parseInt(this.value,10);
						if(isNaN(help)||(help<0)){
							this.value="";
						}else{
							this.value=help;
							valLimitEmptyFields["field"]=help;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valLimitEmptyFields",implode(valLimitEmptyFields),14);
							for(var v=0;v<ALL_ZONES["farm"].length;v++){ 
								if(zoneTyp[ALL_ZONES["farm"][v]]==1){
									processZoneProductionData(ALL_ZONES["farm"][v]); 
								}
							}
						}
					},false);
					createElement("td",{},newtr,texte["valLimitEmptyFields"][0]);
					createElement("td",{},newtr,texte["valLimitEmptyFields"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valGlobaltimeShowCroppedZone["farm"]},newtd);
					newinput.addEventListener("click",function(){
						valGlobaltimeShowCroppedZone["farm"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobaltimeShowCroppedZone",implode(valGlobaltimeShowCroppedZone),16);
					},false);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][0]);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][1]);

					newtr=createElement("tr",{},newtable);
					createElement("td",{"align":"center"},newtr);
					createElement("td",{},newtr,texte["valMoveAnimals"][0]);
					newtd=createElement("td",{},newtr,texte["valMoveAnimals"][1]);
					for(var v=0;v<animalMove.length;v++){ if(animalMove[v]){
						newspan=createElement("span",{"style":"display:inline-block;margin-right:15px;"},newtd);
						produktPic(0,BUILDING2PRODUCT[v][0],newspan);
						newinput=createElement("input",{"id":"inputvalMoveAnimals"+v,"type":"checkbox","class":"link","checked":valMoveAnimals[v]},newspan);
						newinput.addEventListener("click",function(){
							valMoveAnimals[this.id.replace("inputvalMoveAnimals","")]=this.checked;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMoveAnimals", implode(valMoveAnimals),15);
						},false);
					}}

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalSpoilerZoneUpdate","type":"checkbox","class":"link","checked":valSpoilerZoneUpdate},newtd);
					newinput.addEventListener("click",function(){
						valSpoilerZoneUpdate=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valSpoilerZoneUpdate", valSpoilerZoneUpdate,18);
					},false);
					createElement("td",{},newtr,texte["valSpoilerZoneUpdate"][0]);
					createElement("td",{},newtr,texte["valSpoilerZoneUpdate"][1]);

					// ***********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,"Farmis"); // TODO texte

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newdiv=createElement("div",{"style":"white-space:nowrap;"},newtd);
					newinput=createElement("input",{"id":"inputvalFarmiLimits0","value":valFarmiLimits[0],"class":"text","maxlength":"3","size":"3px","style":"background-color:transparent;text-align:center;"},newdiv);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("change",function(){
						var help=parseInt(this.value,10);
						if (isNaN(help)){
							this.value="";
						}else{
							help=Math.max(0,Math.min(999,Math.min(help,valFarmiLimits[1])));
							valFarmiLimits[0]=help;
							doFarmis();
							this.value=help;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valFarmiLimits", implode(valFarmiLimits),19);
							unsafeData.valFarmiLimits=valFarmiLimits.clone();
						}
					},false);
					createElement("span",{},newdiv,"%");
					newdiv=createElement("div",{"style":"white-space:nowrap;"},newtd);
					newinput=createElement("input",{"id":"inputvalFarmiLimits1","value":valFarmiLimits[1],"class":"text","maxlength":"3","size":"3px","style":"background-color:transparent;text-align:center;"},newdiv);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("change",function(){
						var help=parseInt(this.value,10);
						if (isNaN(help)){
							this.value="";
						}else{
							help=Math.max(0,Math.min(999,Math.max(help,valFarmiLimits[0])));
							valFarmiLimits[1]=help;
							doFarmis();
							this.value=help;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valFarmiLimits", implode(valFarmiLimits),20);
							unsafeData.valFarmiLimits=valFarmiLimits.clone();
						}
					},false);
					createElement("span",{},newdiv,"%");
					createElement("td",{},newtr,texte["valFarmiLimits"][0]);
					createElement("td",{},newtr,texte["valFarmiLimits"][1]+" ("+texte["default"]+":&nbsp;90,100)");

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalFarmiMiniInfo","type":"checkbox","class":"link","checked":valFarmiMiniInfo},newtd);
					newinput.addEventListener("click",function(){
						valFarmiMiniInfo=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valFarmiMiniInfo", valFarmiMiniInfo,21);
						doFarmis();
					},false);
					createElement("td",{},newtr,texte["valFarmiMiniInfo"][0]);
					createElement("td",{},newtr,texte["valFarmiMiniInfo"][1]);

					// ***********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["windmill"]);

					var newtdset=null;
					var name;
					for(var j=0;j<ALL_ZONES["windmill"].length;j++){
						name=ALL_ZONES["windmill"][j];
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"align":"center"},newtr);
						newinput=createElement("input",{"id":"inputvalzoneAddToGlobalTime_"+name,"type":"checkbox","class":"link","checked":zoneAddToGlobalTime[name]},newtd);
						if(zoneBlock[name]){ newinput.disabled=true; }
						newinput.addEventListener("click",function(){
							var zoneNrF=this.id.replace("inputvalzoneAddToGlobalTime_","");
							zoneAddToGlobalTime[zoneNrF]=this.checked;
							unsafeData.zoneAddToGlobalTime=zoneAddToGlobalTime[zoneNrF];
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobalTimeAdd", implode(zoneAddToGlobalTime));
							processZoneProductionData(zoneNrF);
						},false);
						newtd=createElement("td",{},newtr);
						if(zoneBlock[name]){ newtd.style.opacity="0.6"; }
						createElement("span",{},newtd,texte[name]);
						if(newtdset==null){
							newtdset=createElement("td",{"rowspan":1,"id":"namevalzoneAddToGlobalTime"},newtr,texte["valzoneAddToGlobalTime"][1]);
						}else{
							newtdset.rowSpan++;
						}
					}
					name=null;newtdset=null;

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valGlobaltimeShowCroppedZone["windmill"]},newtd);
					newinput.addEventListener("click",function(){
						valGlobaltimeShowCroppedZone["windmill"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobaltimeShowCroppedZone",implode(valGlobaltimeShowCroppedZone),16);
					},false);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][0]);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][1]);
					
					// ***********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["forestry"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					var newinput=createElement("input",{"id":"inputvalGiess","type":"checkbox","class":"link","checked":valAutoWater["forestry"]},newtd);
					newinput.addEventListener("click",function(){
						valAutoWater["forestry"]=this.checked;
						unsafeData.valAutoWater=valAutoWater;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoWater",implode(valAutoWater),9);
					},false);
					createElement("td",{},newtr,texte["valAutoWater"][0]);
					createElement("td",{},newtr,texte["valAutoWater"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valAutoCrop["forestry"]},newtd);
					newinput.addEventListener("click",function(){
						valAutoCrop["forestry"]=this.checked;
						unsafeData.valAutoCrop=valAutoCrop;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAutoCrop",implode(valAutoCrop),11);
					},false);
					createElement("td",{},newtr,texte["valAutoCrop"][0]);
					createElement("td",{},newtr,texte["valAutoCrop"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valAssumeWater["forestry"]},newtd);
					newinput.addEventListener("click",function(){
						valAssumeWater["forestry"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valAssumeWater",implode(valAssumeWater),10);
					},false);
					createElement("td",{},newtr,texte["valAssumeWater"][0]);
					createElement("td",{},newtr,texte["valAssumeWater"][1]);
					
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valWaterNeeded["forestry"]},newtd);
					newinput.addEventListener("click",function(){
						valWaterNeeded["forestry"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valWaterNeeded",implode(valWaterNeeded),12);
					},false);
					createElement("td",{},newtr,texte["valWaterNeeded"][0]);
					createElement("td",{},newtr,texte["valWaterNeeded"][1]);
					
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"value":valLimitEmptyFields["forest"],"class":"text","maxlength":"2","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var help=parseInt(this.value,10);
						if(isNaN(help)||(help<0)){
							this.value="";
						}else{
							this.value=help;
							valLimitEmptyFields["forest"]=help;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valLimitEmptyFields",implode(valLimitEmptyFields));
							processZoneProductionData("forest");
						}
					},false);
					createElement("td",{},newtr,texte["valLimitEmptyFields_forest"][0]);
					createElement("td",{},newtr,texte["valLimitEmptyFields_forest"][1]);

					var newtdset=null;
					var name;
					for(var j=0;j<ALL_ZONES["forestry"].length;j++){
						name=ALL_ZONES["forestry"][j];
						// if(!unsafeWindow.formulas && name=="windmill"){continue;}
						// if(unsafeWindow.forestry_unlock==undefined && (name=="forest"||name=="sawmill"||name=="carpentry")){continue;}
						// if($("inputvalzoneAddToGlobalTime_"+zoneTyp[name])){continue;}
	                
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"align":"center"},newtr);
						newinput=createElement("input",{"id":"inputvalzoneAddToGlobalTime_"+name,"type":"checkbox","class":"link","checked":zoneAddToGlobalTime[name]},newtd);
						if(zoneBlock[name]){ newinput.disabled=true; }
						newinput.addEventListener("click",function(){
							var zoneNrF=this.id.replace("inputvalzoneAddToGlobalTime_","");
							zoneAddToGlobalTime[zoneNrF]=this.checked;
							unsafeData.zoneAddToGlobalTime=zoneAddToGlobalTime[zoneNrF];
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobalTimeAdd", implode(zoneAddToGlobalTime));
							processZoneProductionData(zoneNrF);
						},false);
	                
						newtd=createElement("td",{},newtr);
						if(zoneBlock[name]){ newtd.style.opacity="0.6"; }
						createElement("span",{},newtd,texte[name]);
						if(newtdset==null){
							newtdset=createElement("td",{"rowspan":1,"id":"namevalzoneAddToGlobalTime"},newtr,texte["valzoneAddToGlobalTime"][1]);
						}else{
							newtdset.rowSpan++;
						}
					}
					name=null;newtdset=null;

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valGlobaltimeShowCroppedZone["forestry"]},newtd);
					newinput.addEventListener("click",function(){
						valGlobaltimeShowCroppedZone["forestry"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobaltimeShowCroppedZone",implode(valGlobaltimeShowCroppedZone),16);
					},false);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][0]);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][1]);

					// **********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,unsafeWindow.foodworld_title);

					for(var j=0;j<ALL_ZONES["foodworld"].length;j++){
						name=ALL_ZONES["foodworld"][j];
						// if(!unsafeWindow.formulas && name=="windmill"){continue;}
						// if(unsafeWindow.forestry_unlock==undefined && (name=="forest"||name=="sawmill"||name=="carpentry")){continue;}
						// if($("inputvalzoneAddToGlobalTime_"+zoneTyp[name])){continue;}
	                
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"align":"center"},newtr);
						newinput=createElement("input",{"id":"inputvalzoneAddToGlobalTime_"+name,"type":"checkbox","class":"link","checked":zoneAddToGlobalTime[name]},newtd);
						if(zoneBlock[name]){ newinput.disabled=true; }
						newinput.addEventListener("click",function(){
							var zoneNrF=this.id.replace("inputvalzoneAddToGlobalTime_","");
							zoneAddToGlobalTime[zoneNrF]=this.checked;
							unsafeData.zoneAddToGlobalTime=zoneAddToGlobalTime[zoneNrF];
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobalTimeAdd", implode(zoneAddToGlobalTime));
							processZoneProductionData(zoneNrF);
						},false);
	                
						newtd=createElement("td",{},newtr);
						if(zoneBlock[name]){ newtd.style.opacity="0.6"; }
						createElement("span",{},newtd,texte[name]);
						if(newtdset==null){
							newtdset=createElement("td",{"rowspan":1,"id":"namevalzoneAddToGlobalTime"},newtr,texte["valzoneAddToGlobalTime"][1]);
						}else{
							newtdset.rowSpan++;
						}
					}
					name=null;newtdset=null;
					
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":valGlobaltimeShowCroppedZone["foodworld"]},newtd);
					newinput.addEventListener("click",function(){
						valGlobaltimeShowCroppedZone["foodworld"]=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valGlobaltimeShowCroppedZone",implode(valGlobaltimeShowCroppedZone),16);
					},false);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][0]);
					createElement("td",{},newtr,texte["valGlobaltimeShowCroppedZone"][1]);
					
					// **********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["minRackamount"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMinRackMan","type":"checkbox","class":"link","checked":valMinRackMan},newtd);
					newinput.addEventListener("click",function(){
						valMinRackMan=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackMan",valMinRackMan,22);
						var cand=$("infoPanelR").getElementsByClassName("minRackConfig");
						if(valMinRackMan){
							for(var v=0;v<cand.length;v++){
								cand[v].disabled=true;
								cand[v].parentNode.parentNode.style.opacity=0.6;
							}
						}else{
							for(var v=0;v<cand.length;v++){
								cand[v].disabled=false;
								cand[v].parentNode.parentNode.style.opacity=1;
							}
							calcProdMinRackInit();
						}
						cand=null;
					},false);
					createElement("td",{},newtr,texte["valMinRackMan"][0]);
					newtd=createElement("td",{"class":"link"},newtr,texte["valMinRackMan"][1]);
					newtd.addEventListener("click",function(){
						buildInfoPanel("preise2",null);
					},false);

					newTd1=null;
					for(var v in valMinRack){
						if(!valMinRack.hasOwnProperty(v)){ continue; }
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"align":"center"},newtr);
						newinput=createElement("input",{"id":"inputvalMinRack_"+v,"class":"text minRackConfig","value":valMinRack[v],"maxlength":"4","size":"5px","style":"background-color:transparent;text-align:center;"},newtd);
						if(valMinRackMan){
							newinput.disabled=true;
							newtr.style.opacity=0.6;
						}
						newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
						newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
						newinput.addEventListener("keyup",function(){
							var help=parseInt(this.value,10);
							if (isNaN(help)){
								this.value="";
							}else{
								this.value=help;
								valMinRack[this.id.replace("inputvalMinRack_","")]=help;
								GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRack",implode(valMinRack,"valMinRack"));
								calcProdMinRackInit();
							}
						},false);
						createElement("td",{},newtr,texte["category"][v]);
						if(newTd1==null){
							newTd1=createElement("td",{},newtr,texte["valMinRack"][1]);
						} else {
							newTd1.rowSpan++;
						}
					}

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"class":"text minRackConfig","type":"checkbox","checked":valMinRackPlantsize},newtd);
					if(valMinRackMan){
						newinput.disabled=true;
						newtr.style.opacity=0.6;
					}
					newinput.addEventListener("click",function(){
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackPlantsize",this.checked,24);
						calcProdMinRackInit();
					},false);
					createElement("td",{},newtr,texte["valMinRackPlantsize"][0]);
					createElement("td",{},newtr,texte["valMinRackPlantsize"][1]);

					// newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					// newtd=createElement("th",{"colspan":"3"},newtr,texte["minRackamount"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMinRackGrowing","type":"checkbox","class":"link","checked":valMinRackGrowing},newtd);
					newinput.addEventListener("click",function(){
						valMinRackGrowing=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackGrowing",valMinRackGrowing,26);
						calcProdMinRack();
					},false);
					createElement("td",{},newtr,texte["valMinRackGrowing"][0]);
					createElement("td",{},newtr,texte["valMinRackGrowing"][1]);

					newTd1=null;
					for(var typ in questData){
						if(!questData.hasOwnProperty(typ)){ continue; }
						for(var camp in questData[typ]){
							if(!questData[typ].hasOwnProperty(camp)){ continue; }
							newtr=createElement("tr",{},newtable);
							newtd=createElement("td",{"align":"center"},newtr);
							var newsel = createElement("select",{"id":"selectQuestCalcTo_"+typ+"_"+camp,"style":"width:auto;height:18px;margin-left:5px;"},newtd);
							createElement("option",{"value":0},newsel,"--");
							for(var i=questData[typ][camp]["nr"];i<QUESTS[typ][camp].length;i++){
								createElement("option",{"value":i},newsel,i);
							}
							newsel.addEventListener("change",function(){
								if(isNaN(this.value)){return false;}
								var help=this.id.split("_");
								setCalcToQuest(help[1],help[2],this.value);
							},false);
							newsel.value = questData[typ][camp]["calcTo"];
							newtd=createElement("td",{},newtr,typ+" "+camp); //TODO texte
							if(newTd1==null){
								newTd1=createElement("td",{},newtr,texte["valMinRackQuest"][1]);
							} else {
								newTd1.rowSpan++;
							}
						}
					}
					newsel=null;i=null;

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMinRackRecursive","type":"checkbox","class":"link","checked":valMinRackRecursive},newtd);
					newinput.addEventListener("click",function(){
						valMinRackRecursive=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackRecursive",valMinRackRecursive,29);
						calcProdMinRack();
					},false);
					createElement("td",{},newtr,texte["valMinRackRecursive"][0]);
					createElement("td",{},newtr,texte["valMinRackRecursive"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMinRackFarmis","type":"checkbox","class":"link","checked":valMinRackFarmis},newtd);
					newinput.addEventListener("click",function(){
						valMinRackFarmis=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackFarmis",valMinRackFarmis,30);
						calcProdMinRack();
					},false);
					createElement("td",{},newtr,texte["valMinRackFarmis"][0]);
					createElement("td",{},newtr,texte["valMinRackFarmis"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMinRackForestryFarmis","type":"checkbox","class":"link","checked":valMinRackForestryFarmis},newtd);
					newinput.addEventListener("click",function(){
						valMinRackForestryFarmis=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMinRackForestryFarmis",valMinRackForestryFarmis,31);
						calcProdMinRack();
					},false);
					createElement("td",{},newtr,texte["valMinRackForestryFarmis"][0]);
					createElement("td",{},newtr,texte["valMinRackForestryFarmis"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalProtectMinRack","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valProtectMinRack",false)},newtd);
					newinput.addEventListener("click",function(){
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valProtectMinRack",this.checked,32);
					},false);
					createElement("td",{},newtr,texte["protectMinRack"][0]);
					createElement("td",{},newtr,texte["protectMinRack"][1]);

					// *******************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["markt"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalKauflimit00","value":valKauflimit[0][0],"class":"text","maxlength":"3","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var help=parseInt(this.value,10);
						if (isNaN(help)){
							this.value="";
						}else{
							valKauflimit[0][0]=help;
							this.value=valKauflimit[0][0];
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit",implode(valKauflimit),33);
						}
					},false);
					createElement("span",{},newtd,"%");
					createElement("td",{},newtr,texte["valKauflimitDown"][0]);
					newtd=createElement("td",{},newtr,texte["valKauflimitDown"][1]);
					newinput=createElement("input",{"id":"inputvalKauflimit01","value":valKauflimit[0][1],"class":"text","maxlength":"6","size":"10px","style":"background-color:#"+valKauflimit[0][1]+";color:#F0FFEF;"},newtd);
					newinput.addEventListener("keyup",function(){
						this.value=this.value.replace(/[^0-9a-f]/ig,"");
						this.style.backgroundColor="#"+this.value;
					},false);
					newinput.addEventListener("change",function(){
						var color=this.value;
						if(!color.match(/^([0-9a-f]{3}){1,2}$/i)){
							color="990000";
							this.value=color;
						}
						this.style.backgroundColor="#"+this.value;
						valKauflimit[0][1]=this.value;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit",implode(valKauflimit),34);
					},false);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalKauflimit1","value":valKauflimit[1],"class":"text","maxlength":"3","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var help=parseInt(this.value,10);
						if (isNaN(help)){
							this.value="";
						}else{
							if(help<0){ help*=-1; }
							valKauflimit[1]=help;
							this.value=valKauflimit[1];
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit",implode(valKauflimit),35);
						}
					},false);
					createElement("span",{},newtd,"%");
					createElement("td",{},newtr,texte["valKauflimit"][0]);
					createElement("td",{},newtr,texte["valKauflimit"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalKauflimitNPC","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimitNPC",true)},newtd);
					newinput.addEventListener("click",function(){
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimitNPC",this.checked,36);
					},false);
					createElement("td",{},newtr,texte["valKauflimitNPC"][0]);
					createElement("td",{},newtr,texte["valKauflimitNPC"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalVerkaufLimitDown","value":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitDown",95),"class":"text","maxlength":"3","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("change",function(){
						var valVerkaufLimitDown=parseInt(this.value,10);
						var valVerkaufLimitUp=parseInt($("inputvalVerkaufLimitUp").value,10);
						valVerkaufLimitDown=Math.min(valVerkaufLimitDown,valVerkaufLimitUp);
						if (isNaN(valVerkaufLimitDown)){
							this.value="";
						}else{
							this.value=valVerkaufLimitDown;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitDown", valVerkaufLimitDown,37);
						}
					},false);
					createElement("span",{},newtd,"%");
					newinput=createElement("input",{"id":"inputvalVerkaufLimitUp","value":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitUp",130),"class":"text","maxlength":"3","size":"2px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("change",function(){
						var valVerkaufLimitDown=parseInt($("inputvalVerkaufLimitDown").value,10);
						var valVerkaufLimitUp=parseInt(this.value,10);
						valVerkaufLimitUp=Math.max(valVerkaufLimitDown,valVerkaufLimitUp);
						if (isNaN(valVerkaufLimitUp)){
							this.value="";
						}else{
							this.value=valVerkaufLimitUp;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitUp", valVerkaufLimitUp,38);
						}
					},false);
					createElement("span",{},newtd,"%");
					createElement("td",{},newtr,texte["valVerkaufLimit"][0]);
					createElement("td",{},newtr,texte["valVerkaufLimit"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalJoinPreise","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valJoinPreise",false)},newtd);
					newinput.addEventListener("click",function(){ GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valJoinPreise", this.checked,39); },false);
					createElement("td",{},newtr,texte["valJoinPreise"][0]);
					createElement("td",{},newtr,texte["valJoinPreise"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalQuicklinks","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valQuicklinks",true)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valQuicklinks", this.checked,40);},false);
					createElement("td",{},newtr,texte["valQuicklinks"][0]);
					createElement("td",{},newtr,texte["valQuicklinks"][1]);

					function drawDivHighlightUser(name,color,parent){
						newdiv=createElement("div",{},parent);
						newinput=createElement("input",{"value":name,"class":"text","maxlength":"20","size":"25px","style":"background-color:transparent;"},newdiv);
						newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
						newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
						newinput=createElement("input",{"value":color,"class":"text","maxlength":"6","size":"10px","style":"background-color:#"+color+";color:#F0FFEF;"},newdiv);
						newinput.addEventListener("keyup",function(){
							this.value=this.value.replace(/[^0-9a-f]/ig,"");
							this.style.backgroundColor="#"+this.value;
						},false);
						newdiv.addEventListener("change",function(){
							var tableCell=this.parentNode;
							var candinput=tableCell.getElementsByTagName("input");
							var highlightUser=new Object();
							for(var v=0;v<candinput.length;v+=2){
								var name=candinput[v].value;
								if(highlightUser[name]){
									// remove duplicate
									removeElement(candinput[v].parentNode);
									v-=2;
								}else{
									var color=candinput[v+1].value;
									if(!color.match(/^([0-9a-f]{3}){1,2}$/i)){
										color="20b2aa";
										candinput[v+1].value=color;
										candinput[v+1].style.backgroundColor="#"+color;
									}
									highlightUser[name]=color;
								}
							}
							if(highlightUser[""]==undefined){
								drawDivHighlightUser("","20b2aa",tableCell);
							}else{
								delete highlightUser[""];
							}
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_highlight",implode(highlightUser),41);
							candinput=null;tableCell=null;
						},false);
					}
					var highlightUser=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_highlight","{}"),"buildInfoPanel/options/highlightUser",{});
					highlightUser[""]="20b2aa";
					newtr=createElement("tr",{},newtable);
					createElement("td",{"align":"center"},newtr);
					createElement("td",{},newtr,texte["highlightUser"]);
					newtd=createElement("td",{},newtr);
					for(var name in highlightUser){
						if(!highlightUser.hasOwnProperty(name)){ continue; }
						drawDivHighlightUser(name,highlightUser[name],newtd);
					}

					newtr=createElement("tr",{},newtable);
					createElement("td",{"align":"center"},newtr);
					createElement("td",{},newtr,texte["highlightProducts"]);
					newtd=createElement("td",{},newtr);
					newdiv=createElement("div",{},newtd);
					newinput=createElement("input",{"type":"checkbox","class":"link","checked":highlightProducts[0]},newdiv);
					newinput.addEventListener("click",function(){
						highlightProducts[0]=this.checked;
						$("highlightProducts0").disabled=highlightProducts[0];
						$("highlightProducts1").disabled=highlightProducts[0];
						if(highlightProducts[0]){
							// todo calc highlightProducts[1]
							$("highlightProducts0").value=-1;
							$("highlightProducts1").value=-1;
						} else {
							var i=0;
							for(var prod in highlightProducts[1]){
								if(!highlightProducts[1].hasOwnProperty(prod)){ continue; }
								if(i>1){continue;}
								$("highlightProducts"+i).value=prod;
								i++;
							}
						}
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts",implode(highlightProducts),42);
					},false);
					createElement("span",{},newdiv,texte["useQuestProducts"]);
					for(var i=0;i<2;i++){
						newinput=createElement("select",{"id":"highlightProducts"+i,"class":"link2"},newtd);
						createElement("option",{"value":"-1"},newinput,"--");
						for(var v=0;v<prodNameSort[0].length;v++){
							if((!prodBlock[0][prodNameSort[0][v]].match(/t/))&&(!prodBlock[0][prodNameSort[0][v]].match(/l/))){
								createElement("option",{"value":prodNameSort[0][v]},newinput,prodName[0][prodNameSort[0][v]]);
							}
						}
						if(highlightProducts[0]){
							newinput.disabled=true; 
							newinput.value=-1;
						}
						newinput.addEventListener("change",function(){
							highlightProducts[1]={};
							highlightProducts[1][$("highlightProducts0").value]=true;
							highlightProducts[1][$("highlightProducts1").value]=true;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts",implode(highlightProducts),43);
						},false);
					}
					if(!highlightProducts[0]){
						var i=0;
						for(var prod in highlightProducts[1]){
							if(!highlightProducts[1].hasOwnProperty(prod)){ continue; }
							if(i>1){continue;}
							$("highlightProducts"+i).value=prod;
							i++;
						}
					}
						
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalNimmBeob","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_valNimmBeob",false)},newtd);
					newinput.addEventListener("click",function(){ GM_setValue2(LNG+"_"+SERVER+"_valNimmBeob",this.checked,44); },false);
					createElement("td",{},newtr,texte["valNimmBeob"][0]);
					createElement("td",{},newtr,texte["valNimmBeob"][1]);

					// ********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["messages"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalNachr","value":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valPrivNachr",100),"class":"text","maxlength":"5","size":"5px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var valPrivNachr=parseInt(this.value,10);
						if (isNaN(valPrivNachr)){
							this.value="";
						}else{
							this.value=valPrivNachr;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valPrivNachr", valPrivNachr,45);
						}
					},false);
					createElement("td",{},newtr,texte["valPrivNachr"][0]);
					createElement("td",{},newtr,texte["valPrivNachr"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalNachr","value":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valNachr",100),"class":"text","maxlength":"5","size":"5px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var valNachr=parseInt(this.value,10);
						if (isNaN(valNachr)){
							this.value="";
						}else{
							this.value=valNachr;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valNachr", valNachr,46);
						}
					},false);
					createElement("td",{},newtr,texte["valNachr"][0]);
					createElement("td",{},newtr,texte["valNachr"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalMessageRe","type":"checkbox","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMessageRe",true),"class":"link"},newtd);
					newinput.addEventListener("click",function(){ GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valMessageRe", this.checked,47); },false);
					createElement("td",{},newtr,texte["valMessageRe"][0]);
					createElement("td",{},newtr,texte["valMessageRe"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalContractLogAmount","value":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valContractLogAmount",200),"class":"text","maxlength":"5","size":"5px","style":"background-color:transparent;text-align:center;"},newtd);
					newinput.addEventListener("focus",function(){this.style.backgroundColor="lightblue";},false);
					newinput.addEventListener("blur",function(){this.style.backgroundColor="transparent";},false);
					newinput.addEventListener("keyup",function(){
						var valContractLogAmount=parseInt(this.value,10);
						if (isNaN(valContractLogAmount)){
							this.value="";
						}else{
							this.value=valContractLogAmount;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valContractLogAmount", valContractLogAmount,17);
						}
					},false);
					createElement("td",{},newtr,texte["valContractLogAmount"][0]);
					createElement("td",{},newtr,texte["valContractLogAmount"][1]);

					// *********************************************************************
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,texte["allgemein"]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalAutoLogin","type":"checkbox","class":"link","checked":GM_getValue("valAutoLogin",false)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2("valAutoLogin", this.checked,48);},false);
					createElement("td",{},newtr,texte["valAutoLogin"][0]);
					createElement("td",{},newtr,texte["valAutoLogin"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalUpdate","type":"checkbox","class":"link","checked":GM_getValue("valUpdate",true)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2("valUpdate", this.checked,49);},false);
					createElement("td",{},newtr,texte["valUpdate"][0]);
					createElement("td",{},newtr,texte["valUpdate"][1]);

					if (STAT_SERVER[LNG]){
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"align":"center"},newtr);
						newinput=createElement("input",{"id":"inputvalStatistik","type":"checkbox","class":"link","checked":valStatistik},newtd);
						newinput.addEventListener("click",function(){
							valStatistik=this.checked;
							GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valStatistik", valStatistik,50);
						},false);
						createElement("td",{},newtr,texte["valStatistik"][0]);
						createElement("td",{},newtr,texte["valStatistik"][1]);
					}

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{},newtr);
					createElement("td",{},newtr,texte["valServerTimeOffset"][0]);
					newtd=createElement("td",{},newtr);
					newinput=createElement("button",{"type":"button","class":"link2"},newtd,"-");
					newinput.addEventListener("click",function(){
						valServerTimeOffset=Math.max(-86400,valServerTimeOffset-3600);
						GM_setValue(LNG+"_valServerTimeOffset",valServerTimeOffset);
						nowServerOff=unsafeWindow.Zeit.Server+valServerTimeOffset;
						this.parentNode.children[1].innerHTML=(valServerTimeOffset<0?"":"+")+Math.round(valServerTimeOffset/3600)+"h";
						this.parentNode.children[3].innerHTML=getFormattedDateStr(nowServerOff)+"&nbsp;"+getDaytimeStr(nowServerOff);
					},false);
					createElement("span",{"style":"margin-right:5px;"},newtd,(valServerTimeOffset<0?"":"+")+Math.round(valServerTimeOffset/3600)+"h");
					newinput=createElement("button",{"type":"button","class":"link2"},newtd,"+");
					newinput.addEventListener("click",function(){
						valServerTimeOffset=Math.min(86400,valServerTimeOffset+3600);
						GM_setValue(LNG+"_valServerTimeOffset",valServerTimeOffset);
						nowServerOff=unsafeWindow.Zeit.Server+valServerTimeOffset;
						this.parentNode.children[1].innerHTML=(valServerTimeOffset<0?"":"+")+Math.round(valServerTimeOffset/3600)+"h";
						this.parentNode.children[3].innerHTML=getFormattedDateStr(nowServerOff)+"&nbsp;"+getDaytimeStr(nowServerOff);
					},false);
					createElement("span",{"style":"margin-left:10px;"},newtd,getFormattedDateStr(nowServerOff)+"&nbsp;"+getDaytimeStr(nowServerOff));

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalGamecursor","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valGamecursor",true)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valGamecursor", this.checked,51);},false);
					createElement("td",{},newtr,texte["valGamecursor"][0]);
					createElement("td",{},newtr,texte["valGamecursor"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalDrag","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valDrag",false)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valDrag", this.checked,52);},false);
					createElement("td",{},newtr,texte["valDrag"][0]);
					createElement("td",{},newtr,texte["valDrag"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalDrag","type":"checkbox","class":"link","checked":valClickErrorbox},newtd);
					newinput.addEventListener("click",function(){
						valClickErrorbox=this.checked;
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valClickErrorbox", valClickErrorbox,53);
					},false);
					createElement("td",{},newtr,texte["valClickErrorbox"][0]);
					createElement("td",{},newtr,texte["valClickErrorbox"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputvalHotkey","type":"checkbox","class":"link","checked":GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valHotkey",true)},newtd);
					newinput.addEventListener("click",function(){GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_valHotkey", this.checked,54);},false);
					createElement("td",{},newtr,texte["valHotkeys"][0]);
					createElement("td",{},newtr,texte["valHotkeys"][1]);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"colspan":"2","align":"center"},newtr);
					newinput=createElement("button",{"type":"button","class":"link2"},newtd,texte["cacheReset"][0]);
					newinput.addEventListener("click",function(){
						alert2(texte["cacheReset"][1],texte["yes"],texte["no"],function(){
							for(var i=1000; i >=0; --i){unsafeWindow.clearInterval(i);}
							window.setTimeout(function(){
								var protect={"kauf":1,"farmiLog":1,"vertraegeIn":1,"vertraegeOut":1,"levelLog":1,"nachrichten":1};
								var help=GM_listValues();
								for(var v=help.length-1;v>-1;v--){
								if(help[v].match(LNG+"_"+SERVER+"_"+USERNAME+"_")){
									var curr=help[v].replace(LNG+"_"+SERVER+"_"+USERNAME+"_","");
									if(!protect[curr]){ GM_deleteValue(help[v]); }
								}
								}
								top.location.href=top.location.href;
							},500);
						});
					},false);
					createElement("td",{},newtr,texte["cacheReset"][1]);

					// *****
					newtr=createElement("tr",{"style":"background-color:#b69162;"},newtable);
					newtd=createElement("th",{"colspan":"3"},newtr,"Developing");

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputDevmode","type":"checkbox","class":"link","checked":DEVMODE},newtd);
					newinput.addEventListener("click",function(){GM_setValue2("devmode",DEVMODE=this.checked,55);},false);
					createElement("td",{},newtr,"Developer Mode");
					createElement("td",{},newtr);

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputDevmodeEvents","type":"checkbox","class":"link","checked":DEVMODE_EVENTS},newtd);
					newinput.addEventListener("click",function(){GM_setValue2("devmode_events",DEVMODE_EVENTS=this.checked,56);},false);
					createElement("td",{},newtr,"Developer Mode");
					createElement("td",{},newtr,"Show events (reload page)");

					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"align":"center"},newtr);
					newinput=createElement("input",{"id":"inputDevmodeFunctions","type":"checkbox","class":"link","checked":DEVMODE_FUNCTION},newtd);
					newinput.addEventListener("click",function(){GM_setValue2("devmode_function",DEVMODE_FUNCTION=this.checked);},false);
					createElement("td",{},newtr,"Developer Function");
					createElement("td",{},newtr,"Show function calls");
					newtable=null;newtr=null;newtd=null;newdiv=null;newinput=null;
					raiseEvent("gameInfoPanelOptions");
				},false);
				click(newdiv);

				// Accounts
				newdiv=createElement("div",{"class":"link hoverBgLightbrown","style":"padding-top:5px;border-bottom:1px solid #685338;"},$("infoPanelL"),texte["accounts"]);
				newdiv.addEventListener("click",function(){
					var newdiv=$("infoPanelT");
					newdiv.innerHTML="<span><b>"+texte["accounts"]+"</b>&nbsp;-&nbsp;"+texte["berater"]+"&nbsp;"+VERSION+"</span>";
					if(VERSION!=updateCheck[1]){
						newdiv=createElement("span",{"class":"link","style":"margin-left:4px;"},newdiv,"(&rarr;"+updateCheck[1]+")");
						newdiv.addEventListener("click",function(){
							location.href=USO_Source;
						},false);
					}
					$("infoPanelR").innerHTML="";
					//createElement("div",{"align":"center","style":"line-height:30px;font-weight:bold;"},$("infoPanelR"),texte["accounts"]);
					createElement("table",{"id":"tableAutologin","align":"center"},$("infoPanelR"));
					function buildLoginTable(showPW){
						var logindata=explode(GM_getValue("logindata","[]"),"buildLoginTable/logindata",[]);

						function saveLogin(){
							GM_setValue2("logindata",implode(logindata),57);
						}
						var newtable=createElement("table",{"align":"center"});
						$("tableAutologin").parentNode.replaceChild(newtable,$("tableAutologin"));
						newtable.id="tableAutologin";
						newtable.addEventListener("change",saveLogin,false);
						var newtr=createElement("tr",{},newtable);
						createElement("th",{},newtr,texte["server"]);
						createElement("th",{},newtr,texte["name"]);
						createElement("th",{},newtr,texte["passwort"]);
						var newtd,newinput,newselect,newdiv;
						for(var v=0;v<logindata.length;v++){
							newtr=createElement("tr",{},newtable);
							newtd=createElement("td",{},newtr);
							newinput=createElement("input",{"id":"loginActive"+v,"type":"checkbox","class":"link","checked":logindata[v][4]},newtd);
							newinput.addEventListener("mouseover",function(event){ showToolTip(event,texte["accountAktiv"]); },false);
							newinput.addEventListener("change",function(){ logindata[this.id.replace("loginActive","")][4]=this.checked; },false);
							newinput=createElement("input",{"id":"loginServer"+v,"class":"text","style":"width:20px","maxlength":"2"},newtd);
							if (isNaN(logindata[v][1])){ logindata[v][1]="0";}
							if (logindata[v][1]!="0"){ newinput.value=logindata[v][1]; }
							newinput.addEventListener("change",function(){
								var readin=parseInt(this.value,10);
								if (isNaN(readin) || (readin<1)){alert2(texte["ungueltigerServer"],texte["ok"]); this.value="";}
								else{
									this.value=readin;
									logindata[this.id.replace("loginServer","")][1]=readin;
								}
							},false);
							newselect=createElement("select",{"id":"loginLng"+v},newtd);
							for(var w in GAMEPAGES){
								if(!GAMEPAGES.hasOwnProperty(w)){ continue; }
								createElement("option",{"value":w},newselect,w);
							}
							newselect.value=logindata[v][0];
							newselect.addEventListener("change",function(){ logindata[this.id.replace("loginLng","")][0]=this.value; },false);

							newtd=createElement("td",{},newtr);
							newinput=createElement("input",{"id":"loginName"+v,"value":logindata[v][2],"class":"text","style":"width:140px","maxlength":"20"},newtd);
							newinput.addEventListener("change",function(){ logindata[this.id.replace("loginName","")][2]=this.value; },false);

							newtd=createElement("td",{},newtr);
							newinput=createElement("input",{"id":"loginPW"+v,"value":enc(logindata[v][3],-4242),"class":"text","style":"width:140px","maxlength":"20"},newtd);
							if (!showPW){ newinput.type="password"; }
							newinput.addEventListener("change",function(){ logindata[this.id.replace("loginPW","")][3]=enc(this.value,4242); },false);

							newtd=createElement("td",{},newtr);
							if (v>0){
								newdiv=createElement("div",{"id":"loginUp"+v,"class":"link2","style":"width:14px;height:10px;"},newtd);
								createElement("img",{"src":GFX+"quest_up.gif","style":"width:14px;height:10px;"},newdiv);
								newdiv.addEventListener("mouseover",function(){this.style.backgroundColor="blue";},false);
								newdiv.addEventListener("mouseout",function(){this.style.backgroundColor="transparent";},false);
								newdiv.addEventListener("click",function(){
									var currLine=parseInt(this.id.replace("loginUp",""),10);
									logindata.splice(currLine-1,2,logindata[currLine],logindata[currLine-1]);
									saveLogin();
									buildLoginTable(showPW);
								},false);
							}
							if (v<logindata.length-1){
								newdiv=createElement("div",{"id":"loginDown"+v,"class":"link2","style":"width:14px;height:10px;"},newtd);
								createElement("img",{"src":GFX+"quest_down.gif","style":"width:14px;height:10px;"},newdiv);
								newdiv.addEventListener("mouseover",function(){this.style.backgroundColor="blue";},false);
								newdiv.addEventListener("mouseout",function(){this.style.backgroundColor="transparent";},false);
								newdiv.addEventListener("click",function(){
									var currLine=parseInt(this.id.replace("loginDown",""),10);
									logindata.splice(currLine,2,logindata[currLine+1],logindata[currLine]);
									saveLogin();
									buildLoginTable(showPW);
								},false);
							}

							newtd=createElement("td",{"id":"loginDelete"+v},newtr);
							createElement("img",{"src":GFX+"popin/contracts/anullieren.gif","class":"link2","style":"width: 16px;height: 16px;"},newtd);
							newtd.addEventListener("mouseover",function(event){
								showToolTip(event,texte["loeschen"]);
								this.style.backgroundColor="blue";
							},false);
							newtd.addEventListener("mouseout",function(){this.style.backgroundColor="transparent";},false);
							newtd.addEventListener("click",function(){
								var currLine=this.id.replace("loginDelete","");
								logindata.splice(currLine,1);
								saveLogin();
								buildLoginTable(showPW);
							},false);
						}

						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"colspan":"5","class":"link","style":"font-weight:bold;font-size:16px;text-align:right;"},newtr,"+");
						newtd.addEventListener("mouseover",function(){this.style.backgroundColor="blue";},false);
						newtd.addEventListener("mouseout",function(){this.style.backgroundColor="transparent";},false);
						newtd.addEventListener("click",function(){
							logindata.push([LNG,"0","","","false"]); // neue leere zeile
							saveLogin();
							buildLoginTable(showPW);
						},false);
						newtable=null;newtr=null;newtd=null;newinput=null;newselect=null;newdiv=null;
					}
					buildLoginTable(false);
					newdiv=createElement("div",{"align":"center"},$("infoPanelR"));
					var newinput=createElement("input",{"type":"checkbox","class":"link","checked":false},newdiv);
					newinput.addEventListener("click",function(){buildLoginTable(this.checked);},false);
					createElement("span",{},newdiv,texte["zeigePasswoerter"]);

					//paypal
					newdiv=createElement("div",{"align":"center","style":"margin-top:10px;"},$("infoPanelR"));
					var newform=createElement("form",{"id":"paypalForm","action":"https://www.paypal.com/cgi-bin/webscr","method":"post"},newdiv);
					createElement("input",{"type":"hidden","name":"cmd","value":"_donations"},newform);
					createElement("input",{"type":"hidden","name":"business","value":"jessicakanaan@web.de"},newform);
					createElement("input",{"type":"hidden","name":"lc","value":((LNG=="de")?"DE":"US")},newform);
					createElement("input",{"type":"hidden","name":"item_name","value":"MyFreeFarm Script"},newform);
					createElement("input",{"type":"hidden","name":"no_note","value":"0"},newform);
					createElement("input",{"type":"hidden","name":"currency_code","value":"EUR"},newform);
					createElement("input",{"type":"hidden","name":"bn","value":"PP-DonationsBF:btn_donate_LG.gif:NonHostedGuest"},newform);
					createElement("input",{"type":"image","border":"0","src":"https://www.paypal.com/"+((LNG=="de")?"de_DE/DE":"en_US")+"/i/btn/btn_donate_LG.gif","name":"submit",alt:"PayPal"},newform);
					createElement("img",{"alt":"","border":"0","src":"https://www.paypal.com/en_US/i/scr/pixel.gif","width":"1","height":"1"},newform);
					newdiv=null;newinput=null;newform=null;
				},false);

				// Hotkeys
				newdiv=createElement("div",{"class":"link hoverBgLightbrown","style":"padding-top:5px;border-bottom:1px solid #685338;"},$("infoPanelL"),texte["hotkeys"]);
				newdiv.addEventListener("click",function(){
					var newdiv=$("infoPanelT");
					newdiv.innerHTML="<span><b>"+texte["hotkeys"]+"</b>&nbsp;-&nbsp;"+texte["berater"]+"&nbsp;"+VERSION+"</span>";
					if(VERSION!=updateCheck[1]){
						newdiv=createElement("span",{"class":"link","style":"margin-left:4px;"},newdiv,"(&rarr;"+updateCheck[1]+")");
						newdiv.addEventListener("click",function(){
							location.href=USO_Source;
						},false);
					}
					$("infoPanelR").innerHTML="";
					var newtable=createElement("table",{"align":"center","border":"1","class":"hoverRowBgCc9"},$("infoPanelR"));
					var newtr,newtd,newinput;
					for(var tr in texte["hotkeymap"]){
						if(!texte["hotkeymap"].hasOwnProperty(tr)){ continue; }
						newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{},newtr);
						newinput=createElement("input",{"id":"hotkey"+tr,"value":getKeySymbol(hotkeymap[tr]),"class":"text","style":"width:80px;"},newtd);
						newinput.addEventListener("keyup",function(event){
							this.value=getKeySymbol(event.keyCode);
							hotkeymap[this.id.replace("hotkey","")]=event.keyCode;
							GM_setValue2("hotkeymap",implode(hotkeymap),58);
						},false);
						createElement("td",{},newtr,texte["hotkeymap"][tr]);
					}
					newtable=null;newtr=null;newtd=null;newinput=null;newdiv=null;
				},false);

				//CSS
				newdiv=createElement("div",{"class":"link hoverBgLightbrown","style":"padding-top:5px;border-bottom:1px solid #685338;"},$("infoPanelL"),"CSS");
				newdiv.addEventListener("click",function(){
					var newdiv=$("infoPanelT");
					newdiv.innerHTML="<span><b>CSS</b>&nbsp;-&nbsp;"+texte["berater"]+"&nbsp;"+VERSION+"</span>";
					if(VERSION!=updateCheck[1]){
						newdiv=createElement("span",{"class":"link","style":"margin-left:4px;"},newdiv,"(&rarr;"+updateCheck[1]+")");
						newdiv.addEventListener("click",function(){
							location.href=USO_Source;
						},false);
					}
					$("infoPanelR").innerHTML="";

					var newtable=createElement("table",{"align":"center"},$("infoPanelR"));
					var newtr,newtd,newinput;
					for(var v in css_styles){
						if(!css_styles.hasOwnProperty(v)){ continue; }
						newtr=createElement("tr",{},newtable);
						createElement("td",{},newtr,v);
						newtd=createElement("td",{},newtr);
						var help=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_"+v,css_styles[v][1]);
						newinput=createElement("input",{"name":v,"value":help,"class":"text","style":"width:250px;"},newtd);
						newinput.addEventListener("keyup",function(){
							var v=this.getAttribute("name");
							if(this.value==""){ this.value=css_styles_init[v][1]; }
							css_styles[v][1]=this.value;
							var help=css_styles[v][1];
							for(var w=0;w<css_styles[v][0].length;w++){
								help=css_styles[css_styles[v][0][w]][1]+help;
							}
							this.parentNode.nextSibling.firstElementChild.setAttribute("style",help);
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_css_styles",implode(css_styles));
						},false);
						newtd=createElement("td",{},newtr);
						for(var w=0;w<css_styles[v][0].length;w++){
							help=css_styles[css_styles[v][0][w]][1]+help;
						}
						newdiv=createElement("div",{"style":help},newtd,"test");
					}
					newtable=null;newtr=null;newtd=null;newinput=null;newdiv=null;
				},false);

				//Data Import
				newdiv=createElement("div",{"class":"link hoverBgLightbrown","style":"padding-top:5px;border-bottom:1px solid #685338;"},$("infoPanelL"),"Import/Export");
				newdiv.addEventListener("click",function(){
					function showExportData(showData,onlyThisAccount){
						// if (showData&&(!onlyThisAccount)){
						// 	if(!confirm("Attention! Showing all data of all accounts can slow down your browser. Continue?")){
						// 		showData=false;
						// 	}
						// }
						var container=$("beraterDataImportContainer");
						container.innerHTML="";
						createElement("div",{},container,"Click the lines to remove them.");

						var newdiv=createElement("div",{},container);
						var newinput=createElement("input",{"type":"checkbox","checked":showData},newdiv);
						newinput.addEventListener("click",function(){
							showExportData(this.checked,onlyThisAccount);
						},false);
						createElement("span",{},newdiv,"Show the data");

						newdiv=createElement("div",{},container);
						newinput=createElement("input",{"type":"checkbox","checked":onlyThisAccount},newdiv);
						newinput.addEventListener("click",function(){
							showExportData(showData,this.checked);
						},false);
						createElement("span",{},newdiv,"Only this account");

						newinput=createElement("button",{"class":"link"},container,"Create string!");
						newinput.addEventListener("click",function(){
							var save="";
							var help=$("beraterDataImportContainer").getElementsByTagName("tr");
							for(var v=0;v<help.length;v++){
								var help2=help[v].getElementsByTagName("td");
								save += help2[0].innerHTML+":"+help2[1].innerHTML+":"+help2[2].firstElementChild.innerHTML+"::";
							}
							prompt("Copy this string to a text-file", save.slice(0,save.length-2));
						},false);
						var newtable=createElement("table",{"border":"1","class":"hoverRowBgCc9","style":"width:100%"},container);
						var newtr,newtd;
						var help=GM_listValues();
						help.sort();
						if(onlyThisAccount){
							for(var v=0;v<help.length;v++){
								if(help[v].search(LNG+"_"+SERVER+"_"+USERNAME)!=-1){
									var help2=GM_getValue(help[v]);
									var help3="s";
									if(help2==""){ help2=" "; }
									if(typeof help2=="number"){ help3="n"; }
									else if(typeof help2=="boolean"){ help3="b"; }
									else{ help2=help2.replace(/(:+)/g,":"); }
									newtr=createElement("tr",{},newtable);
									newtr.addEventListener("click",function(){ removeElement(this); },false);
									createElement("td",{},newtr,help[v].replace(LNG+"_"+SERVER+"_"+USERNAME+"_",""));
									createElement("td",{},newtr,help3);
									newtd=createElement("td",{"style":(showData?"":"display:none;")},newtr);
									createElement("div",{"style":"max-height:100px;width:270px;overflow:auto;"},newtd,help2);
								}
							}
						}else{
							for(var v=0;v<help.length;v++){
								var help2=GM_getValue(help[v]);
								var help3="s";
								if(help2==""){ help2=" "; }
								if(typeof help2=="number"){ help3="n"; }
								else if(typeof help2=="boolean"){ help3="b"; }
								else{ help2=help2.replace(/(:+)/g,":"); }
								newtr=createElement("tr",{},newtable);
								newtr.addEventListener("click",function(){ removeElement(this); },false);
								createElement("td",{},newtr,help[v]);
								createElement("td",{},newtr,help3);
								newtd=createElement("td",{"style":(showData?"":"display:none;")},newtr);
								createElement("div",{"style":"max-height:100px;width:270px;overflow:auto;"},newtd,help2);
							}
						}
						container=null;newdiv=null;newtable=null;newtr=null;newtd=null;newinput=null;
					}
					function showImportData(showData,onlyThisAccount){
						var container=$("beraterDataImportContainer");
						container.innerHTML="";
						createElement("div",{},container,"Click the lines to remove them.");

						var newdiv=createElement("div",{},container);
						var newinput=createElement("input",{"type":"checkbox","checked":showData},newdiv);
						newinput.addEventListener("click",function(){
							showImportData(this.checked,onlyThisAccount);
						},false);
						createElement("span",{},newdiv,"Show the data");

						newdiv=createElement("div",{},container);
						newinput=createElement("input",{"type":"checkbox","checked":onlyThisAccount},newdiv);
						newinput.addEventListener("click",function(){
							showImportData(showData,this.checked);
						},false);
						createElement("span",{},newdiv,"Only this account");

						newinput=createElement("button",{"class":"link"},container,"Enter data-string");
						newinput.addEventListener("click",function(){
							var promptdata=prompt("Please enter the data-string","");
							if(promptdata){
								var container=$("beraterDataImportContainer");
								var newtable=container.getElementsByTagName("table");
								if(newtable[0]){ removeElement(newtable[0]); }
								newtable=createElement("table",{"border":"1","class":"hoverRowBgCc9","style":"width:100%"},container);
								var newtr,newtd;
								var help=promptdata.split("::");
								for(var v=0;v<help.length;v++){
									var help2=help[v].split(":");
									var impName=(onlyThisAccount?LNG+"_"+SERVER+"_"+USERNAME+"_":"")+help2.splice(0,1)[0];
									var impType=help2.splice(0,1)[0];
									var impContent=help2.join(":");
									if(impContent==" "){ impContent=""; }
									if((impType=="n")||(impType=="b")||(impType=="s")){
										newtr=createElement("tr",{},newtable);
										newtr.addEventListener("click",function(){ removeElement(this); },false);
										createElement("td",{},newtr,impName);
										createElement("td",{},newtr,impType);
										newtd=createElement("td",{"style":(showData?"":"display:none;")},newtr);
										createElement("div",{"style":"max-height:100px;width:280px;overflow:auto;"},newtd,impContent);
									}
								}
								container=null;newtable=null;newtr=null;newtd=null;
							}
						},false);
						newinput=createElement("button",{"class":"link"},container,"Import this!");
						newinput.addEventListener("click",function(){
							var help=$("beraterDataImportContainer").getElementsByTagName("tr");
							for(var v=0;v<help.length;v++){
								var help2=help[v].getElementsByTagName("td");
								switch(help2[1].innerHTML){
								case "n": GM_setValue2(help2[0].innerHTML,parseInt(help2[2].getElementsByTagName("div")[0].innerHTML,10),59);break;
								case "b": GM_setValue2(help2[0].innerHTML,help2[2].getElementsByTagName("div")[0].innerHTML=="true",60);break;
								case "s": GM_setValue2(help2[0].innerHTML,help2[2].getElementsByTagName("div")[0].innerHTML,61);break;
								}
							}
							alert2("done",texte["ok"]);
						},false);
					}
					var newdiv=$("infoPanelT");
					newdiv.innerHTML="<span><b>Settings Import/Export</b>&nbsp;-&nbsp;"+texte["berater"]+"&nbsp;"+VERSION+"</span>";
					if(VERSION!=updateCheck[1]){
						newdiv=createElement("span",{"class":"link","style":"margin-left:4px;"},newdiv,"(&rarr;"+updateCheck[1]+")");
						newdiv.addEventListener("click",function(){
							location.href=USO_Source;
						},false);
					}
					$("infoPanelR").innerHTML="";
					var newinput=createElement("div",{"id":"beraterDataImportModeExport","class":"link","style":"display:inline-block;width:49%;text-align:center;border:1px solid black;"},$("infoPanelR"),"Export");
					newinput.addEventListener("click",function(){
						this.style.backgroundColor="green";
						$("beraterDataImportModeImport").style.backgroundColor="";
						showExportData(false,true);
					},false);
					newinput=createElement("div",{"id":"beraterDataImportModeImport","class":"link","style":"display:inline-block;width:49%;text-align:center;border:1px solid black;"},$("infoPanelR"),"Import");
					newinput.addEventListener("click",function(){
						this.style.backgroundColor="green";
						$("beraterDataImportModeExport").style.backgroundColor="";
						showImportData(false,true);
					},false);
					createElement("div",{"id":"beraterDataImportContainer"},$("infoPanelR"));
					newinput=null;newdiv=null;
				},false);
			}
			break;
			case "zonen":{
				var totalPunkte=0;

				newtable=createElement("table",{"style":"width:100%" ,"border":"1"},infoPanelInner);
				for(var farms=0;farms<top.window.wrappedJSObject.farmamount;farms++){
					newtr=createElement("tr",{},newtable);
					newtd=createElement("th",{"colspan":"6","class":"link hoverBgCc9"},newtr,texte["farm"]+" "+(farms+1));
					newtd.addEventListener("click",function(){
						closeInfoPanel();
						top.window.wrappedJSObject.initZones(this.innerHTML.replace(texte["farm"]+" ",""));
						top.window.wrappedJSObject.showMain();
					},false);
					for(var z=1;z<7;z++){
						var zf=z+6*farms;
						if (z%3==1) newtr=createElement("tr",{},newtable);
						newtd=createElement("td",{"colspan":"2","style":"width:33%;","zf":zf},newtr);
						if (zoneTyp[zf]!=0){
							newdiv=createElement("div",{"style":"position:relative;top:0;height:60px;overflow:hidden;"},newtd);
							createElement("div",{"class":"bm"+zoneTyp[zf],"style":"position:absolute;top:-20px;opacity:0.3;z-index:-1;"},newdiv);
							newdiv1=createElement("div",{"style":"position:absolute;top:0;height:60px;width:100%;overflow:auto;"},newdiv);
							newdiv=createElement("div",{},newdiv1);
							if (!zoneBlock[zf]&&(BUILDINGTYPE[zoneTyp[zf]]>0)){
								newtd.setAttribute("class","link hoverBgCc9");
								newtd.addEventListener("click",function(){
									closeInfoPanel();
									goToFarmZone(parseInt(this.getAttribute("zf"),10));
								},false);
								if (zoneEndTimes[zf]!=NEVER){
									var endDay=countDays(now,zoneEndTimes[zf]);
									if (endDay == 0) newdiv.innerHTML=getDaytimeStr(zoneEndTimes[zf],1)+"&nbsp;"+texte["uhr"];
									else if (texte["day"+endDay]) newdiv.innerHTML=texte["day"+endDay]+" "+getDaytimeStr(zoneEndTimes[zf],1)+"&nbsp;"+texte["uhr"];
									else newdiv.innerHTML=new Date(1000*zoneEndTimes[zf]).toLocaleString();
								}else{ newdiv.innerHTML=texte["unbeschaeftigt"];}
								if (zoneEndTimes[zf]<now){
									newdiv.style.textDecoration="blink";
									newdiv.style.fontWeight="bold";
								}
								var points=0;
								for(var k=0;k<zoneErnte[zf].length;k++){
									newdiv=createElement("div",{"style":"line-height:16px;"},newdiv1);
									produktPic(zoneErnte[zf][k][0],zoneErnte[zf][k][1],newdiv);
									createElement("div",{"style":"display:inline-block;"},newdiv,zoneErnte[zf][k][2]+" "+prodName[zoneErnte[zf][k][0]][zoneErnte[zf][k][1]]);
									points += zoneErnte[zf][k][3];
								}
								pointsFormat(points,"div",newdiv1);
								totalPunkte += points;
							}else{
								newdiv.innerHTML="---";
							}
						}else{
							newtd.innerHTML="---";
						}
					}
				}

				newtr=createElement("tr",{},newtable);
				createElement("th",{"colspan":"3"},newtr,texte["total"]);
				newtd=createElement("th",{"colspan":"3","class":"link hoverBgCc9"},newtr,texte["fehlt"]);
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["zumSGH"]); },false);
				newtd.addEventListener("click",showSGH,false);
				newtr=createElement("tr",{},newtable);
				newtd=createElement("td",{"colspan":"3"},newtr);
				calcTotalErnte();
				for(var k in totalErnte[0]){
					if(!totalErnte[0].hasOwnProperty(k)){ continue; }
					newdiv=createElement("div",{"style":"height:16px"},newtd);
					produktPic(0,k,newdiv);
					createElement("div",{"style":"display:inline-block;"},newdiv,numberFormat(totalErnte[0][k])+" "+prodName[0][k]);
				}
				pointsFormat(totalPunkte,"div",newtd);

				var newtdfehlt=createElement("td",{"colspan":"3"},newtr);

				//Farmi-Uebersicht
				newtable=createElement("table",{"style":"margin-top:10px;width:100%","border":"1"});
				newtr=createElement("tr",{"style":"color:black"},newtable);
				createElement("th",{},newtr,texte["farmi"]);
				createElement("th",{},newtr,texte["produkte"]);
				createElement("th",{},newtr,texte["geld"]);
				createElement("th",{"colspan":"2"},newtr,texte["wert"]);
				var farmiNr=-1;
				var farmiCount=0;
				var farmiSum=new Object;
				var farmiCash=0;
				var farmiWert=0;
				while (top.window.wrappedJSObject.farmisinfo[0][++farmiNr]){
					if (!top.window.wrappedJSObject.farmisaway[farmiNr]){
					farmiCount++;
					newtr=createElement("tr",{},newtable);
					newtd=createElement("td",{"class":"link hoverBgCc9","name":farmiNr},newtr);
					var farmiGfxNr=top.window.wrappedJSObject.farmisinfo[0][farmiNr]["pic"];
					createElement("img",{"src":GFX+"verkauf/kunde_"+farmiGfxNr+"_still.gif","style":"width:"+FARMISIZE[farmiGfxNr][0]+"px;height:"+FARMISIZE[farmiGfxNr][1]+"px;"},newtd);
					newtd.addEventListener("click",function(){
						closeInfoPanel();
						if ($("citymaincontainer").style.display=="block"){
							unsafeWindow.initZones(1);
							unsafeWindow.showMain();
						}
						unsafeWindow.showCart(parseInt(this.getAttribute("name"),10));
					},false);
					newtd=createElement("td",{},newtr);
					var cash=parseFloat(top.window.wrappedJSObject.farmisinfo[0][farmiNr]["price"],10);
					var wert=0;
					for(var i=1 ; i <= 7 ; i++){ // 7=maxanzahl produkte pro farmi
						var pid=parseInt(top.window.wrappedJSObject.farmisinfo[0][farmiNr]["p"+i],10);
						var amount=parseInt(top.window.wrappedJSObject.farmisinfo[0][farmiNr]["a"+i],10);
						if((pid > 0) && (amount > 0)){
							newdiv=createElement("div",{},newtd);
							produktPic(0,pid,newdiv);
							newdiv1=createElement("div",{"class":"link hoverBgCc9","style":"display:inline-block;"+(prodStock[0][pid]<amount?"color:red;":""),"prod":pid},newdiv,numberFormat(amount)+"&nbsp;"+prodName[0][pid]);
							newdiv1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
							newdiv1.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
							if (farmiSum[pid]) farmiSum[pid] += amount;
							else farmiSum[pid]=amount;
							wert += amount*gut[pid];
						}
					}
					farmiCash += cash;
					farmiWert += wert;
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{},newtd,moneyFormat(cash));
						createElement("div",{},newtd,numberFormat(100*cash/wert,1)+"%");
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						newdiv=createElement("div",{},newtd,moneyFormat(wert));
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"100%"); },false);
						newdiv=createElement("div",{},newtd,moneyFormat(0.9*wert));
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"90%"); },false);
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						newdiv=createElement("div",{},newtd,(cash>wert?"+":"")+moneyFormatInt(cash-wert));
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"100%"); },false);
						newdiv=createElement("div",{},newtd,(cash>0.9*wert?"+":"")+moneyFormatInt(cash-0.9*wert));
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"90%"); },false);
					}
				}
				if (farmiCount>0){
					infoPanelInner.appendChild(newtable);
					if (farmiCount>1){
						newtr.setAttribute("class","borderBottom2");
						newtr=createElement("tr",{"class":"borderTop2"},newtable);
						createElement("td",{},newtr);
						newtd=createElement("td",{},newtr);
						for(var v in farmiSum){
							if(!farmiSum.hasOwnProperty(v)){ continue; }
							newdiv=createElement("div",{},newtd);
							produktPic(0,v,newdiv);
							createElement("div",{"style":"display:inline-block;"},newdiv,numberFormat(farmiSum[v])+"&nbsp;"+prodName[0][v]);
						}
						newtd=createElement("td",{"style":"text-align:right;"},newtr);
							createElement("div",{},newtd,moneyFormat(farmiCash));
							createElement("div",{},newtd,numberFormat(100*farmiCash/farmiWert,1)+"%");
						newtd=createElement("td",{"style":"text-align:right;"},newtr);
							newdiv=createElement("div",{},newtd,moneyFormat(farmiWert));
							newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"100%"); },false);
							newdiv=createElement("div",{},newtd,moneyFormat(0.9*farmiWert));
							newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"90%"); },false);
						newtd=createElement("td",{"style":"text-align:right;"},newtr);
							newdiv=createElement("div",{},newtd,(farmiCash>farmiWert?"+":"")+moneyFormatInt(farmiCash-farmiWert));
							newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"100%"); },false);
							newdiv=createElement("div",{},newtd,(farmiCash>0.9*farmiWert?"+":"")+moneyFormatInt(farmiCash-0.9*farmiWert));
							newdiv.addEventListener("mouseover",function(event){ showToolTip(event,"90%"); },false);
					}
				}
				for(var w=0;w<prodNameSort[0].length;w++){
					var v=prodNameSort[0][w];
					if((!prodBlock[0][v].match(/t/))&&(!prodBlock[0][v].match(/l/))){
						var amount1=(farmiSum[v]?farmiSum[v]:0)-prodStock[0][v];
						var amount=amount1+prodMinRack[0][v];
						if (amount>0){
							newdiv=createElement("div",{},newtdfehlt);
							produktPic(0,v,newdiv);
							newdiv1=createElement("div",{"style":"display:inline-block;","class":"link hoverBgCc9","name":v},newdiv,numberFormat(amount)+(amount1>0?"&nbsp;("+numberFormat(amount1)+")":"")+"&nbsp;"+prodName[0][v]);
							newdiv1.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,this.getAttribute("name"));},false);
							newdiv1.addEventListener("click",function(){showMarket(this.getAttribute("name"));},false);
						}
					}
				}
				newtdfehlt=null;
			}
			break;
			case "profit":{
				// data
				//var imgStarBlack="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAOCAIAAAB7HQGFAAAABnRSTlMA/wD/AP83WBt9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAATUlEQVR4nJ2RQQrAQAgDN/7/z9OD0C6NtGE9jnEgKGAFU44kRbnI1zJXpr6V9ADqN9rb+rbevByN5Ml5x50MfQF3q1GfvtY71Pl/x7kAn0stADSCq8MAAAAASUVORK5CYII=";
				var imgStarGrey="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAOCAIAAAB7HQGFAAAABnRSTlMA/wD/AP83WBt9AAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAVklEQVR4nJ2RUQrAMAhDp3fMKT1k9iGs0tgiy4/wGqNFI/kM5IoiYuQb5WWYRk7zjGS7UBUAz3I3rbkn68ddUUuWT7espPkvAM22vFu2bs8V2v/7tnoB7YUnCmjChpYAAAAASUVORK5CYII=";
				var perc=0.9;
				var showAll=false;
				var sortMode=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittable","gut");

				newdiv=createElement("div",{"style":"text-align:center;height:20px;width:100%;"},infoPanelInner);
				createElement("span",{"style":"font-weight:bold;"},newdiv,texte["profitTable"]);
				newspan=createElement("span",{"style":"margin-left:50px;"},newdiv);
				newinput=createElement("input",{"type":"checkbox","class":"link","checked":(perc==0.9)},newspan);
				newinput.addEventListener("click",function(){
					perc=this.checked?0.9:1;
					buildProfitTable();
				},false);
				createElement("span",{},newspan,"90%");
				newinput=createElement("input",{"type":"checkbox","class":"link","checked":showAll},newdiv);
				newinput.addEventListener("click",function(){
					showAll=this.checked;
					buildProfitTable();
				},false);
				createElement("span",{},newdiv,texte["showAll"]);
				newdiv=createElement("div",{"style":"height:495px;width:100%;overflow:auto;"},infoPanelInner);
				createElement("table",{},newdiv);
				function buildProfitTable(jumpTo){
				try{
					var err_trace="init";
					//GM_log("buildProfitTable "+sortMode+":"+perc+":"+showAll+":"+jumpTo);
					var sterne=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableSterne","[]"),"buildProfitTable/modeProfittableSterne",[]);
					if(!(sterne instanceof Array)){ sterne=new Array(); }
					if(!sterne[1]){ sterne[1]=0; }
					if(!showAll){
						while((sterne[1]>0)&&(USERLEVEL<BUILDING_UPGRADES[1][sterne[1]][0])){ sterne[1]--; }
					}
					// [alternative, fully fed(0/1)]
					var valFutterMode=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableFeed","{}"),"buildProfitTable/modeProfittableFeed",{});
					err_trace="calc array";
					var profit=new Array();
					var c=-1;
					var currBuilding;
					for(var v=0;v<prodName[0].length;v++){ if((showAll||(!prodBlock[0][v])) && (prodGrowTime[0][v])){
						if (prodTyp[0][v]=="v"){
							var bonus=BUILDING_UPGRADES[1][sterne[1]][2];
							if(questData["farm"]["1"]["nr"]>170){ bonus-=0.05; }
							profit[++c]=new Object();
							profit[c]["id"]=v;
							profit[c]["dauer"]=calcProductionTime(1,0,v,bonus); //calcGrowDuration(60*prodGrowTime[0][v],BUILDING_UPGRADES[1][sterne[1]][2]);
							profit[c]["runs"]=calcGrowTimes(60*prodGrowTime[0][v],86400,BUILDING_UPGRADES[1][sterne[1]][2]);
							profit[c]["punkte"]=prodPoints[0][v]*profit[c]["runs"]*120/prodPlantSize[0][v];
							profit[c]["menge"]=(prodYield[0][v]-1)*profit[c]["runs"]*120/prodPlantSize[0][v];
							profit[c]["gut"]=perc*gut[v]*profit[c]["menge"];
							profit[c]["gutBeob"]=perc*(gutBeob[v]?gutBeob[v]:0)*profit[c]["menge"];
						}else if ((prodTyp[0][v]=="e")||(prodTyp[0][v]=="o")){
							profit[++c]=new Object();
							profit[c]["id"]=v;
							currBuilding=PRODUCT2BUILDING[0][v];
							if(!sterne[currBuilding]){ sterne[currBuilding]=0; }
							profit[c]["level"]=sterne[currBuilding];
							profit[c]["maxlevel"]=BUILDING_UPGRADES[currBuilding].length-1;
							if(!showAll){
								while((profit[c]["maxlevel"]>0)&&(USERLEVEL<BUILDING_UPGRADES[currBuilding][profit[c]["maxlevel"]][0])){ profit[c]["maxlevel"]--; }
								profit[c]["level"]=Math.min(profit[c]["level"],profit[c]["maxlevel"]);
							}
							var bonus=BUILDING_UPGRADES[currBuilding][profit[c]["level"]][2];
							// profit[c]["dauer"]=60*prodGrowTime[0][v]*bonus;
							// profit[c]["runs"]=86400/profit[c]["dauer"];
							if(!valFutterMode[v]){ valFutterMode[v]=[0,0]; }
							if(typeof valFutterMode[v][0]!="number"){ valFutterMode[v][0]=0; }
							if(typeof valFutterMode[v][1]!="number"){ valFutterMode[v][1]=0; }
							var help=[];
							if(BUILDINGTYPE[currBuilding]==2){ // Stable
								profit[c]["input"]=[];
								for(var alt=0;alt<BUILDING_INPUT[currBuilding][v].length;alt++){
									profit[c]["input"][alt]=[[],[]];
									help[alt]=[];
									help[alt][0]=calcProductionTime(2,0,v,bonus,BUILDING_INPUT[currBuilding][v][alt][0][1]/BUILDING_UPGRADES[currBuilding][profit[c]["level"]][3]);
									help[alt][1]=calcProductionTime(2,0,v,bonus,BUILDING_INPUT[currBuilding][v][alt][0][1]/BUILDING_UPGRADES[currBuilding][profit[c]["level"]][3],1);
									for(var i=0;i<BUILDING_INPUT[currBuilding][v][alt].length;i++){
										var currInput=BUILDING_INPUT[currBuilding][v][alt][i];
										var preis=(isNaN(NPC[0][currInput[0]])?gut[currInput[0]]:Math.min(NPC[0][currInput[0]],gut[currInput[0]]));
										var preisBeob=(isNaN(NPC[0][currInput[0]])?(gutBeob[currInput[0]]?gutBeob[currInput[0]]:0):Math.min(NPC[0][currInput[0]],(gutBeob[currInput[0]]?gutBeob[currInput[0]]:0)));
										var menge=help[alt][1][1]*86400/help[alt][1][0];
										//profit[c]["runs"];
										profit[c]["input"][alt][1][i]=[currInput[0],menge,menge*preis,menge*preisBeob];
										// var menge=profit[c]["runs"]*Math.floor(profit[c]["dauer"]*BUILDING_UPGRADES[currBuilding][profit[c]["level"]][3]/currInput[1]);
										var menge=help[alt][0][1]*86400/help[alt][0][0];
										profit[c]["input"][alt][0][i]=[currInput[0],menge,menge*preis,menge*preisBeob];
									}
								}
								// if(valFutterMode[v][1]==0){
								// 	profit[c]["dauer"] *= 0.5;
								// 	profit[c]["runs"] *= 2;
								// }
							}else if(BUILDINGTYPE[currBuilding]==3){ // Factory
								profit[c]["input"]=[];
								for(var alt=0;alt<BUILDING_INPUT[currBuilding][v].length;alt++){
									profit[c]["input"][alt]=[[]];
									help[alt]=[];
									help[alt][0]=[calcProductionTime(3,0,v,bonus)];
									for(var i=0;i<BUILDING_INPUT[currBuilding][v][alt].length;i++){
										var currInput=BUILDING_INPUT[currBuilding][v][alt][i];
										var preis=(isNaN(NPC[0][currInput[0]])?gut[currInput[0]]:Math.min(NPC[0][currInput[0]],gut[currInput[0]]));
										var preisBeob=(isNaN(NPC[0][currInput[0]])?(gutBeob[currInput[0]]?gutBeob[currInput[0]]:0):Math.min(NPC[0][currInput[0]],(gutBeob[currInput[0]]?gutBeob[currInput[0]]:0)));
										var menge=currInput[1]*86400/help[alt][0][0];
										profit[c]["input"][alt][0][i]=[currInput[0],menge,menge*preis,menge*preisBeob];
									}
								}
							}
							if(!help[valFutterMode[v][0]]){ valFutterMode[v][0]=0; }
							if(!help[valFutterMode[v][0]][valFutterMode[v][1]]){ valFutterMode[v][1]=0; }
							profit[c]["dauer"] = help[valFutterMode[v][0]][valFutterMode[v][1]][0];
							profit[c]["runs"]=86400/profit[c]["dauer"];
							profit[c]["menge"] = profit[c]["runs"]*BUILDING_UPGRADES[currBuilding][profit[c]["level"]][3]*prodYield[0][v];
							profit[c]["punkte"]=profit[c]["menge"]*prodPoints[0][v];
							var help=profit[c]["input"][valFutterMode[v][0]][valFutterMode[v][1]];
							profit[c]["gut"]=profit[c]["menge"]*perc*gut[v];
							profit[c]["gutBeob"]=profit[c]["menge"]*perc*(gutBeob[v]?gutBeob[v]:0);
							for(var i=0;i<help.length;i++){
								profit[c]["gut"]-=help[i][2];
								profit[c]["gutBeob"]-=help[i][3];
							}
							profit[c]["gut"]=profit[c]["gut"];
							profit[c]["gutBeob"]=profit[c]["gutBeob"];
						}
						// GM_log(prodName[0][v]+":"+implode(profit[c]));
					}}
					profit.sort(function (a,b){return b[sortMode] - a[sortMode];});

					err_trace="table";
					var oldtable=$("infoPanelInner").getElementsByTagName("table")[0];
					var newtable=createElement("table",{"cellspacing":"0","border":"1","width":"100%;"});
					oldtable.parentNode.replaceChild(newtable,oldtable);
					oldtable=null;
					newtable.addEventListener("mouseover",function(event){
						var node=event.target;
						var mouseOverText=node.getAttribute("mouseOverText");
						while((node!=this)&&(!mouseOverText)){
							node=node.parentNode;
							mouseOverText=node.getAttribute("mouseOverText");
						}
						if(mouseOverText){ showToolTip(event,mouseOverText); }
						node=null;mouseOverText=null;
					},false);
					var newthead=createElement("thead",{},newtable);
					var newtbody=createElement("tbody",{},newtable);

					err_trace="tablehead";
					var newtr=createElement("tr",{"style":"color:black;"},newthead);
					var newtd=createElement("th",{"mouseOverText":"<table class='white' cellspacing=0><tr><th style='border-bottom:1px solid white;'>"+unsafeWindow.buildinginfos[0][1][10]+"</th></tr><tr><td>"+(unsafeWindow.garden_waterbonus.replace(/%BONUS%/,"").replace(/\%/g,"").replace(/:/g,""))+"</td></tr><tr><td>("+texte["clickToChange"]+")</td></tr></table>","class":"link"},newtr);
					newtd.addEventListener("click",function(){
						var c=BUILDING_UPGRADES[1].length-1;
						if(!showAll){
							while((c>0)&&(USERLEVEL<BUILDING_UPGRADES[1][c][0])){ c--; }
						}
						sterne[1]=(sterne[1]+1)%(c+1);
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableSterne",implode(sterne),62);
						buildProfitTable();
					},false);
					if(questData["farm"]["1"]["nr"]>170){ createElement("span",{},newtd,"5%+"); }
					createElement("span",{},newtd,Math.round(100*(1-BUILDING_UPGRADES[1][sterne[1]][2]))+"%");
					for(var v=0;v<BUILDING_UPGRADES[1].length;v++){
						if(showAll||(USERLEVEL>=BUILDING_UPGRADES[1][v][0])){
							createElement("img",{"mouseOverText":"<table class='white' cellspacing=0><tr><th style='border-bottom:1px solid white;'>"+unsafeWindow.buildinginfos[0][1][10]+"</th></tr><tr><td>"+texte["ausbaustufe"]+"</td></tr><tr><td>("+texte["clickToChange"]+")</td></tr></table>","src":v<=sterne[1]?GFX+"star.png":imgStarGrey},newtd);
						}
					}
					newtd=createElement("th",{"class":"link hoverBgCc9"+(sortMode=="dauer"?" sortableColDesc":"")},newtr,texte["dauer"]);
					newtd.addEventListener("click",function(){
						sortMode="dauer";
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittable",sortMode,63);
						buildProfitTable();
					},false);
					newtd=createElement("th",{},newtr);
					newtd=createElement("th",{"class":"link hoverBgCc9"+(sortMode=="punkte"?" sortableColDesc":"")},newtr,texte["punkte"]);
					newtd.addEventListener("click",function(){
						sortMode="punkte";
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittable",sortMode,64);
						buildProfitTable();
					},false);
					newtd=createElement("th",{"class":"link hoverBgCc9"+(sortMode=="gut"?" sortableColDesc":"")},newtr,texte["preise"]);
					newtd.addEventListener("click",function(){
						sortMode="gut";
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittable",sortMode,65);
						buildProfitTable();
					},false);
					newtd=createElement("th",{"class":"link hoverBgCc9"+(sortMode=="gutBeob"?" sortableColDesc":"")},newtr,texte["beobachtet"]);
					newtd.addEventListener("click",function(){
						sortMode="gutBeob";
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittable",sortMode,66);
						buildProfitTable();
					},false);

					err_trace="tablebody";
					var newspan,newdiv,newtable1,newtr1,newtd1;
					for(var v=0;v<profit.length;v++){
						var buildingNr=PRODUCT2BUILDING[0][profit[v]["id"]];
						newtr=createElement("tr",{"nr":v,"prod":profit[v]["id"],"class":"hoverBgCc9","style":"color:black;"},newtbody);
						newtd=createElement("td",{},newtr);
						newtd=createElement("div",{"style":"position:relative;height:100%;"},newtd);
						produktPic(0,profit[v]["id"],newtd);
							newdiv=createElement("div");
							newtable1=createElement("table",{"cellspacing":0,"class":"white"},newdiv);
							newtr1=createElement("tr",{},newtable1);
							createElement("th",{"colspan":2,"style":"border-bottom:1px solid white;"},newtr1,texte["goToMarketOfX"].replace(/%1%/,prodName[0][profit[v]["id"]]));
							newtr1=createElement("tr",{},newtable1);
							createElement("td",{},newtr1,texte["bestand"]);
							createElement("td",{},newtr1,numberFormat(prodStock[0][profit[v]["id"]]));
							newtr1=createElement("tr",{},newtable1);
							createElement("td",{},newtr1,texte["dailyYield"]);
							createElement("td",{},newtr1,numberFormat(profit[v]["menge"],1));
							newtr1=createElement("tr",{},newtable1);
							createElement("td",{},newtr1,texte["yield"]);
							createElement("td",{},newtr1,numberFormat(profit[v]["menge"]/profit[v]["runs"]));
							newtr1=createElement("tr",{},newtable1);
							createElement("td",{},newtr1,texte["dailyRuns"]);
							createElement("td",{},newtr1,numberFormat(profit[v]["runs"],3));
						newspan=createElement("span",{"class":"link","mouseOverText":newdiv.innerHTML},newtd,prodName[0][profit[v]["id"]]);
						newspan.addEventListener("click",function(){showMarket(profit[this.parentNode.parentNode.parentNode.getAttribute("nr")]["id"]);},false);
						if(typeof profit[v]["level"]=="number"){
							newspan=createElement("span",{"mouseOverText":"<table class='white' cellspacing=0><tr><th style='border-bottom:1px solid white;'>"+unsafeWindow.buildinginfos[0][buildingNr][10]+"</th></tr><tr><td>"+texte["ausbaustufe"]+"</td></tr><tr><td>("+texte["clickToChange"]+")</td></tr></table>","class":"link"},newtd); // ,"mouseOverText":"max "+profit[v]["maxlevel"]
							for(var w=0;w<=profit[v]["maxlevel"];w++){ createElement("img",{"src":w<=profit[v]["level"]?GFX+"star.png":imgStarGrey},newspan); }
							newspan.addEventListener("click",function(){
								var currNr=this.parentNode.parentNode.parentNode.getAttribute("nr");
								sterne[PRODUCT2BUILDING[0][profit[currNr]["id"]]]=(profit[currNr]["level"]+1)%(profit[currNr]["maxlevel"]+1);
								GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableSterne",implode(sterne),67);
								buildProfitTable(profit[currNr]["id"]);
							},false);

							newspan=produktPic(0,profit[v]["input"][valFutterMode[profit[v]["id"]][0]][valFutterMode[profit[v]["id"]][1]][0][0],newtd);
							newdiv=createElement("div");
							newtable1=createElement("table",{"cellspacing":0,"class":"white"},newdiv);
							newtr1=createElement("tr",{},newtable1);
							createElement("th",{"colspan":2,"style":"border-bottom:1px solid white;"},newtr1,unsafeWindow.buildinginfos[0][buildingNr][10]);
							newtr1=createElement("tr",{},newtable1);
							createElement("td",{"colspan":2},newtr1,texte["futter"]+":");
							for(var i=0;i<profit[v]["input"].length;i++){
								for(var j=0;j<profit[v]["input"][i].length;j++){
									newtr1=createElement("tr",{},newtable1);
									var help=((profit[v]["input"].length>1)&&(valFutterMode[profit[v]["id"]][0]==i)&&(valFutterMode[profit[v]["id"]][1]==j))?"background-color:#BB6600;":"";
									createElement("td",{"style":"text-align:right;"+help},newtr1,numberFormat(profit[v]["input"][i][j][0][1],1));
									createElement("td",{"style":help},newtr1,prodName[0][profit[v]["input"][i][j][0][0]]);
								}
							}
							if(profit[v]["input"].length>1){
								newtr1=createElement("tr",{},newtable1);
								createElement("td",{"colspan":2},newtr1,"("+texte["clickToChange"]+")");
								newspan.setAttribute("class",newspan.getAttribute("class")+" link");
								if(1+valFutterMode[profit[v]["id"]][1]<profit[v]["input"][valFutterMode[profit[v]["id"]][0]].length){
									newspan.setAttribute("nextMode",implode([valFutterMode[profit[v]["id"]][0],1+valFutterMode[profit[v]["id"]][1]],"profitTable/nextMode"));
								}else if(1+valFutterMode[profit[v]["id"]][0]<profit[v]["input"].length){
									newspan.setAttribute("nextMode",implode([1+valFutterMode[profit[v]["id"]][0],0],"profitTable/nextMode"));
								}else{
									newspan.setAttribute("nextMode",implode([0,0],"profitTable/nextMode"));
								}
								profit[v]["input"][valFutterMode[profit[v]["id"]][0]][valFutterMode[profit[v]["id"]][1]]
								newspan.addEventListener("click",function(){
									var currId=this.parentNode.parentNode.parentNode.getAttribute("prod");
									var valFutterMode=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableFeed"),"profitTable/valFutterMode",{});
									valFutterMode[currId]=explode(this.getAttribute("nextMode"),"profitTable/nextMode",[0,0]);
									GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeProfittableFeed",implode(valFutterMode));
									buildProfitTable(currId);
								},false);
							}
							newspan.setAttribute("mouseOverText",newdiv.innerHTML);
						}
						createElement("td",{"style":"text-align:right;"},newtr,getTimeStr(profit[v]["dauer"],1));

						createElement("td",{"style":"text-align:right;"},newtr,getDaytimeStr(now+profit[v]["dauer"],1)+"&nbsp;"+texte["uhr"]);
						newdiv=createElement("div");
						newtable1=createElement("table",{"cellspacing":0,"class":"white"},newdiv);
						newtr1=createElement("tr",{},newtable1);
						createElement("th",{"colspan":2,"style":"border-bottom:1px solid white;"},newtr1,unsafeWindow.buildinginfos[0][buildingNr][10]);
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{},newtr1,texte["punkte"]);
						createElement("td",{},newtr1,numberFormat(profit[v]["punkte"]/profit[v]["runs"]));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{},newtr1,texte["dailyRuns"]);
						createElement("td",{},newtr1,numberFormat(profit[v]["runs"],3));
						createElement("td",{"style":"text-align:right;","mouseOverText":newdiv.innerHTML},newtr,numberFormat(profit[v]["punkte"]));

						newdiv=createElement("div");
						newtable1=createElement("table",{"cellspacing":0,"class":"white"},newdiv);
						newtr1=createElement("tr",{},newtable1);
						createElement("th",{"colspan":4,"style":"border-bottom:1px solid white;"},newtr1,unsafeWindow.buildinginfos[0][buildingNr][10]);
						var sum=0;
						if (typeof profit[v]["level"]=="number"){
							var help=profit[v]["input"][valFutterMode[profit[v]["id"]][0]][valFutterMode[profit[v]["id"]][1]];
							for(var j=0;j<help.length;j++){
								sum+=help[j][2]/profit[v]["runs"];
								newtr1=createElement("tr",{},newtable1);
								createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(help[j][1]/profit[v]["runs"]));
								createElement("td",{},newtr1,prodName[0][help[j][0]]);
								createElement("td",{"style":"text-align:right;"},newtr1,"("+moneyFormat(gut[help[j][0]])+")");
								createElement("td",{"style":"text-align:right;"},newtr1,moneyFormatInt(-help[j][2]/profit[v]["runs"]));
							}
						}
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(profit[v]["menge"]/profit[v]["runs"]));
						createElement("td",{},newtr1,prodName[0][profit[v]["id"]]);
						createElement("td",{"style":"text-align:right;"},newtr1,"("+moneyFormat(perc*gut[profit[v]["id"]])+")");
						createElement("td",{"style":"border-bottom:1px solid white;text-align:right;"},newtr1,moneyFormatInt(profit[v]["gut"]/profit[v]["runs"]+sum));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"style":"border-bottom:1px solid white;","colspan":3},newtr1);
						createElement("td",{"style":"border-bottom:1px solid white;text-align:right;"},newtr1,moneyFormatInt(profit[v]["gut"]/profit[v]["runs"]));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"colspan":2},newtr1,texte["dailyRuns"]);
						createElement("td",{"colspan":2},newtr1,numberFormat(profit[v]["runs"],3));
						createElement("td",{"style":"text-align:right;","mouseOverText":newdiv.innerHTML},newtr,moneyFormatInt(profit[v]["gut"]));

						newdiv=createElement("div");
						newtable1=createElement("table",{"cellspacing":0,"class":"white"},newdiv);
						newtr1=createElement("tr",{},newtable1);
						createElement("th",{"colspan":4,"style":"border-bottom:1px solid white;"},newtr1,unsafeWindow.buildinginfos[0][buildingNr][10]);
						var sum=0;
						if (typeof profit[v]["level"]=="number"){
							var help=profit[v]["input"][valFutterMode[profit[v]["id"]][0]][valFutterMode[profit[v]["id"]][1]];
							for(var j=0;j<help.length;j++){
								sum+=help[j][3]/profit[v]["runs"];
								newtr1=createElement("tr",{},newtable1);
								createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(help[j][1]/profit[v]["runs"]));
								createElement("td",{},newtr1,prodName[0][help[j][0]]);
								createElement("td",{"style":"text-align:right;"},newtr1,"("+moneyFormat(gutBeob[help[j][0]])+")");
								createElement("td",{"style":"text-align:right;"},newtr1,moneyFormatInt(-help[j][3]/profit[v]["runs"]));
							}
						}
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(profit[v]["menge"]/profit[v]["runs"]));
						createElement("td",{},newtr1,prodName[0][profit[v]["id"]]);
						createElement("td",{"style":"text-align:right;"},newtr1,"("+moneyFormat(perc*gutBeob[profit[v]["id"]])+")");
						createElement("td",{"style":"border-bottom:1px solid white;text-align:right;"},newtr1,moneyFormatInt(profit[v]["gutBeob"]/profit[v]["runs"]+sum));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"style":"border-bottom:1px solid white;","colspan":3},newtr1);
						createElement("td",{"style":"border-bottom:1px solid white;text-align:right;"},newtr1,moneyFormatInt(profit[v]["gutBeob"]/profit[v]["runs"]));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"colspan":2},newtr1,texte["dailyRuns"]);
						createElement("td",{"colspan":2},newtr1,numberFormat(profit[v]["runs"],3));
						createElement("td",{"style":"text-align:right;","mouseOverText":newdiv.innerHTML},newtr,moneyFormatInt(profit[v]["gutBeob"]));

						if(jumpTo==profit[v]["id"]){
							newtbody.scrollTop=newtr.offsetTop;
							newspan=createElement("div",{"id":"vanishDiv","style":"position:absolute;top:0;left:0;height:15px;width:100%;background-color:blue;opacity:0.7;"},newtr.firstElementChild.firstElementChild);
							var intervalVanishDiv=window.setInterval(function(){
								try{
									var div=$("vanishDiv");
									if(div){
										var opac=parseFloat(div.style.opacity,10)-0.05;
										if(opac>0){ div.style.opacity=opac; }
										else{ 
											removeElement(div);
											window.clearInterval(intervalVanishDiv);
										}
									}else{ window.clearInterval(intervalVanishDiv); }
								}catch(err){}
							},100);
						}
					}
					//makeTablebodyScrollable(newtable,"470px");
					newtable=null;newthead=null;newtbody=null;newtr=null;newtd=null;newspan=null;newdiv=null;newtable1=null;newtr1=null;newtd1=null;
				}catch(err){ GM_log("ERROR buildProfitTable ("+err_trace+")\nv="+v+"\n"+err); }
				}
				buildProfitTable();
			}
			break;
			case "farmiLog":{
				var newFarmiumsatz=new Object();
				var farmiOk=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_farmiOk",95);
				var totalPrice=0;
				var totalWert=0;
				var totalPriceOk=0;
				var totalWertOk=0;
				var countFarmisOk=0;
				var countFarmisAll=0;
				var totalProducts=new Object();

				infoPanelInner.style.width="626px";

				newdiv=createElement("div",{"style":"height:100%;width:595px;overflow:auto;"},infoPanelInner);
				newtable=createElement("table",{"style":"width:100%","border":"1"},newdiv); //scrollTable
				newtable.addEventListener("mouseover",function(event){
					var node=event.target;
					var mouseOverText=node.getAttribute("mouseOverText");
					while((node!=this)&&(!mouseOverText)){
						node=node.parentNode;
						mouseOverText=node.getAttribute("mouseOverText");
					}
					if(mouseOverText){ showToolTip(event,mouseOverText); }
					node=null;mouseOverText=null;
				},false);
				newthead=createElement("thead",{},newtable);
				newtbody=createElement("tbody",{"style":"height:480px;overflow-y:auto;overflow-x:hidden"},newtable);

				// selection bar on the right side
				newdiv1=createElement("div",{"class":"link","style":"position:absolute;top:0;right:0;border:1px solid black;"},infoPanelInner);
				newdiv1.addEventListener("mouseover",function(event){
					var node=event.target;
					var mouseOverText=node.getAttribute("mouseOverText");
					while((node!=this)&&(!mouseOverText)){
						node=node.parentNode;
						mouseOverText=node.getAttribute("mouseOverText");
					}
					if(mouseOverText){ showToolTip(event,mouseOverText); }
					node=null;mouseOverText=null;
				},false);
				for(var v=200;v>-1;v--){
					newdiv=createElement("div",{"class":"hoverBgRed","style":"width:20px;height:2.5px;","mouseOverText":v+"%"},newdiv1);
					if (v<=farmiOk){ newdiv.style.backgroundColor="blue"; }
					if (v==90||v==100) newdiv.style.borderTop="1px solid black";
					newdiv.addEventListener("click",function(){
						GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_farmiOk",parseInt(this.getAttribute("mouseOverText"),10),69);
						$("infoPanel").setAttribute("mode","");
						buildInfoPanel("farmiLog");
					},false);
				}

				// Farmi table
				newtr=createElement("tr",{},newthead);
				createElement("th",{"style":"border-bottom:2px solid black;"},newtr,"");
				createElement("th",{"style":"border-bottom:2px solid black;"},newtr,texte["produkte"]);
				createElement("th",{"style":"border-bottom:2px solid black;"},newtr,texte["geld"]);
				createElement("th",{"style":"border-bottom:2px solid black;","colspan":"2"},newtr,texte["wert"]);

				var borderTop;
				var c=0;
				var prev=null;
				for(var v in farmiLog){
					if(!farmiLog.hasOwnProperty(v)){ continue; }
					countFarmisAll++;
					newtr=createElement("tr",{"class":"hoverBgCc9"},newtbody);
					if (prev==null){
						borderTop="2px solid black;";
						newtd1=createElement("td",{"style":"border-top:"+borderTop},newtr,farmiLog[v][0]);
						c=1;
					}else if (farmiLog[v][0]!=farmiLog[prev][0]){
						borderTop="2px solid black;";
						newtd1.innerHTML += "<br>("+c+")";
						newtd1=createElement("td",{"style":"border-top:"+borderTop},newtr,farmiLog[v][0]);
						c=1;
					}else{
						borderTop="1px solid black;";
						newtd1.rowSpan=++c;
					}
					newtd=createElement("td",{"style":"border-top:"+borderTop},newtr);
					var wert=0;
					for(var w in farmiLog[v][2]){
						if(!farmiLog[v][2].hasOwnProperty(w)){ continue; }
						newdiv=createElement("div",{"style":"line-height:16px;"},newtd);
						produktPic(0,w,newdiv);
						createElement("div",{"style":"display:inline-block;"},newdiv,numberFormat(farmiLog[v][2][w])+"&nbsp;"+prodName[0][w]);
						wert += farmiLog[v][2][w]*gut[w];
					}
					totalPrice += farmiLog[v][1];
					totalWert += wert;
					newtd=createElement("td",{"style":"text-align:right;border-top:"+borderTop},newtr);
						createElement("div",{},newtd,moneyFormatInt(farmiLog[v][1]));
						newdiv=createElement("div",{},newtd,numberFormat(100*farmiLog[v][1]/wert,1)+"%");
						if (100*farmiLog[v][1]>farmiOk*wert){
							countFarmisOk++;
							for(var w in farmiLog[v][2]){
								if(!farmiLog[v][2].hasOwnProperty(w)){ continue; }
								if(totalProducts[w]==undefined){ totalProducts[w]=[0,0]; }
								totalProducts[w][0]++;
								totalProducts[w][1]+=farmiLog[v][2][w];
							}
							totalPriceOk += farmiLog[v][1];
							totalWertOk += wert;

						}else{ newdiv.style.backgroundColor="red"; }
					newtd=createElement("td",{"style":"text-align:right;border-top:"+borderTop},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,moneyFormatInt(wert));
						createElement("div",{"mouseOverText":"90%"},newtd,moneyFormatInt(0.9*wert));
					newtd=createElement("td",{"style":"text-align:right;border-top:"+borderTop},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,(farmiLog[v][1]>wert?"+":"")+moneyFormatInt(farmiLog[v][1]-wert));
						createElement("div",{"mouseOverText":"90%"},newtd,(farmiLog[v][1]>0.9*wert?"+":"")+moneyFormatInt(farmiLog[v][1]-0.9*wert));
					if(!newFarmiumsatz[farmiLog[v][0]]){ newFarmiumsatz[farmiLog[v][0]]=0; }
					newFarmiumsatz[farmiLog[v][0]] += farmiLog[v][1];
					prev=v;
				}
				if(countFarmisAll>0){ newtd1.innerHTML += "<br>("+c+")"; }
				for(var v in newFarmiumsatz){
					if(!newFarmiumsatz.hasOwnProperty(v)){ continue; }
					newFarmiumsatz[v]=Math.round(100*newFarmiumsatz[v])/100;
					if(levelLog[v]!=undefined){ levelLog[v][4]=newFarmiumsatz[v]; } //dont override all because data could be joined to monthly
				}
				GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog),70);
				for(var v in totalProducts){
					if(!totalProducts.hasOwnProperty(v)){ continue; }
					totalProducts[v][2]=totalProducts[v][1]/totalProducts[v][0];
				}

				if(countFarmisAll>0){
					newtr=createElement("tr");
					newtbody.insertBefore(newtr,newtbody.firstElementChild);
					createElement("td",{},newtr,texte["total"]+"<br>("+countFarmisOk+")");
					newtd=createElement("td",{"id":"tdTotalProducts"},newtr);
					function buildTotalProducts(mode){
						$("tdTotalProducts").innerHTML="";
						var newtable=createElement("table",{cellspacing:"0",cellpadding:"0"},$("tdTotalProducts"));
						var newtr=createElement("tr",{},newtable);
						var newtd=createElement("td",{"class":"link hoverBgLightblue","style":"text-align:center;padding-right:3px;border-bottom:1px solid black;"},newtr,texte["product"]);
						if (mode==0){
							newtd.style.backgroundColor="lightblue";
							totalProducts.sortObj(sortObjFunctions["int"],true);
						}else{
							newtd.addEventListener("click",function(){buildTotalProducts(0);},false);
							totalProducts.sortObj(function(mode){return function(a,b){return (a[1][mode-1]-b[1][mode-1]);}}(mode),true);
						}
						newtd=createElement("td",{"class":"link hoverBgLightblue","style":"text-align:center;border-left:1px solid black;border-bottom:1px solid black;padding-left:3px;padding-right:3px;"},newtr,sign_mult);
						if (mode==1){ newtd.style.backgroundColor="lightblue"; }
						else{
							newtd.addEventListener("click",function(){buildTotalProducts(1);},false);
						}
						newtd=createElement("td",{"class":"link hoverBgLightblue","style":"text-align:center;border-left:1px solid black;border-bottom:1px solid black;padding-left:3px;padding-right:3px;"},newtr,sign_sum);
						if (mode==2){ newtd.style.backgroundColor="lightblue"; }
						else{
							newtd.addEventListener("click",function(){buildTotalProducts(2);},false);
						}
						newtd=createElement("td",{"class":"link hoverBgLightblue","style":"text-align:center;border-left:1px solid black;border-bottom:1px solid black;padding-left:3px;padding-right:3px;"},newtr,sign_sum+"/"+sign_mult);
						if (mode==3){ newtd.style.backgroundColor="lightblue"; }
						else{
							newtd.addEventListener("click",function(){buildTotalProducts(3);},false);
						}
						for(var v in totalProducts){
							if(!totalProducts.hasOwnProperty(v)){ continue; }
							//newdiv=createElement("div",{"style":"line-height:16px;"},newtd);
							newtr=createElement("tr",{"class":"hoverBgCc9"},newtable);
							newtd=createElement("td",{"style":"padding-right:3px;"},newtr);
							produktPic(0,v,newtd);
							createElement("div",{"style":"display:inline-block;"},newtd,prodName[0][v]);
							createElement("td",{"style":"text-align:right;border-left:1px solid black;padding-left:3px;padding-right:3px;"},newtr,numberFormat(totalProducts[v][0]));
							createElement("td",{"style":"text-align:right;border-left:1px solid black;padding-left:3px;padding-right:3px;"},newtr,numberFormat(totalProducts[v][1]));
							createElement("td",{"style":"text-align:right;border-left:1px solid black;padding-left:3px;padding-right:3px;"},newtr,numberFormat(totalProducts[v][2]));
						}
						newtable=null;newtr=null;newtd=null;
					}
					buildTotalProducts(0);
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{},newtd,moneyFormatInt(totalPriceOk));
						createElement("div",{},newtd,numberFormat(100*totalPriceOk/totalWertOk,1)+"%");
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,moneyFormatInt(totalWertOk));
						createElement("div",{"mouseOverText":"90%"},newtd,moneyFormatInt(0.9*totalWertOk));
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,(totalPriceOk>totalWertOk?"+":"")+moneyFormatInt(totalPriceOk-totalWertOk));
						createElement("div",{"mouseOverText":"90%"},newtd,(totalPriceOk>0.9*totalWertOk?"+":"")+moneyFormatInt(totalPriceOk-0.9*totalWertOk));

					newtr=createElement("tr",{"class":"hoverBgCc9"});
					newtbody.insertBefore(newtr,newtbody.children[1]);
					newtd=createElement("td",{},newtr);
						createElement("div",{},newtd,sign_average+" ("+countFarmisOk+")");
					newtd=createElement("td",{},newtr,"");
						createElement("div",{},newtd,">"+numberFormat(farmiOk)+"%");
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{},newtd,moneyFormatInt(totalPriceOk/countFarmisOk));
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%<br>"+sign_average+"[>"+numberFormat(farmiOk)+"%]"},newtd,moneyFormatInt(totalWertOk/countFarmisOk));
						createElement("div",{"mouseOverText":" 90%<br>"+sign_average+"[>"+numberFormat(farmiOk)+"%]"},newtd,moneyFormatInt(0.9*totalWertOk/countFarmisOk));
						createElement("div",{"mouseOverText":"100%<br>"+sign_sum+"[>"+numberFormat(farmiOk)+"%]/"+texte["alle"],"style":"border-top:1px solid black;"},newtd,moneyFormatInt(totalWertOk/countFarmisAll));
						createElement("div",{"mouseOverText":" 90%<br>"+sign_sum+"[>"+numberFormat(farmiOk)+"%]/"+texte["alle"]},newtd,moneyFormatInt(0.9*totalWertOk/countFarmisAll));
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,(totalPriceOk>totalWertOk?"+":"")+moneyFormatInt((totalPriceOk-totalWertOk)/countFarmisOk));
						createElement("div",{"mouseOverText":" 90%"},newtd,(totalPriceOk>0.9*totalWertOk?"+":"")+moneyFormatInt((totalPriceOk-0.9*totalWertOk)/countFarmisOk));
						createElement("div",{"mouseOverText":"100%","style":"border-top:1px solid black;"},newtd,(totalPriceOk>totalWertOk?"+":"")+moneyFormatInt((totalPriceOk-totalWertOk)/countFarmisAll));
						createElement("div",{"mouseOverText":" 90%"},newtd,(totalPriceOk>0.9*totalWertOk?"+":"")+moneyFormatInt((totalPriceOk-0.9*totalWertOk)/countFarmisAll));

					newtr=createElement("tr",{"class":"hoverBgCc9"});
					newtbody.insertBefore(newtr,newtbody.children[2]);
					newtd=createElement("td",{},newtr);
						createElement("div",{},newtd,sign_average+" ("+countFarmisAll+")");
					newtd=createElement("td",{},newtr);
						createElement("div",{},newtd,texte["alle"]);
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{},newtd,moneyFormatInt(totalPrice/countFarmisAll));
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,moneyFormatInt(totalWert/countFarmisAll));
						createElement("div",{"mouseOverText":"90%"},newtd,moneyFormatInt(0.9*totalWert/countFarmisAll));
					newtd=createElement("td",{"style":"text-align:right;"},newtr);
						createElement("div",{"mouseOverText":"100%"},newtd,(totalPrice>totalWert?"+":"")+moneyFormatInt((totalPrice-totalWert)/countFarmisAll));
						createElement("div",{"mouseOverText":"90%"},newtd,(totalPrice>0.9*totalWert?"+":"")+moneyFormatInt((totalPrice-0.9*totalWert)/countFarmisAll));
				}
			}
			break;
			case "preise":{
				//$("infoPanelInner").style.background="url('"+GFX+"stadt/markt2.jpg') no-repeat scroll left top transparent";
				buildStockTable(1,0,mode2,infoPanelInner,"black","#bb8");
			}
			break;
			case "preise2":{
				//$("infoPanelInner").style.background="url('"+GFX+"stadt/markt2.jpg') no-repeat scroll left top transparent";
				buildStockTable(2,0,mode2,infoPanelInner,"black","#bb8");
			}
			break;
			case "formulas":{
				// unsafeWindow.formulas[0][id]:
				// 0: id
				// 1: needed level
				// 2: name
				// 3: ingredients [[id,amount],[id,amount],[id,amount]]
				// 4: baking time in sek
				// 5: gain [0|[prod,amount],0|[prod,+val,time in sek],0|[prod,+pts,time in sek]]
				// 6: price money
				// 7: price coins
				// 8: points for baking
				// 9: [0,1,2,3,4,5,6]
				//10: ?
				//endremain: time to end
				//end: date until recipe is buyable
				if(mode2==""){
					//show all levels,show products,show crop amount,show crop points
					mode2=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_infoPanelFormulas","[false,true,true,true]"),"buildInfoPanel/formulas/infoPanelFormulas",[false,true,true,true]);
				}
				function buildInfoPanelFormulas(){
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_infoPanelFormulas",implode(mode2));
					var infoPanelInner=$("infoPanelInner");
					infoPanelInner.innerHTML="";
					var newdiv=createElement("div",{"style":"height:23px;width:100%;"},infoPanelInner);

					var newinput=createElement("input",{"type":"checkbox","class":"link","checked":mode2[0]},newdiv);
					newinput.addEventListener("click",function(){
						mode2[0]=this.checked;
						buildInfoPanelFormulas();
					},false);
					createElement("span",{"style":"margin-right:10px;"},newdiv,texte["showAll"]);

					for(var v=0;v<=2;v++){
						newinput=createElement("div",{"style":"display:inline-block;width:70px;text-align:center;border:1px inset black;"+(mode2[v+1]?"background-color:lightblue;":""),"class":"link hoverBgLightbrown","v":v},newdiv,texte["formulaType"][v]);
						newinput.addEventListener("mouseover",function(event){
							showToolTip(event,texte["click"]+'&nbsp;/&nbsp;'+texte["clickStrg"]);
						},false);
						newinput.addEventListener("click",function(event){
							var v=parseInt(this.getAttribute("v"),10);
							if(!event.ctrlKey){
								for(var w=1;w<=3;w++){ mode2[w]=false; }
							}
							mode2[v+1]=!mode2[v+1];
							buildInfoPanelFormulas();
						},false);
					}

					newdiv=createElement("div",{"style":"height:492px;width:100%;overflow:auto;"},infoPanelInner);
					var newtable=createElement("table",{"style":"line-height:16px;width:100%","border":"1"},newdiv); //scrollTable
					var newthead=createElement("thead",{},newtable);
					var newtbody=createElement("tbody",{"class":"hoverRowBgLightbrown","style":"height:465px;"},newtable);

					var newtr=createElement("tr",{"class":"borderBottom2"},newthead);
					var newtd,newtd1;
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["nr"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["lvl"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["title"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["ingredients"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["time"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["gain"]);
					createElement("th",{"sortdir":"Asc","class":"link"},newtr,texte["price"]);
					new SortableTable(newtr);

					for(var v in unsafeWindow.formulas[0]){
						if(!unsafeWindow.formulas[0].hasOwnProperty(v)){ continue; }
						if(mode2[0]||((USERLEVEL>=unsafeWindow.formulas[0][v][1])&&(unsafeWindow.formulas[0][v]["endremain"]>=0))){
							if((mode2[1]&&(unsafeWindow.formulas[0][v][5][0]!=0))||(mode2[2]&&(unsafeWindow.formulas[0][v][5][1]!=0))||(mode2[3]&&(unsafeWindow.formulas[0][v][5][2]!=0))){
								newtr=createElement("tr",{},newtbody);
								createElement("td",{"value":unsafeWindow.formulas[0][v][0],"style":(unsafeWindow.formulas[0][v]["endremain"]>=0?"":"background-color:red;")},newtr,unsafeWindow.formulas[0][v][0]);
								createElement("td",{"value":unsafeWindow.formulas[0][v][1],"style":(USERLEVEL>=unsafeWindow.formulas[0][v][1]?"":"background-color:red;")},newtr,unsafeWindow.formulas[0][v][1]);
								// Title
								newtd1=createElement("td",{},newtr,unsafeWindow.formulas[0][v][2]);
								// Ingredients
								newtd=createElement("td",{},newtr);
								var sum1=0;
								var sumPts=0;
								var preis=0;
								for(var w=0;w<unsafeWindow.formulas[0][v][3].length;w++){
									preis=!isNaN(NPC[0][unsafeWindow.formulas[0][v][3][w][0]])?Math.min(NPC[0][unsafeWindow.formulas[0][v][3][w][0]],gut[unsafeWindow.formulas[0][v][3][w][0]]):gut[unsafeWindow.formulas[0][v][3][w][0]];
									sum1 += unsafeWindow.formulas[0][v][3][w][1]*preis;
									newdiv=createElement("div",{"class":"link hoverBgLightblue","prod":unsafeWindow.formulas[0][v][3][w][0],"value":preis*unsafeWindow.formulas[0][v][3][w][1]},newtd);
									newdiv.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,this.getAttribute("prod"),null,'<tr><td>'+sign_sum+'</td><td style="text-align:right;">'+moneyFormatInt(parseInt(this.getAttribute("value"),10))+'</td></tr>');},false);
									newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
									produktPic(0,unsafeWindow.formulas[0][v][3][w][0],newdiv);
									newdiv=createElement("span",{},newdiv,numberFormat(unsafeWindow.formulas[0][v][3][w][1]));
								}
								newtd.setAttribute("value",sum1);
								createElement("div",{},newtd,"("+moneyFormatInt(sum1)+")");
								var sum=-sum1;
								// Time
								createElement("td",{"value":unsafeWindow.formulas[0][v][4]},newtr,getTimeStr(unsafeWindow.formulas[0][v][4],1)+"h");
								// Gain
								newtd=createElement("td",{"style":"width:80px;"},newtr);
								if(unsafeWindow.formulas[0][v][5][0]!=0){
									// Products
									preis=!isNaN(NPC[0][unsafeWindow.formulas[0][v][5][0][0]])?Math.min(NPC[0][unsafeWindow.formulas[0][v][5][0][0]],gut[unsafeWindow.formulas[0][v][5][0][0]]):gut[unsafeWindow.formulas[0][v][5][0][0]];
									sum1=unsafeWindow.formulas[0][v][5][0][1]*preis;
									sum += sum1;
									newdiv=createElement("div",{"class":"link hoverBgLightblue","prod":unsafeWindow.formulas[0][v][5][0][0],"value":sum1},newtd);
									newdiv.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,this.getAttribute("prod"));},false);
									newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
									produktPic(0,unsafeWindow.formulas[0][v][5][0][0],newdiv);
									createElement("span",{},newdiv,unsafeWindow.formulas[0][v][5][0][1]);
									createElement("div",{},newtd,"("+moneyFormatInt(sum1)+")");
								}else if(unsafeWindow.formulas[0][v][5][1]!=0){
									// Crop amount boost
									createElement("div",{},newtd,getTimeStr(unsafeWindow.formulas[0][v][5][1][2],1)+"h");
									newdiv=createElement("div",{"class":"link hoverBgLightblue","prod":unsafeWindow.formulas[0][v][5][1][0],"style":"white-space:nowrap;"},newtd);
									newdiv.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,this.getAttribute("prod"));},false);
									newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
									produktPic(0,unsafeWindow.formulas[0][v][5][1][0],newdiv);
									createElement("span",{},newdiv,"+"+unsafeWindow.formulas[0][v][5][1][1]+"val&nbsp;(+"+numberFormat(100*unsafeWindow.formulas[0][v][5][1][1]/(prodYield[0][unsafeWindow.formulas[0][v][5][1][0]]-1))+"%)");
									sum1=0;
									for(var zoneNr=1;zoneNr<zoneTyp.length;zoneNr++){ if((zoneTyp[zoneNr]==1)&&(!zoneBlock[zoneNr])){
										preis=!isNaN(NPC[0][unsafeWindow.formulas[0][v][5][1][0]])?Math.min(NPC[0][unsafeWindow.formulas[0][v][5][1][0]],gut[unsafeWindow.formulas[0][v][5][1][0]]):gut[unsafeWindow.formulas[0][v][5][1][0]];
										sum1 += preis*unsafeWindow.formulas[0][v][5][1][1]*Math.ceil(calcGrowTimes(60*prodGrowTime[0][unsafeWindow.formulas[0][v][5][1][0]],unsafeWindow.formulas[0][v][5][1][2],1-(zoneBonus[zoneNr]/100)))*120/prodPlantSize[0][unsafeWindow.formulas[0][v][5][1][0]];
									}}
									sum += sum1;
									createElement("div",{},newtd,"("+moneyFormatInt(sum1)+")");
									newtd.setAttribute("value",sum1);
								}else if(unsafeWindow.formulas[0][v][5][2]!=0){
									// Crop points boost
									createElement("div",{},newtd,getTimeStr(unsafeWindow.formulas[0][v][5][2][2],1)+"h");
									newdiv=createElement("div",{"class":"link hoverBgLightblue","prod":unsafeWindow.formulas[0][v][5][2][0],"style":"white-space:nowrap;"},newtd);
									newdiv.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,this.getAttribute("prod"));},false);
									newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
									produktPic(0,unsafeWindow.formulas[0][v][5][2][0],newdiv);
									createElement("span",{},newdiv,"+");
									pointsFormat(unsafeWindow.formulas[0][v][5][2][1],"span",newdiv);
									createElement("span",{},newdiv,"&nbsp;(+"+numberFormat(100*unsafeWindow.formulas[0][v][5][2][1]/prodPoints[0][unsafeWindow.formulas[0][v][5][2][0]])+"%)");

									sum1=0;
									for(var zoneNr=1;zoneNr<zoneTyp.length;zoneNr++){ if((zoneTyp[zoneNr]==1)&&(!zoneBlock[zoneNr])){
										sum1 += unsafeWindow.formulas[0][v][5][2][1]*Math.ceil(calcGrowTimes(60*prodGrowTime[0][unsafeWindow.formulas[0][v][5][2][0]],unsafeWindow.formulas[0][v][5][2][2],1-(zoneBonus[zoneNr]/100)))*120/prodPlantSize[0][unsafeWindow.formulas[0][v][5][2][0]];
									}}
									sumPts=sum1;
									newdiv=createElement("div",{},newtd);
									createElement("span",{},newdiv,"(");
									pointsFormat(sum1,"span",newdiv);
									createElement("span",{},newdiv,")");
									newtd.setAttribute("value",0);
								}
								pointsFormat(unsafeWindow.formulas[0][v][8],"div",newtd);
								sumPts += unsafeWindow.formulas[0][v][8];
								// Price
								newtd=createElement("td",{},newtr);
								if(unsafeWindow.formulas[0][v][6]>0){
									sum1=unsafeWindow.formulas[0][v][6];
									sum -= sum1;
									newspan=createElement("div",{},newtd,moneyFormatInt(sum1));
									newtd.setAttribute("value",sum1);
								}
								if(unsafeWindow.formulas[0][v][7]>0){
									sum1=unsafeWindow.formulas[0][v][7]*gut[0];
									sum -= sum1;
									newspan=createElement("div",{"class":"link hoverBgLightblue"},newtd,coinsFormat(unsafeWindow.formulas[0][v][7],createElement("div")).parentNode.innerHTML);
									newspan.addEventListener("mouseover",function(event){showGoToMarketToolTip(event,"0");},false);
									newspan.addEventListener("click",function(){showMarket("0");},false);
									createElement("div",{"style":"clear:both;"},newtd,"("+moneyFormatInt(sum1)+")");
									newtd.setAttribute("value",sum1);
								}
								//createElement("td",{},newtr,unsafeWindow.formulas[0][v][8]);
								//createElement("td",{},newtr,unsafeWindow.formulas[0][v][9]);
								// Title
								createElement("div",{},newtd1,moneyFormatInt(sum));
								newtd1.setAttribute("value",sum);
								pointsFormat(sumPts,"div",newtd1);
							}
						}
					}
					infoPanelInner=null;
					newtable=null;newthead=null;newtbody=null;newtr=null;newtd=null;newtd1=null;newdiv=null;newinput=null;
				}
				buildInfoPanelFormulas();
			}
			break;
			case "lotteryLog":{
				var lotteryLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog","{}"),"buildInfoPanel/lotteryLog/lotteryLog",{});
				// implode data older than last month
				var stichtag=new Date();
				stichtag=Math.round(((new Date(stichtag.getFullYear(),stichtag.getMonth()-1,1)).getTime())/1000);
				var changed=false;
				for(var v in lotteryLog){
					if(!lotteryLog.hasOwnProperty(v)){ continue; }
					if(v.match(/\d+\.\d+\.\d+/)){
						if(getTime(v)<stichtag){
							changed=true;
							var w=v.replace(/\d+\./,"");
							if(!lotteryLog[w]){
								lotteryLog[w]=[[],[],{},[]];
							}
							if(lotteryLog[v][0]>0){
								if(lotteryLog[v][1]&&(!lotteryLog[v][1].isEmpty())){
									if(!lotteryLog[w][1][lotteryLog[v][0]]){ lotteryLog[w][1][lotteryLog[v][0]]=0; }
									lotteryLog[w][1][lotteryLog[v][0]]++;
									for(var p in lotteryLog[v][1]){
										if(!lotteryLog[v][1].hasOwnProperty(p)){ continue; }
										if(!lotteryLog[w][2][p]){ lotteryLog[w][2][p]=0; }
										lotteryLog[w][2][p] += lotteryLog[v][1][p];
									}
								}else{
									if(!lotteryLog[w][0][lotteryLog[v][0]]){ lotteryLog[w][0][lotteryLog[v][0]]=0; }
									lotteryLog[w][0][lotteryLog[v][0]]++;
								}
							}
							lotteryLog[w][2].sortObj(sortObjFunctions["productId"]);
							if(lotteryLog[v][2]){
								for(var p=0;p<lotteryLog[v][2].length;p++){
									if(!lotteryLog[w][3][lotteryLog[v][2][p]]){ lotteryLog[w][3][lotteryLog[v][2][p]]=0; }
									lotteryLog[w][3][lotteryLog[v][2][p]]++;
								}
							}
							delete lotteryLog[v];
						}
					}
				}
				if(changed){
					lotteryLog.sortObj(sortObjFunctions["date"]);
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog",implode(lotteryLog));
				}

				var modeLotteryLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeLotteryLog","{}"),"buildInfoPanel/lotteryLog/modeLotteryLog",{});

				newdiv=createElement("div",{"style":"text-align:center;height:20px;width:100%;"},infoPanelInner);
				createElement("span",{"style":"font-weight:bold;"},newdiv,texte["lotteryLog"]);
				newinput=createElement("input",{"type":"checkbox","class":"link","checked":modeLotteryLog["total"],"style":"margin-left:50px;"},newdiv);
				newinput.addEventListener("click",function(){
					modeLotteryLog["total"]=this.checked;
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeLotteryLog",implode(modeLotteryLog));
					buildLotteryLogTable();
				},false);
				createElement("span",{},newdiv,texte["total"]);
				newdiv=createElement("div",{"style":"height:495px;width:100%;overflow:auto;"},infoPanelInner);
				createElement("table",{},newdiv);

				function buildLotteryLogTable(){
					var oldtable=$("infoPanelInner").getElementsByTagName("table")[0];
					//var newtable=createElement("table",{"cellspacing":"0","border":"1","width":"100%;"});
					var newtable=createElement("table",{"style":"line-height:16px;width:100%","border":"1"}); // scrollTable
					oldtable.parentNode.replaceChild(newtable,oldtable);
					oldtable=null;

					var newthead=createElement("thead",{},newtable);
					var newtbody=createElement("tbody",{"class":"hoverRowBgLightbrown","style":"height:465px;"},newtable);
					var newtd,newdiv,newtable1,newtr1;
					var newtr=createElement("tr",{},newthead);
					if(modeLotteryLog["total"]){
						// prepare data
						var lotteryLogTotal=[[],[],{},[]];
						for(var v in lotteryLog){
							if(!lotteryLog.hasOwnProperty(v)){ continue; }
							if(v.match(/\d+\.\d+\.\d+/)){
								if(lotteryLog[v][0]>0){
									if(lotteryLog[v][1]&&(!lotteryLog[v][1].isEmpty())){
										if(!lotteryLogTotal[1][lotteryLog[v][0]]){ lotteryLogTotal[1][lotteryLog[v][0]]=0; }
										lotteryLogTotal[1][lotteryLog[v][0]]++;
										for(var p in lotteryLog[v][1]){
											if(!lotteryLog[v][1].hasOwnProperty(p)){ continue; }
											if(!lotteryLogTotal[2][p]){ lotteryLogTotal[2][p]=0; }
											lotteryLogTotal[2][p] += lotteryLog[v][1][p];
										}
									}else{
										if(!lotteryLogTotal[0][lotteryLog[v][0]]){ lotteryLogTotal[0][lotteryLog[v][0]]=0; }
										lotteryLogTotal[0][lotteryLog[v][0]]++;
									}
								}
								lotteryLogTotal[2].sortObj(sortObjFunctions["productId"]);
								if(lotteryLog[v][2]){
									for(var p=0;p<lotteryLog[v][2].length;p++){
										if(!lotteryLogTotal[3][lotteryLog[v][2][p]]){ lotteryLogTotal[3][lotteryLog[v][2][p]]=0; }
										lotteryLogTotal[3][lotteryLog[v][2][p]]++;
									}
								}
							}else{
								for(var j=0;j<4;j++){
								if(j==2){ continue; }
									for(var i=0;i<lotteryLog[v][j].length;i++){
										if(lotteryLog[v][j][i]>0){
											if(!lotteryLogTotal[j][i]){ lotteryLogTotal[j][i]=0; }
											lotteryLogTotal[j][i] += lotteryLog[v][j][i];
										}
									}
								}

								for(var prod in lotteryLog[v][2]){
									if(!lotteryLog[v][2].hasOwnProperty(prod)){ continue; }
									if(!lotteryLogTotal[2][prod]){ lotteryLogTotal[2][prod]=0; }
									lotteryLogTotal[2][prod] += lotteryLog[v][2][prod];
								}
							}
						}
						// plot table
						createElement("th",{"style":"white-space:nowrap;"},newtr,texte["dailyTicket"]);
						createElement("th",{"style":"white-space:nowrap;"},newtr,texte["boughtTickets"]);

						newtr=createElement("tr",{},newtbody);
						newtd=createElement("td",{},newtr);
						newdiv=createElement("div",{"style":"margin-bottom:3px;"},newtd);
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["keptLots"]); },false);
						var c=0;
						for(var i=0;i<lotteryLogTotal[0].length;i++){
							if(lotteryLogTotal[0][i]>0){
								c += lotteryLogTotal[0][i];
								newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
								createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
								createElement("span",{},newdiv1,lotteryLogTotal[0][i]);
							}
						}
						if(c>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+c+sign_mult); }

						var changedLots=0;
						newdiv=createElement("div",{"style":""},newtd);
						newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["exchangedLots"]); },false);
						for(var i=0;i<lotteryLogTotal[1].length;i++){
							if(lotteryLogTotal[1][i]>0){
								changedLots += lotteryLogTotal[1][i];
								newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
								createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
								createElement("span",{},newdiv1,lotteryLogTotal[1][i]);
							}
						}
						if(changedLots>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+changedLots+sign_mult); }

						var c,sum=0;
						newtable1=createElement("table",{"style":"display:inline-block;padding-right:5px;margin-right:5px;","border":"0","cellspacing":"0"},newtd);
						for(var prod in lotteryLogTotal[2]){
							if(!lotteryLogTotal[2].hasOwnProperty(prod)){ continue; }
							newtr1=createElement("tr",{"class":"link hoverBgLightblue","prod":prod},newtable1);
							newtr1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
							newtr1.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
							produktPic(0,prod,createElement("td",{},newtr1));
							createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(lotteryLogTotal[2][prod]));
							createElement("td",{"style":"padding-right:5px;"},newtr1,prodName[0][prod]);
							c=lotteryLogTotal[2][prod]*gut[prod];
							sum += c;
							createElement("td",{"style":"text-align:right;"},newtr1,moneyFormat(c));
						}
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"colspan":"2"},newtr1);
						createElement("td",{"style":"border-top:1px solid black;"},newtr1,sign_sum);
						createElement("td",{"style":"border-top:1px solid black;text-align:right;"},newtr1,moneyFormat(sum));
						newtr1=createElement("tr",{},newtable1);
						createElement("td",{"colspan":"2"},newtr1);
						createElement("td",{},newtr1,sign_average);
						createElement("td",{"style":"text-align:right;"},newtr1,moneyFormat(sum/changedLots));

						c=0;
						newtd=createElement("td",{},newtr);
						for(var i=0;i<lotteryLogTotal[3].length;i++){
							if(lotteryLogTotal[3][i]>0){
								c += lotteryLogTotal[3][i];
								newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
								createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
								createElement("span",{},newdiv1,lotteryLogTotal[3][i]);
							}
						}
						if(c>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+c+sign_mult); }




					}else{
						createElement("th",{"style":"white-space:nowrap;"},newtr,texte["tag"]);
						createElement("th",{"style":"white-space:nowrap;"},newtr,texte["dailyTicket"]);
						createElement("th",{"style":"white-space:nowrap;"},newtr,texte["boughtTickets"]);

						for(var v in lotteryLog){
							if(!lotteryLog.hasOwnProperty(v)){ continue; }
							newtr=createElement("tr",{},newtbody);
							createElement("td",{},newtr,v);

							if(v.match(/\d+\.\d+\.\d+/)){
								newtd=createElement("td",{},newtr);
								newdiv=createElement("div",{"style":"display:inline-block;margin-right:3px;vertical-align:top;"},newtd);
								if(lotteryLog[v][0]>0){ createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+lotteryLog[v][0]+".jpg"},newdiv); }
								if(lotteryLog[v][1]){
									var c,sum=0;
									newtable1=createElement("table",{"style":"display:inline-block;border-right:1px solid black;padding-right:5px;margin-right:5px;","border":"0","cellspacing":"0"},newtd);
									for(var prod in lotteryLog[v][1]){
										if(!lotteryLog[v][1].hasOwnProperty(prod)){ continue; }
										newtr1=createElement("tr",{"class":"link hoverBgLightblue","prod":prod},newtable1);
										newtr1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
										newtr1.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
										produktPic(0,prod,createElement("td",{},newtr1));
										createElement("td",{"style":"text-align:right;"},newtr1,numberFormat(lotteryLog[v][1][prod]));
										createElement("td",{"style":"padding-right:5px;"},newtr1,prodName[0][prod]);
										c=lotteryLog[v][1][prod]*gut[prod];
										sum += c;
										createElement("td",{"style":"text-align:right;"},newtr1,moneyFormat(c));
									}
									createElement("div",{"style":"display:inline-block;vertical-align:bottom;"},newtd,moneyFormat(sum));
								}

								newtd=createElement("td",{},newtr);
								if(lotteryLog[v][2]){
									for(var w=0;w<lotteryLog[v][2].length;w++){
										createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+lotteryLog[v][2][w]+".jpg"},newtd);
									}
								}
							}else{
								newtd=createElement("td",{},newtr);
								newdiv=createElement("div",{"style":"margin-bottom:3px;"},newtd);
								newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["keptLots"]); },false);
								var c=0;
								for(var i=0;i<lotteryLog[v][0].length;i++){
									if(lotteryLog[v][0][i]>0){
										c += lotteryLog[v][0][i];
										newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
										createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
										createElement("span",{},newdiv1,lotteryLog[v][0][i]);
									}
								}
								if(c>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+c+sign_mult); }

								var changedLots=0;
								newdiv=createElement("div",{"style":""},newtd);
								newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["exchangedLots"]); },false);
								for(var i=0;i<lotteryLog[v][1].length;i++){
									if(lotteryLog[v][1][i]>0){
										changedLots += lotteryLog[v][1][i];
										newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
										createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
										createElement("span",{},newdiv1,lotteryLog[v][1][i]);
									}
								}
								if(changedLots>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+changedLots+sign_mult); }

								var sum=0;
								for(var prod in lotteryLog[v][2]){
									if(!lotteryLog[v][2].hasOwnProperty(prod)){ continue; }
									newdiv=createElement("div",{"class":"link hoverBgLightblue","prod":prod,"style":"position:relative;display:inline-block;margin-right:3px;"},newtd);
									newdiv.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
									newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
									produktPic(0,prod,newdiv);
									createElement("span",{"style":"text-align:right;"},newdiv,numberFormat(lotteryLog[v][2][prod]));
									c=lotteryLog[v][2][prod]*gut[prod];
									sum += c;
								}
								createElement("div",{},newtd,moneyFormat(sum)+"&nbsp;("+sign_average+moneyFormat(sum/changedLots)+")");

								c=0;
								newtd=createElement("td",{},newtr);
								for(var i=0;i<lotteryLog[v][3].length;i++){
									if(lotteryLog[v][3][i]>0){
										c += lotteryLog[v][3][i];
										newdiv1=createElement("div",{"style":"position:relative;display:inline-block;margin-right:2px;"},newdiv);
										createElement("img",{"style":"width:20px;border:0;","src":GFX+"city/"+i+".jpg"},newdiv1);
										createElement("span",{},newdiv1,lotteryLog[v][3][i]);
									}
								}
								if(c>0){ createElement("div",{"style":"position:relative;display:inline-block;"},newdiv,"&nbsp;=&nbsp;"+c+sign_mult); }
							}
						}
					}
					newthead=null;newtable=null;newtbody=null;newtd=null;newdiv=null;newtable1=null;newtr1=null;newtr=null;
				}
				buildLotteryLogTable();
			}
			break;
			case "upjersWerbung":{
				createElement("div",{"align":"center","style":"font-weight:bold;line-height:30px;"},infoPanelInner,texte["upjersWerbung"]);
				for(var v=0;v<upjersWerbung.length;v++){
					createElement("div",{"style":"padding:5px;margin:5px;border:1px solid black;"},infoPanelInner,upjersWerbung[v]);
				}
			}
			break;
			}
			raiseEvent("gameInfoPanelOpen");
			infoPanelInner=null;
			newtable=null;newthead=null;newtbody=null;newtfoot=null;newtr=null;newtd=null;newtd1=null;newdiv1=null;newinput=null;
		}
		newdiv=null;
	}catch(err){ GM_log("ERROR buildInfoPanel mode="+implode(mode)+" mode2="+implode(mode2)+"\n"+err); }
	}

	// Profit
	err_trace="Profit";
	newdiv=createElement("div",{"id":"divBeraterButtonsProfit","class":"link beraterButtonIcon hoverBgGreen","mouseOverText":texte["profitTable"]},$("divBeraterButtons"));
	createElement("img",{"src":GFX+"farmhouse/items/76_1.png","style":"position:relative;top:-5px;left:-5px;width:40px;height:40px;"},newdiv);
	newdiv.addEventListener("click",function(){buildInfoPanel("profit");},false);

	// Preise
	err_trace="Prices";
	newdiv=createElement("div",{"id":"divBeraterButtonsPreise","class":"link beraterButtonIcon hoverBgGold","mouseOverText":texte["preise"]},$("divBeraterButtons"));
	createElement("img",{"src":GFX+"money.gif","style":"width:30px;height:30px;"},newdiv);
	newdiv.addEventListener("click",function(){buildInfoPanel("preise",null);},false);

	// Recipes and Powerups
	err_trace="Recipes and Powerups";
	if(unsafeWindow.formulas){
		newdiv=createElement("div",{"id":"divBeraterButtonsFormulas","class":"link beraterButtonIcon hoverBgBlue","mouseOverText":texte["rezepte"]},$("divBeraterButtons"));
		createElement("img",{"src":GFX+"farmhouse/catalogue.gif","style":"position:relative;top:3px;left:3px;width:24px;height:24px;"},newdiv);
		newdiv.addEventListener("click",function(){buildInfoPanel("formulas");},false);

		if(unsafeWindow.showPowerUps){ // hofix 13.03.2013
			unsafeWindow._showPowerUps=unsafeWindow.showPowerUps;
			unsafeWindow.showPowerUps = function showPowerUps(){
				unsafeWindow._showPowerUps();
				var cand=$("powerselectorcontent").getElementsByClassName("blackbox");
				for(var v=0;v<cand.length;v++){
					if(cand[v].id.match(/^formulatimer\d+$/)){
						cand[v].style.top="47px";
					}
				}
				cand=null;
			};
			unsafeWindow.showPowerUps();
		}

	}

	// Uebersicht
	err_trace="Overview";
	newdiv=$("titlepig");
	if(!newdiv){ newdiv = createElement("div",{"id":"titlepig","style":"top:12px;left:218px;width:97px;height:100px;position:absolute;"},$("headercontainer")) };
	newdiv.setAttribute("class","link");
	newdiv.addEventListener("click",function(){ buildInfoPanel("zonen"); },false);
	newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["uebersicht"]); },false);

	// Quest
	err_trace="Quest";
/*
	questdata={ 
	"questid":quest number,
	"remain":seconds to the start,
	"data":{	"0":2,
				"1":{"0":{"prodId1":amountNeeded,
						  "prodId2":{"prod2a":amountNeeded,
						             "prod2a":amountNeeded}},
					 "1":0,
					 "2":0,
					 "3":0},
				"2":{"0":points,"1":money,"2":0,"3":flagRack,"4":flagFarm","5":object,"6":0}, //Rewards
				"3":??,
				"4":??,
				"5":??,
				"6":"Short Description",
				"7":"Long Description",
				"8":waitingTime (before or after?),
				"9":??,
				"10":??},
	"entries":{"prodId1":"amountGiven","prodId2":"amountGiven"},
	"solved":0,
	"farmi":flagFarmiRewarded,
	"end":flagQuestsEnded}
*/
	var highlightProducts=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts","[false,{}]"),"do_main/highlightProducts",[false,{}]);
	function calcQuestData(quTyp,campaign){
		try{
			var err_trace = "Set current data";
			// Quest data
			if(QUESTS[quTyp][campaign][questData[quTyp][campaign]["nr"]]){
				questData[quTyp][campaign]["data"]=QUESTS[quTyp][campaign][questData[quTyp][campaign]["nr"]].clone();
				for(var i=questData[quTyp][campaign]["data"][0].length-1;i>=0;i--){
					// Alternative: if product is already given, reduce to this one
					if(typeof questData[quTyp][campaign]["data"][0][i][0]=="object"){
						for(var j=0;j<questData[quTyp][campaign]["data"][0][i].length;j++){
							if(questData[quTyp][campaign]["given"][questData[quTyp][campaign]["data"][0][i][j][0]]&&questData[quTyp][campaign]["given"][questData[quTyp][campaign]["data"][0][i][j][0]][questData[quTyp][campaign]["data"][0][i][j][1]]){
								questData[quTyp][campaign]["data"][0][i]=questData[quTyp][campaign]["data"][0][i][j];
							}
						}
					}
					// Mark the cheapest items. important at alternatives
					if(typeof questData[quTyp][campaign]["data"][0][i][0]=="object"){
						help=[];
						for(var k=0;k<questData[quTyp][campaign]["data"][0][i].length;k++){
							if(questData[quTyp][campaign]["data"][0][i][k][0]!=0){
								help[k]=0;
							}else if(isNaN(NPC[questData[quTyp][campaign]["data"][0][i][k][0]][questData[quTyp][campaign]["data"][0][i][k][1]])){
								help[k]=questData[quTyp][campaign]["data"][0][i][k][2]*gut[questData[quTyp][campaign]["data"][0][i][k][1]];
							}else{
								help[k]=questData[quTyp][campaign]["data"][0][i][k][2]*Math.min(gut[questData[quTyp][campaign]["data"][0][i][k][1]],NPC[questData[quTyp][campaign]["data"][0][i][k][0]][questData[quTyp][campaign]["data"][0][i][k][1]]);
							}
							questData[quTyp][campaign]["data"][0][i][k][3]=true;
							for(var l=0;l<k;l++){
								if(help[k]<help[l]){ questData[quTyp][campaign]["data"][0][i][l][3]=false; }
								else { questData[quTyp][campaign]["data"][0][i][k][3]=false; }
							}
						}
						help=questData[quTyp][campaign]["data"][0].splice(i,1)
						questData[quTyp][campaign]["data"][0]=questData[quTyp][campaign]["data"][0].concat(help[0]);
					}else{
						questData[quTyp][campaign]["data"][0][i][3]=true;
					}
				}
			}else{
				questData[quTyp][campaign]["data"]=[];
			}
			// GM_log("questData["+quTyp+"]["+campaign+"]="+implode(questData[quTyp][campaign]));
			// GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_questData",implode(questData));
			// unsafeData.questData=questData.clone();
		}catch(err){ GM_log("ERROR calcQuestData ("+err_trace+")\n"+err); }
	}
	function handleQuestData(){
	    // GM_log("setQuest newQuestNr="+newQuestNr);
		try{
			var err_trace = "Get questdata";	
			if(unsafeWindow.questdata){
				// GM_log("unsafeWindow.questdata:\n"+print_r(unsafeWindow.questdata,"",true,"\n"));
				for(var campaign in QUESTS["farm"]){
					if(!QUESTS["farm"].hasOwnProperty(campaign)){continue;}
					if(unsafeWindow.questdata[campaign]){
						if(!questData["farm"][campaign]){ questData["farm"][campaign]=INIT_questData["farm"][campaign].clone(); }
						if(unsafeWindow.questdata[campaign]["end"]&&(unsafeWindow.questdata[campaign]["end"]==1)){
							// GM_log("Quests farm campaign="+campaign+" complete");
							questData["farm"][campaign]["nr"]=QUESTS["farm"][campaign].length;
							questData["farm"][campaign]["given"] = new Object();
							questData["farm"][campaign]["time"] = 0;
						}else{
							// if(!questData["farm"][campaign]){continue;}
							// Quest number
							questData["farm"][campaign]["nr"]=unsafeWindow.questdata[campaign]["questid"];
							// Given
							questData["farm"][campaign]["given"] = new Object();
							if(unsafeWindow.questdata[campaign]["entries"]){
								for(var t in unsafeWindow.questdata[campaign]["entries"]){
									if(!unsafeWindow.questdata[campaign]["entries"].hasOwnProperty(t)){continue;}
									var prod = parseInt(t,10);
									var type = 0;
									if(!questData["farm"][campaign]["given"][type]){ questData["farm"][campaign]["given"][type] = new Object(); }
									if(!questData["farm"][campaign]["given"][type][prod]){ questData["farm"][campaign]["given"][type][prod] = 0; }
									questData["farm"][campaign]["given"][type][prod] += parseInt(unsafeWindow.questdata[campaign]["entries"][t],10);
								}
							}
							// Time
							questData["farm"][campaign]["time"] = now+unsafeWindow.questdata[campaign]["remain"];
						}
						calcQuestData("farm",campaign);
					}
				}
				// GM_log("questdata:\n"+print_r(questData["farm"],"",true,"\n"));
			}
			err_trace = "Calc highlightProducts"; 
			if(highlightProducts[0]){ // TODO: For all quests. Not if all given.
				highlightProducts[1]={};
				if(questData["farm"]["1"]["data"]){
					for(var j=0;j<questData["farm"]["1"]["data"][0].length;j++){
						if(questData["farm"]["1"]["data"][0][j][3]){
							highlightProducts[1][questData["farm"]["1"]["data"][0][j][1]]=true;
						}
					}				
				}
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts",implode(highlightProducts));
			}
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_questData",implode(questData));
			unsafeData.questData=questData.clone();
		}catch(err){ GM_log("ERROR handleQuestData ("+err_trace+")\n"+err); }
		// Fix class of questboxline
		for(var camp in questData["farm"]){
			if(!questData["farm"].hasOwnProperty(camp)){continue;}
			var div=$("questboxlinecontent"+camp);
			if(div){
				if(questData["farm"][camp]["time"]<now){ 
					if(div.getAttribute("class")!="link"){ div.setAttribute("class","link"); }
				}else{
					if(div.getAttribute("class")!=""){ div.setAttribute("class",""); }
				}
			}
		}
		div=null;
	}
	handleQuestData();

	unsafeWindow._questInitResponse=unsafeWindow.questInitResponse;
	unsafeWindow.questInitResponse = function(request,action,show,campaign){
	try{
		unsafeWindow._questInitResponse(request,action,show,campaign);
	}catch(err){ GM_log("ERROR _questInitResponse\n"+err); }		
	try{
		handleQuestData();
	}catch(err){ GM_log("ERROR questInitResponse\n"+err); }		
	}

	// mouseover showing quest data
	function questLineMouseOver(questType,campaign){
		try{
			var div=createElement("div");
			var questDataCurr = questData[questType][campaign];
			var questCurr = QUESTS[questType][campaign][questDataCurr["nr"]];
			var questStarted = (questDataCurr["time"]<now);
			var newtable=createElement("table",{"class":"white","border":"0","cellspacing":"0","cellpadding":"3","style":"line-height:16px;"},div);
			var newtr=createElement("tr",{},newtable);
			var newtd=createElement("td",{"colspan":"3","style":"text-align:center;border-bottom:1px solid white;"},newtr,questType+" "+campaign+"."+questDataCurr["nr"]);
			if(questStarted){ createElement("td",{"colspan":"2","style":"text-align:center;border-bottom:1px solid white;border-left:1px solid white;"},newtr,texte["given"]); }
			createElement("td",{"colspan":"2","style":"text-align:center;border-bottom:1px solid white;border-left:1px solid white;"},newtr,texte["fehlt"]);
			createElement("td",{"colspan":"2","style":"text-align:center;border-bottom:1px solid white;border-left:1px solid white;"},newtr,texte["total"]);
			var sumWert=[0,0,0]; //given,needed,total
			var menge,item,preis;
			for(var v=0;v<questDataCurr["data"][0].length;v++){
				item=questDataCurr["data"][0][v];
				menge=[,,item[2]];
				if(questStarted){ menge[0]=(questDataCurr["given"]&&questDataCurr["given"][item[0]]&&questDataCurr["given"][item[0]][item[1]])?questDataCurr["given"][item[0]][item[1]]:0; }
				else{ menge[0]=0; }
				menge[1]=Math.max(0,menge[2]-menge[0]-prodStock[item[0]][item[1]]);
				preis=null;
				if(item[0]==0){
					preis=gut[item[1]]; 
					if(!isNaN(NPC[item[0]][item[1]])){ preis=Math.min(preis,NPC[item[0]][item[1]]); }
				}
				newtr=createElement("tr",{},newtable);
				if(!item[3]){ newtr.style.textDecoration="line-through"; }
				newtd=createElement("td",{},newtr);
				produktPic(item[0],item[1],newtd);
				createElement("td",{},newtr,prodName[item[0]][item[1]]);
				createElement("td",{"style":"text-align:right;"},newtr,numberFormat(100*(menge[2]-menge[1])/menge[2])+"%");
				for(var i=0;i<3;i++){
					if((i==0)&&(!questStarted)){ continue; }
					if(item[3]&&(preis!=null)){ sumWert[i] += menge[i]*preis; }
					createElement("td",{"style":"text-align:right;border-left:1px solid white;"},newtr,numberFormat(menge[i]));
					createElement("td",{"style":"text-align:right;padding-left:10px;"},newtr,preis!=null?moneyFormatInt(menge[i]*preis):"--");
				}
			}

			newtr=createElement("tr",{},newtable);
			createElement("td",{"colspan":"2","style":"border-top:1px solid white;"},newtr);
			createElement("td",{"style":"text-align:right;border-top:1px solid white;"},newtr,numberFormat(100*(sumWert[2]-sumWert[1])/(sumWert[2]))+"%");
			for(var i=0;i<3;i++){
				if((i==0)&&(!questStarted)){ continue; }
				createElement("td",{"style":"text-align:right;border-top:1px solid white;","colspan":"2"},newtr,moneyFormatInt(sumWert[i]));
			}
			
			newtable=createElement("table",{"class":"white","border":"0","cellspacing":"0","cellpadding":"3","style":"line-height:16px;"},div);
			newtr=createElement("tr",{},newtable);
			createElement("td",{"style":"vertical-align:top;"},newtr,"Reward:"); // TODO texte
			newtd=createElement("td",{},newtr);
			var newdiv;
			if(questCurr[2]>0){
				pointsFormat(questCurr[2],"div",newtd);
			}
			if(questCurr[3]){
				for(var w=0;w<questCurr[3].length;w++){
					switch(questCurr[3][w][0]){
					case 0:{
						createElement("div",{},newtd,moneyFormat(questCurr[3][w][1]));
					break;}
					case 1:{
						newdiv=createElement("div",{},newtd);
						produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
						createElement("span",{},newdiv,numberFormat(questCurr[3][w][3])+"&nbsp;"+prodName[questCurr[3][w][1]][questCurr[3][w][2]]);
					break;}
					case 2:{
						createElement("div",{},newtd,questCurr[3][w][1]+". rack accessed"); // TODO texte
					break;}
					case 3:{
						createElement("div",{},newtd,questCurr[3][w][1]+". farm accessed"); // TODO texte
					break;}
					case 4:{
						newdiv=createElement("div",{},newtd);
						produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
						createElement("span",{},newdiv,"-"+questCurr[3][w][3]+"min "+prodName[questCurr[3][w][1]][questCurr[3][w][2]]);
					break;}
					case 5:{
						newdiv=createElement("div",{},newtd);
						createElement("img",{"src":GFX+"adbonus.gif","style":"border:0;height:15px;"},newdiv);
						createElement("span",{},newdiv,"Farmi +"+questCurr[3][w][1]);
					break;}
					case 6:{
						createElement("div",{},newtd,"Log rack-amount +"+questCurr[3][w][1]); // TODO texte
					break;}
					case 7:{
						createElement("div",{},newtd,"Watering bonus "+questCurr[3][w][1]+"%"); // TODO texte
					break;}
					case 8:{
						createElement("div",{},newtd,"zone "+questCurr[3][w][1]+" accessed"); // TODO texte
					break;}
					case 9:{
						newdiv=createElement("div",{},newtd);
						produktPic(questCurr[3][w][1],questCurr[3][w][2],newdiv);
						createElement("span",{},newdiv,prodName[questCurr[3][w][1]][questCurr[3][w][2]]+" accessed");
					break;}
					case 10:{
						createElement("div",{},newtd,"Forest watering accessed"); // TODO texte
					break;}
					case 11:{
						newdiv=createElement("div",{},newtd);
						createElement("img",{"src":GFX+"adbonus.gif","style":"border:0;height:15px;"},newdiv);
						createElement("span",{},newdiv,"Farmi slots +"+questCurr[3][w][1]);
					break;}
					}
				}
			}
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr,"Start:"); // TODO texte
			createElement("td",{},newtr,getDateText(questDataCurr["time"])+" "+getDaytimeStr(questDataCurr["time"]));
			
			newdiv=null;newdiv1=null;
			newtable=null;newtr=null;newtd=null;
			return div.innerHTML;
		}catch(err){ GM_log("ERROR questLineMouseOver\n"+err);return err; }
	}
	
	try{
		for(var i=1;i<=2;i++){
			newdiv=$("questboxlinecontent"+i);
			if(newdiv){
				newdiv.addEventListener("mouseover",function(event){
					showToolTip(event,questLineMouseOver("farm",this.id.replace("questboxlinecontent","")));
				},false);
			}
		}
		newdiv=$("questbarcontrol");
		if(newdiv){
			$("garten_komplett").appendChild(newdiv);
			newdiv.style.left="";
			newdiv.style.right="-20px";
			newdiv.style.top="0";
			newdiv.style.marginLeft="360px"; // Fix Seberoth
		}
	}catch(err){ GM_log("ERROR questboxlinecontent "+i+" addEventListener mouseover: "+err); }
	
	unsafeWindow._showQuestBox=unsafeWindow.showQuestBox;
	unsafeWindow.showQuestBox = function(c){
	try{
		unsafeWindow._showQuestBox(c);
	}catch(err){ GM_log("ERROR _showQuestBox\n"+err); }		
	try{
		var cand=$("questboxobjects").getElementsByClassName("questboxbarout");
		for(var i=0;i<cand.length;i++){
			var questWare = parseInt(cand[i].children[0].id.replace("questboxbarin",""),10);
			var menge = [0,0,0]; //given,stock,total
			for(var v in unsafeWindow.questdata[c]["data"][1][0]){
				if(!unsafeWindow.questdata[c]["data"][1][0].hasOwnProperty(v)){ continue; }
				if(typeof unsafeWindow.questdata[c]["data"][1][0][v]=="object"){
					if(unsafeWindow.questdata[c]["data"][1][0][v][questWare]){
						menge[2] = unsafeWindow.questdata[c]["data"][1][0][v][questWare];
					}
				}else{
					if(v==questWare){
						menge[2] = unsafeWindow.questdata[c]["data"][1][0][v];
					}
				}
			}
			menge[0]=((unsafeWindow.questdata[c]["entries"]&&unsafeWindow.questdata[c]["entries"][questWare])?parseInt(unsafeWindow.questdata[c]["entries"][questWare],10):0);
			menge[1]=Math.min(menge[2]-menge[0],prodStock[0][questWare]);
			createElement("div",{"style":"width:"+Math.floor(200*menge[1]/menge[2])+"px;left:"+Math.floor(200*(menge[0])/menge[2])+"px;","class":"questboxbarinPoss"},cand[i]);
			// better number-formatting
			$("questboxobj"+questWare+"_current").innerHTML = numberFormat(menge[0]);
			$("questboxobj"+questWare+"_need").innerHTML = numberFormat(menge[2]);
		}
	}catch(err){ GM_log("ERROR showQuestBox\n"+err); }		
	}

/* todo:
	raiseEvent("gameQuestSolvable");
	raiseEvent("gameQuestNewAvailable");
	raiseEvent("gameQuestFinished");
	raiseEvent("gameQuestAccepted");
*/

	// farmi amount + quest boni
	var farmiZahl=6;
	for(var v=1;v<questData["farm"]["1"]["nr"];v++){
		if(QUESTS["farm"]["1"][v]&&QUESTS["farm"]["1"][v][3]){
			for(var w=0;w<QUESTS["farm"]["1"][v][3].length;w++){
				if(QUESTS["farm"]["1"][v][3][w][0]==5){
					farmiZahl+=QUESTS["farm"]["1"][v][3][w][1];
				}
			}
		}
	}	

	// SHOW RACK DATA
	err_trace="Show rack data";
	function showDataAllProducts(){
	try{
		var container=createElement("div",{"style":"z-index:995;position:absolute;top:0;left:0;background-color:white;height:100%;"},ALL);
		var div=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:0;right:0;width:20px;height:20px;margin:5px;"},container);
		div.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		div=createElement("div",{"style":"height:100%;padding-right:20px;margin-right:30px;overflow:auto;"},container);
		var table=createElement("table",{"border":"1"},div);
		var tr,td,newDiv1;
		for(var type in prodName){
		try{
			if(!prodName.hasOwnProperty(type)){continue;}
			tr=createElement("tr",{"style":"background-color:orange;color:black;"},table);
			createElement("th",{"colspan":"14"},tr,type+": "+["farm","forestry","recipes","powerups"][type]);
			tr=createElement("tr",{"style":"background-color:orange;color:black;"},table);
			createElement("th",{"style":"white-space:nowrap;"},tr,"id");
			createElement("th",{"style":"white-space:nowrap;"},tr,"Name");
			createElement("th",{},tr,"Typ");
			createElement("th",{},tr,"Stock");
			createElement("th",{},tr,"MaxStock");
			createElement("th",{},tr,"MinRack");
			createElement("th",{},tr,"MinRackInit");
			createElement("th",{},tr,"PlantSize");
			createElement("th",{},tr,"Block");
			createElement("th",{},tr,"Require");
			createElement("th",{},tr,"Yield");
			createElement("th",{},tr,"GrowTime");
			createElement("th",{},tr,"Points");
			createElement("th",{},tr,"NPC");
			createElement("th",{},tr,"gut");
			createElement("th",{},tr,"loc");
			for(var v in prodName[type]){
			try{
				if(!prodName[type].hasOwnProperty(v)){continue;}
				tr=createElement("tr",{},table);
				createElement("td",{},tr,v);
				td=createElement("td",{"style":"white-space:nowrap;"},tr);
					produktPic(type,v,td);
					createElement("span",{},td,prodName[type][v]);
				td=createElement("td",{},tr,prodTyp[type][v]);
				td=createElement("td",{},tr,numberFormat(prodStock[type][v]));
				td=createElement("td",{},tr,numberFormat(prodStockMax[type][v]));
				td=createElement("td",{},tr,numberFormat(prodMinRack[type][v]));
				td=createElement("td",{},tr,numberFormat(prodMinRackInit[type][v]));
				td=createElement("td",{},tr,prodPlantSize[type][v]);
				td=createElement("td",{},tr,prodBlock[type][v]);
				td=createElement("td",{},tr);
				if(typeof prodRequire[type][v]=="object"){
					for(var i=0;i<prodRequire[type][v].length;i++){
						if(i>0){ createElement("div",{"style":"display:inline-block;white-space:nowrap;"},td,";&nbsp;"); }
						newDiv1=createElement("div",{"style":"display:inline-block;white-space:nowrap;","class":"hoverBgLightblue","prodType":prodRequire[type][v][i][0],"prodId":prodRequire[type][v][i][1]},td);
						newDiv1.addEventListener("mouseover",function(event){
							showToolTip(event,prodName[this.getAttribute("prodType")][this.getAttribute("prodId")]);
							//showToolTip(event,prodName[parseInt(this.getAttribute("prodType"),10)][parseInt(this.getAttribute("prodId"),10)]);
						},false);
						produktPic(prodRequire[type][v][i][0],prodRequire[type][v][i][1],newDiv1);
						createElement("span",{},newDiv1,numberFormat(prodRequire[type][v][i][2]));
					}
				}
				td=createElement("td",{},tr,prodYield[type][v]);
				td=createElement("td",{},tr,prodGrowTime[type][v]>0?getTimeStr(60*prodGrowTime[type][v],true):"");
				td=createElement("td",{},tr,prodPoints[type][v]==undefined?"-":numberFormat(prodPoints[type][v]));
				td=createElement("td",{},tr);
				if(!NPC[type][v]){
					createElement("span",{},td,"-");
				}else if(!isNaN(NPC[type][v])){
					createElement("span",{},td,moneyFormat(NPC[type][v]));
				}else if (NPC[type][v].match(/^f/)){
					createElement("span",{},td,"*"+moneyFormat(parseFloat(NPC[type][v].replace("f",""),10)));
				}else if (NPC[type][v].match(/^c/)){
					coinsFormat(parseInt(NPC[type][v].replace("c",""),10),td);
				}
				td=createElement("td",{},tr,gut[v]==undefined||type>0?"-":moneyFormat(gut[v]));
				td=createElement("td",{},tr,PRODUCT2BUILDING[type][v]);
			}catch(err){ GM_log("ERROR showDataAllProducts type="+type+" v="+v+"\n"+err); }
			}
		}catch(err){ GM_log("ERROR showDataAllProducts type="+type+"\n"+err); }
		}
		container=null;div=null;
		table=null;tr=null;td=null;newDiv1=null;
	}catch(err){ GM_log("ERROR showDataAllProducts\n"+err); }
	}
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Products", showDataAllProducts);
	
	// SHOW PICNIC PROFIT
	err_trace="Show picnic profit";
	function showProfitPicnic(){
	try{
		var container=createElement("div",{"style":"z-index:995;position:absolute;top:0;left:0;background-color:white;height:100%;"},ALL);
		var div=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:0;right:0;width:20px;height:20px;margin:5px;"},container);
		div.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		div=createElement("div",{"style":"height:100%;padding-right:20px;margin-right:30px;overflow:auto;"},container);
		var newtable,newthead,newtbody,tr,td,newDiv1,help;
		for(var type=1;type<=4;type++){
			newtable=createElement("table",{"border":"1"},div);
			newthead=createElement("thead",{},newtable);
			newtbody=createElement("tbody",{"class":"hoverRowBgLightbrown"},newtable);		
			tr=createElement("tr",{"style":"background-color:orange;color:black;"},newthead);
			createElement("th",{"sortdir":"Asc","class":"link","style":"white-space:nowrap;"},tr,"id");
			createElement("th",{"sortdir":"Asc","class":"link","style":"white-space:nowrap;"},tr,"Name");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Stock");
			createElement("th",{},tr,"Yield");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"GrowTime");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Price");
			createElement("th",{},tr,"Require");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Costs");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Costs/piece");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Profit");
			createElement("th",{"sortdir":"Asc","class":"link"},tr,"Profit/hour");
			new SortableTable(tr);			
			for(var v in prodName[0]){
				try{
					if(!prodName[0].hasOwnProperty(v)){continue;}
					if(!prodBlock[0][v]){
						if(prodTyp[0][v]=="fw"+type){
							tr=createElement("tr",{},newtbody);
							createElement("td",{"value":v},tr,v);
							td=createElement("td",{"value":prodName[0][v],"style":"white-space:nowrap;"},tr);
								produktPic(0,v,td);
								createElement("span",{},td,prodName[0][v]);
							td=createElement("td",{"value":prodStock[0][v]},tr,numberFormat(prodStock[0][v]));
							td=createElement("td",{},tr,prodYield[0][v]);
							td=createElement("td",{"value":prodGrowTime[0][v]},tr,getTimeStr(60*prodGrowTime[0][v],true));
							help=[gut[v]==undefined?0:gut[v],0]
							td=createElement("td",{"value":help[0]},tr,numberFormat(help[0],2));
							help[0]*=prodYield[0][v];
							td=createElement("td",{},tr);
							if(typeof prodRequire[0][v]=="object"){
								for(var i=0;i<prodRequire[0][v].length;i++){
									if(i>0){ createElement("div",{"style":"display:inline-block;white-space:nowrap;"},td,";&nbsp;"); }
									newDiv1=createElement("div",{"style":"display:inline-block;white-space:nowrap;","class":"hoverBgLightblue","prodType":prodRequire[0][v][i][0],"prodId":prodRequire[0][v][i][1]},td);
									newDiv1.addEventListener("mouseover",function(event){
										showGoToMarketToolTip(event,this.getAttribute("prodId"));
									},false);
									produktPic(prodRequire[0][v][i][0],prodRequire[0][v][i][1],newDiv1);
									createElement("span",{},newDiv1,numberFormat(prodRequire[0][v][i][2]));
									if(prodRequire[0][v][i][0]==0){
										help[1]+=gut[prodRequire[0][v][i][1]]*prodRequire[0][v][i][2];
									}
								}
							}
							td=createElement("td",{"value":help[1]},tr,numberFormat(help[1],2));
							td=createElement("td",{"value":Math.round((help[1]/prodYield[0][v])*100)/100},tr,numberFormat(help[1]/prodYield[0][v],2));
							td=createElement("td",{"value":Math.round((help[0]-help[1])*100)/100},tr,numberFormat(help[0]-help[1],2));
							td=createElement("td",{"value":Math.round((60*(help[0]-help[1])/prodGrowTime[0][v])*100)/100},tr,numberFormat(60*(help[0]-help[1])/prodGrowTime[0][v],2));
						}
					}
				}catch(err){ GM_log("ERROR showProfitPicnic v="+v+"\n"+err); }
			}
		}
		newtable=null;newthead=null;newtbody=null;tr=null;td=null;newDiv1=null;help=null;
		container=null;div=null;
	}catch(err){ GM_log("ERROR showProfitPicnic\n"+err); }
	}
	GM_registerMenuCommand(texte["berater"]+" "+"Show Picnic Profit", showProfitPicnic);

	// SHOW ZONE DATA
	err_trace="Show zone data";
	function showDataAllZones(){
	try{
		var prType,zoneNrS,zones=[];
		var style="";
		for(var i in ALL_ZONES){
			if(!ALL_ZONES.hasOwnProperty(i)){ continue; }
			for(var j=0;j<ALL_ZONES[i].length;j++){
				zones.push(ALL_ZONES[i][j].toString());
				if(isMultiSlotZone(ALL_ZONES[i][j])){
					for(var slot=1;slot<=3;slot++){
						zones.push(ALL_ZONES[i][j]+"."+slot);
					}
				}
			}
		}
		var container=createElement("div",{"style":"z-index:995;position:absolute;top:0;left:0;background-color:white;height:100%;"},ALL);
		var div=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:0;right:0;width:20px;height:20px;margin:5px;"},container);
		div.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		div=createElement("div",{"style":"height:100%;padding-right:20px;margin-right:30px;overflow:auto;"},container);
		var table=createElement("table",{"border":"1"},div);
		var tr=createElement("tr",{},table);
		var td=createElement("td",{},tr,"Nr");
		createElement("td",{},tr,"Type(zoneTyp,BUILDINGTYPE)");
		createElement("td",{},tr,"Block");
		createElement("td",{},tr,"AddToGlobalTime");
		createElement("td",{},tr,"Animals");
		createElement("td",{},tr,"Bonus");
		createElement("td",{},tr,"BonusSpecial");
		createElement("td",{},tr,"EndProduct");
		createElement("td",{},tr,"EndTime");
		createElement("td",{},tr,"WaterTime");
		createElement("td",{},tr,"Ernte");
		createElement("td",{},tr,"FieldData");

		
		for(var i=0;i<zones.length;i++){
		try{
			zoneNrS=zones[i];
			style="color:"+(zoneBlock[zoneNrS]?"lightgrey;":"black;");
			tr=createElement("tr",{},table);
			createElement("td",{"style":style},tr,zoneNrS);
			switch(getLocation(zoneNrS)){
			case "windmill":{ prType=3; } break;
			case "forestry":{ prType=1; } break;
			default:{ prType=0; }
			}
			if(zoneTyp[zoneNrS]){
				if(unsafeWindow.buildinginfos[0][zoneTyp[zoneNrS]]){
					createElement("td",{"style":style},tr,unsafeWindow.buildinginfos[0][zoneTyp[zoneNrS]][10]+" ("+zoneTyp[zoneNrS]+","+BUILDINGTYPE[zoneTyp[zoneNrS]]+")");
				}else{
					createElement("td",{"style":style},tr,"("+zoneTyp[zoneNrS]+")");
				}
			}else if(texte[zoneNrS]){
				createElement("td",{"style":style},tr,texte[zoneNrS]+" ("+zoneNrS+")");
			}else{
				createElement("td",{"style":style},tr,"");
			}
			// createElement("td",{},tr,(?(unsafeWindow.buildinginfos[0][zoneTyp[zoneNrS]]?unsafeWindow.buildinginfos[0][zoneTyp[zoneNrS]][10]:zoneTyp[zoneNrS]):zoneNrS));
			createElement("td",{"style":style},tr,zoneBlock[zoneNrS]);
			createElement("td",{"style":style},tr,(isNaN(zoneNrS)?!!zoneAddToGlobalTime[zoneNrS]:true).toString());
			createElement("td",{"style":style},tr,isNaN(zoneAnimals[zoneNrS])?"":numberFormat(zoneAnimals[zoneNrS]));
			createElement("td",{"style":style},tr,isNaN(zoneBonus[zoneNrS])?"":(numberFormat(zoneBonus[zoneNrS])+"%"));
			td=createElement("td",{"style":style},tr);
			if(zoneBonusSpecialAmount[zoneNrS]>0){
				createElement("span",{},td,numberFormat(zoneBonusSpecialAmount[zoneNrS])+"%");
				produktPic(0,zoneBonusSpecialProduct[zoneNrS],td);
				createElement("span",{},td,"("+numberFormat(zoneBonusSpecialProduct[zoneNrS])+")");
			}
			td=createElement("td",{"style":style},tr);
			if(zoneEndProducts[zoneNrS]){
				produktPic(prType,zoneEndProducts[zoneNrS],td);
				createElement("span",{},td,"("+prType+","+zoneEndProducts[zoneNrS]+")");
			}
			td=createElement("td",{"style":style+(zoneEndTimes[zoneNrS]<now?"font-weight:bold;":"")},tr);
			if(zoneEndTimes[zoneNrS]){
				if(zoneEndTimes[zoneNrS]==NEVER){
					createElement("div",{},td,"NEVER");
				} else {
					createElement("div",{},td,getDateText(zoneEndTimes[zoneNrS]));
					createElement("div",{},td,getDaytimeStr(zoneEndTimes[zoneNrS],false,true));
				}
			}
			td=createElement("td",{"style":style+(zoneWaterTimes[zoneNrS]<now?"font-weight:bold;":"")},tr);
			if(zoneWaterTimes[zoneNrS]){
				if(zoneWaterTimes[zoneNrS]==NEVER){
					createElement("div",{},td,"NEVER");
				} else {
					createElement("div",{},td,getDateText(zoneWaterTimes[zoneNrS]));
					createElement("div",{},td,getDaytimeStr(zoneWaterTimes[zoneNrS],false,true));
				}
			}
			td=createElement("td",{"style":style},tr);
			if(zoneErnte[zoneNrS]){
				for(var j=0;j<zoneErnte[zoneNrS].length;j++){
					div=createElement("div",{"style":"white-space:nowrap;"},td);
					produktPic(zoneErnte[zoneNrS][j][0],zoneErnte[zoneNrS][j][1],div);
					createElement("span",{},div,numberFormat(zoneErnte[zoneNrS][j][2])+"(");
					pointsFormat(zoneErnte[zoneNrS][j][3],"span",div);
					createElement("span",{},div,")");
				}
			}
			td=createElement("td",{"style":style},tr);
			if(zoneProductionData[zoneNrS]){
				createElement("div",{"style":"white-space:nowrap;"},td,print_r(zoneProductionData[zoneNrS]));
			}
		}catch(err){ GM_log("ERROR showDataAllZones row zoneNrS="+zoneNrS+"\n"+err); }
		}
		container=null;div=null;
		table=null;tr=null;td=null;
	}catch(err){ GM_log("ERROR showDataAllZones\n"+err); }
	}
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Zones", showDataAllZones);

	/*
	function showDataLodgeFarmi(){
		var div=createElement("div",{"style":"z-index:995;position:fixed;top:0;background-color:white;height:800px;overflow:auto;padding-right:40px;"},ALL);
		var newimg=createElement("img",{"class":"link","src":GFX+"close.jpg","style":"position:absolute;top:8px;right:0px;width:20px;height:20px;"},div);
		newimg.addEventListener("click",function(){ removeElement(this.parentNode); },false);
		var table=createElement("table",{"border":"1"},div);
		var tr=createElement("tr",{},table);
		createElement("td",{"style":"max-width:120px;"},tr,"ID");
		for(var k in prodName[1]){
			if(!prodName[1].hasOwnProperty(k)){continue;}
			if(k>=500){continue;}
			produktPic(1,k,createElement("td",{"style":"max-width:120px;"},tr));
		}
		createElement("td",{"style":"max-width:120px;"},tr,"price");
		createElement("td",{"style":"max-width:120px;"},tr,"points");

		var tr=createElement("tr",{},table);
		createElement("td",{"style":"max-width:120px;"},tr,"ID");
		for(var k in prodName[1]){
			if(!prodName[1].hasOwnProperty(k)){continue;}
			if(k>=500){continue;}
			createElement("td",{"style":"max-width:120px;"},tr,k);
		}

		if(unsafeWindow.forestry_production_products.length>0){
			var tr=createElement("tr",{},table);
			createElement("td",{"style":"max-width:120px;"},tr,"{1}");
			for(var k in prodName[1]){
				if(!prodName[1].hasOwnProperty(k)){continue;}
				if(k>=500){continue;}
				createElement("td",{"style":"max-width:120px;"},tr,unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k]?unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k][1]:"-");
			}
			var tr=createElement("tr",{},table);
			createElement("td",{"style":"max-width:120px;"},tr,"{7}");
			for(var k in prodName[1]){
				if(!prodName[1].hasOwnProperty(k)){continue;}
				if(k>=500){continue;}
				createElement("td",{"style":"max-width:120px;"},tr,unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k]?unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k][7]:"-");
			}
		}

		var farmies=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_forestry_farmies","{}"),"showDataLodgeFarmi/forestry_farmies",{});
		for(var v in farmies){
			if(!farmies.hasOwnProperty(v)){continue;}
			tr=createElement("tr",{},table);
			createElement("td",{},tr,v);
			farmies[v]["products"].sort(function(a,b){return -1*((parseInt(b["product"],10)>parseInt(a["product"],10))-(parseInt(b["product"],10)<parseInt(a["product"],10)));});
			for(var k in prodName[1]){
				if(!prodName[1].hasOwnProperty(k)){continue;}
				if(k>=500){continue;}
				td=createElement("td",{"style":"white-space:nowrap;"},tr);
				for(var i in farmies[v]["products"]){
					if(!farmies[v]["products"].hasOwnProperty(i)){continue;}
					if(farmies[v]["products"][i]["product"]==k){
						createElement("span",{},td,farmies[v]["products"][i]["amount"]);
						//createElement("span",{},td," x ");
						//createElement("span",{},td,farmies[v]["products"][i]["product"]);
						produktPic(1,farmies[v]["products"][i]["product"],td);
					}

				}
			}
			createElement("td",{"style":"white-space:nowrap;"},tr,farmies[v]["price"]);
			createElement("td",{"style":"white-space:nowrap;"},tr,farmies[v]["points"]);
		}
		farmies=null;

		var tr=createElement("tr",{},table);
		createElement("td",{"style":"max-width:120px;"},tr,"ID");
		for(var k in prodName[1]){
			if(!prodName[1].hasOwnProperty(k)){continue;}
			if(k>=500){continue;}
			produktPic(1,k,createElement("td",{"style":"max-width:120px;"},tr));
		}
		createElement("td",{"style":"max-width:120px;"},tr,"price");
		createElement("td",{"style":"max-width:120px;"},tr,"points");

		var tr=createElement("tr",{},table);
		createElement("td",{"style":"max-width:120px;"},tr,"ID");
		for(var k in prodName[1]){
			if(!prodName[1].hasOwnProperty(k)){continue;}
			if(k>=500){continue;}
			createElement("td",{"style":"max-width:120px;"},tr,k);
		}

		if(unsafeWindow.forestry_production_products.length>0){
			var tr=createElement("tr",{},table);
			createElement("td",{"style":"max-width:120px;"},tr,"{1}");
			for(var k in prodName[1]){
				if(!prodName[1].hasOwnProperty(k)){continue;}
				if(k>=500){continue;}
				createElement("td",{"style":"max-width:120px;"},tr,unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k]?unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k][1]:"-");
			}
			var tr=createElement("tr",{},table);
			createElement("td",{"style":"max-width:120px;"},tr,"{7}");
			for(var k in prodName[1]){
				if(!prodName[1].hasOwnProperty(k)){continue;}
				if(k>=500){continue;}
				createElement("td",{"style":"max-width:120px;"},tr,unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k]?unsafeWindow.forestry_production_products[prodTyp[1][k].replace("f","")][k][7]:"-");
			}
		}
	}
	GM_registerMenuCommand(texte["berater"]+" "+"Show Data: Lodge Farmi", showDataLodgeFarmi);
	*/

	// Market
	err_trace="Market";
	function showMarket(pid){
		try{
			if((gameLocation[0]!="city")||(gameLocation[1]!=1)){
				document.addEventListener("gameCity1",function(pid){ return function(){
					document.removeEventListener("gameCity1",arguments.callee,false);
					showMarket(pid);
				};}(pid),false);
				click($("speedlink_city1"));
			}else if($("market").style.display!="block"){
				document.addEventListener("gameOpenMarket",function(pid){ return function(){
					document.removeEventListener("gameOpenMarket",arguments.callee,false);
					showMarket(pid);
				};}(pid),false);
				unsafeWindow.close_page(); 
				unsafeWindow.hideDiv("shop");				
				unsafeWindow.hideDiv("wbwcontainer");				
				unsafeWindow.hideDiv("adcolumn");				
				$("transp3").style.visibility = "visible"; 
				unsafeWindow.showDiv("transp3"); 
				unsafeWindow.marketAction("marketinit");
			}else{
				closeInfoPanel();
				unsafeWindow.market_filter_name="";
				unsafeWindow.market_filter_pid=parseInt(pid,10);
				unsafeWindow.market_filter_own=0;
				unsafeWindow.market_guild_filter=0;
				unsafeWindow.showOffers();			
			}
		}catch(err){ GM_log("ERROR showMarket pid="+pid+"\n"+err); }
	}
	function showMarketStall(){
		try{
			if((gameLocation[0]!="city")||(gameLocation[1]!=1)){
				document.addEventListener("gameCity1",function(){
					document.removeEventListener("gameCity1",arguments.callee,false);
					showMarketStall();
				},false);
				click($("speedlink_city1"));
			}else if($("market").style.display!="block"){
				document.addEventListener("gameOpenMarket",function(){
					document.removeEventListener("gameOpenMarket",arguments.callee,false);
					showMarketStall();
				},false);
				unsafeWindow.close_page(); 
				unsafeWindow.showDiv("transp3"); 
				unsafeWindow.$("transp3").style.visibility = "visible"; 
				unsafeWindow.marketAction("marketinit");
			}else{
				unsafeWindow.setMarketNavi(3);
				unsafeWindow.market_guild_filter = 0;
				unsafeWindow.market_filter_pid = -1;
				unsafeWindow.market_filter_own = 1;
				unsafeWindow.showOffers();				
			}
		}catch(err){ GM_log("ERROR showMarketStall\n"+err); }
	}
	function quicklinks(){
		try{
			if (GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valQuicklinks",true)){
				var newdiv=$("market_navi5");
				if(newdiv){
					newdiv.addEventListener("mouseover",function(event){
						$("quicklinks").style.display="block";
					},false);
					newdiv.addEventListener("mouseout",function(event){
						$("quicklinks").style.display="none";
					},false);
			
					var highlightProducts=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts","[false,{}]"),"quicklinks/highlightProducts",[false,{}]);
					var divquick=createElement("div",{"id":"quicklinks","style":"display:none;position:absolute;right:-75px;top:67px;width:600px;background-color:white;z-index:10;"},newdiv);
					// if(self!=top){
					// 	divquick.addEventListener("mouseover",function(){this.style.left="290px";},false);
					// 	divquick.addEventListener("mouseout",function(){this.style.left="620px";},false);
					// }
		
					var newtable=createElement("table",{"border":"3px solid black;"},divquick);
					var newtr=createElement("tr",{},newtable);
					var newtd=createElement("td",{},newtr);
		
					// newdiv=createElement("div",{"style":"float:right;height:30px;padding:2px;margin-right:20px;"},newtd);
					// createElement("div",{"class":"v88"},newdiv);
					// var newa=createElement("a",{"class":"link2","href":"markt.php","style":"position:relative;top:-30px;"},newdiv);
					// newdiv=createElement("div",{"style":"width:30px;height:30px;background-color:green;opacity:0;"},newa);
					// newdiv.addEventListener("mouseover",function(){this.style.opacity="0.3";$("quicklinksName").innerHTML=texte["aktuelleAngebote"];},false);
					// newdiv.addEventListener("mouseout",function(){this.style.opacity="0";$("quicklinksName").innerHTML="";},false);
					createElement("div",{"id":"quicklinksName","style":"color:black;font-weight:bold;float:right;line-height:30px;padding:2px;margin-right:170px;"},newtd);
		
					var prodTypOld="c";
					for(var w=0;w<prodNameSort[0].length;w++){
						var v=prodNameSort[0][w];
						if((!prodBlock[0][v].match(/t/))&&(!prodBlock[0][v].match(/l/))){
							if (prodTypOld!=prodTyp[0][v]){
								newtr=createElement("tr",{},newtable);
								newtd=createElement("td",{},newtr);
								prodTypOld=prodTyp[0][v];
							}
							newdiv=createElement("div",{"style":"float:left;height:30px;"+(highlightProducts[1][v]?"border:2px solid blue;border-radius:10px;":"padding:2px;")},newtd);
							createElement("div",{"class":"v"+v},newdiv);
							newdiv=createElement("div",{"v":v,"style":"position:relative;top:-30px;width:30px;height:30px;background-color:blue;opacity:0;"},newdiv);
							newdiv.addEventListener("click",function(event){
								event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true); // stop bubbling
								showMarket(this.getAttribute("v"));
								$("quicklinks").style.display="none";
							},false);
							newdiv.addEventListener("mouseover",function(){this.style.opacity="0.3";$("quicklinksName").innerHTML=prodName[0][this.getAttribute("v")];},false);
							newdiv.addEventListener("mouseout",function(){this.style.opacity="0";$("quicklinksName").innerHTML="";},false);
						}
					}
					divquick=null;newtable=null;newtr=null;newtd=null;newa=null;
				}
				newdiv=null;
			}
		}catch(err){ GM_log("ERROR doBuyNotepad ("+err_trace+")\nprod="+prod+" \n"+err); }				
	}
	var valKauflimit=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimit","[[85,'990000'],110]"),"do_main/valKauflimit",[[85,'990000'],110]);
	var valKauflimitNPC=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valKauflimitNPC",true);
	var highlightProducts=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_highlightProducts","[false,{}]"),"do_main/highlightProducts",[false,{}]);
	var highlightUser=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_highlight","{}"),"do_main/highlightUser",{});
	highlightUser[FARMNAME]="104e8b";
	var valNimmBeob=GM_getValue(LNG+"_"+SERVER+"_valNimmBeob",false);

	var valVerkaufLimitDown=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitDown",95);
	var valVerkaufLimitUp=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valVerkaufLimitUp",130);
	var valJoinPreise=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valJoinPreise",false);
	var lastOffer=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lastOffer","[]"),"do_main/lastOffer",[]);
	var protectMinRack=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valProtectMinRack",false);
	var ownMarketOffers=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_ownMarketOffers","{}"),"do_main/ownMarketOffers",{});
	
	// var mode=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeMarket","cveoz");
	GM_addStyle(
		 ".market_buy{width:30px!important;}\n"
		//+".market_carticon{height:16px!important;}" // Bugfix. Game-CSS sets 15px=dis-harmonic to other classes.
		+".market_delicon{height:15px!important;}" // Bugfix. Game-CSS sets 16px=dis-harmonic to class market_carticon.
		+".market_noicon{height:15px!important;}" // Bugfix. Game-CSS sets 16px=dis-harmonic to class market_carticon.
	);
	function do_market(){
	// GM_log("function do_market");
	try{
		var err_trace="Init";
		// GM_addStyle(
		// 	 "div.link2{color:#ffffff!important;}\n"
		// 	+"div.link2:hover{color:#000000!important;}\n"
		// 	+"a.link2:hover{color:#00ddff!important;}\n"
		// 	+"#marketcontainer{overflow:hidden!important;height:325px!important;width:567px!important;}\n"
		// 	+"#initsearchbutton{right:40px!important;}\n"
		// );
	
		// Berater Information Line
		err_trace="market_beraterline";
		var market_beraterline=$("market_beraterline");
		if(!market_beraterline){
			market_beraterline=createElement("div",{"id":"market_beraterline","style":"position:absolute;width:630px;height:40px;bottom:-40px;padding:0 20px 20px 20px;background:url('"+GFX+"market/market_back.jpg') repeat scroll 0px -470px transparent;"},$("market"));
		}
		market_beraterline.innerHTML="";
		for(var i=0;i<7;i++){
			createElement("div",{"style":"float:left;height:40px;width:90px;"},market_beraterline);
		}
		
		// loadProductData();
		var candtable; //document.getElementsByTagName("table");
		var candtr; //candtable[0].getElementsByTagName("tr");
		var row,row_title,canddiv,canda,candtd,newa,newinput,newspan,newdiv,newdiv1;
	
		/*
		var marktButtons=new Array();
		marktButtons[0]=document.querySelector('div[onclick*="\'marktstand.php\'"]'); // market stall
		marktButtons[1]=document.querySelector('div[onclick*="\'markt.php?filter=1&guild=1\'"]');	// club offers
		marktButtons[2]=document.querySelector('div[onclick*="\'markt.php?show=overview\'"]');	// overview
		marktButtons[3]=document.querySelector('div[onclick*="\'markt.php\'"]');	// current offers
		for(var v=0;v<marktButtons.length;v++){
			if(marktButtons[v]){
				marktButtons[v].setAttribute("class","link hoverBlack");
				marktButtons[v].id="marketButton_"+["marktstand","guild","overview","current"][v];
			}
		}
		*/
		/*
		// Market mode
		newdiv=createElement("div",{"id":"offertypeselector","style":"position:absolute;top:0;left:500px;-moz-user-select:none;"},ALL);
		newdiv.addEventListener("mouseover",function(event){
			var mouseOverText=event.target.getAttribute("mouseOverText");
			if(mouseOverText){
				mouseOverText='<div>'+texte["click"]+'&nbsp;/&nbsp;'+texte["clickStrg"]+'</div><div>'+mouseOverText+'</div>';
				showToolTip(event,mouseOverText);
			}
		},false);
		var newdiv1=createElement("div",{"mouseOverText":texte["category"]["v"],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -10px 0px transparent;"},newdiv);
		if (mode.match(/v/)){
			newdiv1.style.backgroundPosition="-10px -20px";
		}else{
			newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-10px 0px";},false);
			newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-10px -20px";},false);
		}
		newdiv1.addEventListener("click",function(event){
			if(event.ctrlKey){
				if(mode.match(/v/)){mode=mode.replace(/v/,"");}
				else{mode += "v";}}
			else{mode="v";}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeMarket",mode);
			location.href=location.href;
		},false);
	
		newdiv1=createElement("div",{"mouseOverText":texte["category"]["c"]+"<br>"+texte["category"]["e"],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -62px 0px transparent;"},newdiv);
		if (mode.match(/c/)&&mode.match(/e/)){
			newdiv1.style.backgroundPosition="-62px -20px";
		}else{
			newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-62px 0px";},false);
			newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-62px -20px";},false);
		}
		newdiv1.addEventListener("click",function(event){
			if(event.ctrlKey){
				if(mode.match(/ce/)){mode=mode.replace(/ce/,"");}
				else{mode += "ce";}}
			else{mode="ce";}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeMarket",mode);
			location.href=location.href;
		},false);
	
		newdiv1=createElement("div",{"mouseOverText":texte["category"]["o"],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -62px 0px transparent;"},newdiv);
		if (mode.match(/o/)&&mode.match(/o/)){
			newdiv1.style.backgroundPosition="-62px -20px";
		}else{
			newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-62px 0px";},false);
			newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-62px -20px";},false);
		}
		newdiv1.addEventListener("click",function(event){
			if(event.ctrlKey){
				if(mode.match(/o/)){mode=mode.replace(/o/,"");}
				else{mode += "o";}}
			else{mode="o";}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeMarket",mode);
			location.href=location.href;
		},false);
	
		newdiv1=createElement("div",{"mouseOverText":texte["category"]["z"],"class":"link","style":"display:inline-block;height:20px;width:26px;background:url('"+GFX+"racksort2.jpg') repeat scroll -36px 0px transparent;"},newdiv);
		if (mode.match(/z/)){
			newdiv1.style.backgroundPosition="-36px -20px";
		}else{
			newdiv1.addEventListener("mouseout",function(){this.style.backgroundPosition="-36px 0px";},false);
			newdiv1.addEventListener("mouseover",function(){this.style.backgroundPosition="-36px -20px";},false);
		}
		newdiv1.addEventListener("click",function(event){
			if(event.ctrlKey){
				if(mode.match(/z/)){mode=mode.replace(/z/,"");}
				else{mode += "z";}}
			else{mode="z";}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeMarket",mode);
			location.href=location.href;
		},false);
		*/
		var pageId=unsafeWindow.market_filter_pid;
		var userId=unsafeWindow.market_filter_name;
		var marktoffers_rows=$("marktoffers_rows");
		if(unsafeWindow.market_filter_own==0){
			// Market page
			err_trace="Market page";
			var nothingToBuy=true;
	
			// Page of a single product
			if((pageId!=-1)&&(userId=="")&&(unsafeWindow.market_guild_filter==0)){
				err_trace="Market page, single product";
				var preisKlasse=0;
				// $("offertypeselector").style.display="none";
	
				newdiv1=createElement("div",{"prod":pageId},market_beraterline.children[0]);
				newdiv1.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);				
				produktPic(0,pageId,newdiv1);
				newspan=createElement("div",{"style":"display:inline-block;"},newdiv1,numberFormat(prodStock[0][pageId],0));
	
				// NPC price
				newdiv1=createElement("div",{},market_beraterline.children[0]);
				err_trace="Market page, single product, NPC";
				if(NPC[0][pageId]){
					if(!isNaN(NPC[0][pageId])){
						newspan=createElement("span",{},newdiv1,"NPC&nbsp;"+numberFormat(NPC[0][pageId],2));
					}else if (NPC[0][pageId].match(/^f/)){
						newspan=createElement("span",{},newdiv1,"*NPC*&nbsp;"+numberFormat(parseFloat(NPC[0][pageId].replace("f",""),10),2));
					}else if (NPC[0][pageId].match(/^c/)){
						newspan=createElement("span",{},newdiv1,"NPC&nbsp;<span style='display:inline-block;vertical-align:bottom;'>"+coinsFormat(parseInt(NPC[0][pageId].replace("c",""),10)).innerHTML+"</span>");
						//coinsFormat(parseInt(NPC[0][pageId].replace("c",""),10),newdiv).style.cssFloat="right";
					}
					if((NPCSAISON[pageId]!=undefined)&&(!NPCSAISON[pageId])){
						newspan.style.textDecoration="line-through";
						newspan.setAttribute("class","hoverNoTextDecoration");
					}
				}else{
					createElement("span",{},newdiv1,"NPC&nbsp;--");
				}
				// Link to previous/next product
				err_trace="Market page, single product, prev/next";
				var c=0;
				while ((c<prodNameSort[0].length)&&(prodNameSort[0][c]!=pageId)){ c++; }
				var pageIdVor=c-1;
				if(pageIdVor<0){ pageIdVor+=prodNameSort[0].length; }
				while(prodBlock[0][prodNameSort[0][pageIdVor]].match(/t/)||prodBlock[0][prodNameSort[0][pageIdVor]].match(/l/)){
					pageIdVor--;
					if(pageIdVor<0){ pageIdVor+=prodNameSort[0].length; }
				}
				pageIdVor=prodNameSort[0][pageIdVor];
				var pageIdNach=c+1;
				if(pageIdNach>prodNameSort[0].length-1){ pageIdNach=0; }
				while(prodBlock[0][prodNameSort[0][pageIdNach]].match(/t/)||prodBlock[0][prodNameSort[0][pageIdNach]].match(/l/)){
					pageIdNach++;
					if(pageIdNach>prodNameSort[0].length-1){ pageIdNach=0; }
				}
				pageIdNach=prodNameSort[0][pageIdNach];
				newdiv1=createElement("div",{},market_beraterline.children[0]);
				newspan=createElement("div",{"class":"link2","style":"display:inline-block;padding-right:2px;","prod":pageIdVor},newdiv1,"<<");
				newspan.addEventListener("click",function(event){ showMarket(this.getAttribute("prod")); },false);
				newspan.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
				newspan=createElement("div",{"class":"link2","style":"display:inline-block;","prod":pageIdNach},newdiv1,">>");
				newspan.addEventListener("click",function(event){ showMarket(this.getAttribute("prod")); },false);
				newspan.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
	
				// Total amount of all offers
				// newtd=createElement("td",{"align":"right","style":"border-top:1px solid;"});
				// newtd.innerHTML=numberFormat(sumTotal,0);
				// candtr[candtr.length-1].insertBefore(newtd,candtr[candtr.length-1].firstElementChild);
	
				// Set price field
				err_trace="Market page, single product, set price";
				newdiv1=createElement("div",{},market_beraterline.children[1]);
				newinput=createElement("input",{"id":"marketButton_price","value":numberFormat(gut[pageId],2),"class":"text","maxlength":"10","style":"width:65px;text-align:right;background-color:#589456;"},newdiv1);
				newinput.addEventListener("mouseover",function(event){ showToolTip(event,texte["preis"]+"<br>"+texte["beobachtet"]+":&nbsp;"+moneyFormat(gutBeob[pageId])); },false);
				if(valNimmBeob){
					newinput.readOnly=true;
				}else{
					newinput.addEventListener("focus",function(){
						this.style.backgroundColor="white";
						unsafeWindow.clearMarketTimer();
					},false);
					newinput.addEventListener("blur",function(){
						this.style.backgroundColor="#589456";
						if(!unsafeWindow.market_timer['update']){ unsafeWindow.market_timer['update'] = unsafeWindow.setInterval("marketTimer()",1000); }
					},false);
					newinput.addEventListener("change",function(){
						var currId=unsafeWindow.market_filter_pid;
						var preis=Math.max(0,parseFloat(this.value.replace(regDelimThou,"").replace(regDelimDeci,"."),10));
						var thisNode=this;
						var yesFkt = function(){
							gut[currId]=preis;
							GM_setValueCache(LNG+"_"+SERVER+"_gut",implode(gut));
							raiseEventTop("gameChangedGut");
							unsafeWindow.showOffers();
							if(!unsafeWindow.market_timer['update']){ unsafeWindow.market_timer['update'] = unsafeWindow.setInterval("marketTimer()",1000); }
						};
						var noFkt = function(){
							thisNode.value=numberFormat(gut[currId],2);
							thisNode=null;
						};
						if(preis==0){
							alert2(texte["alertSetPriceNone"].replace(/%PRODUCT%/,prodName[0][currId]),texte["yes"],texte["no"],yesFkt,noFkt);
						}else if((!isNaN(NPC[0][currId]))&&(preis>NPC[0][currId])){
							alert2(texte["alertSetPriceOverNPC"].replace(/%PRODUCT%/,prodName[0][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%NPC%/,moneyFormat(NPC[0][currId])),texte["yes"],texte["no"],yesFkt,noFkt);
						}else if ((gutBeob[currId]!=undefined)&&(gutBeob[currId]>0)){
							if(preis<0.7*gutBeob[currId]){
								alert2(texte["alertSetPriceUnderObs"].replace(/%PRODUCT%/,prodName[0][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%OBS%/,moneyFormat(gutBeob[currId])),texte["yes"],texte["no"],yesFkt,noFkt);
							}else if (1.3*gutBeob[currId]<preis){
								alert2(texte["alertSetPriceOverObs"].replace(/%PRODUCT%/,prodName[0][currId]).replace(/%PRICE%/,moneyFormat(preis)).replace(/%OBS%/,moneyFormat(gutBeob[currId])),texte["yes"],texte["no"],yesFkt,noFkt);
							}else{
								yesFkt();
							}
						}else{
							yesFkt();
						}
					},false);
				}

				// Statistic server
				err_trace="Market page, single product, Statistic";
				if (STAT_VIEW && STAT_VIEW[LNG]){
					newdiv1=createElement("div",{"id":"marketButton_stats","class":"link2 hoverBlack","style":"position:relative;width:80px;height:40px;background: url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},market_beraterline.children[2]);
					createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;"},newdiv1,texte["statistik"]);
					newdiv1.addEventListener("click",function(){
						showStatisticFullscreen(unsafeWindow.market_filter_pid);
					},false);
				}
			}else{
				var preisKlasse=2;
			}
	
			if(pageId!=-1){
				//Link to NPC-Shop
				err_trace="Link to NPC";
				if(nothingToBuy && (unsafeWindow.marketlist_currentpage==1) && (prodTyp[0][pageId]=="v") && $top("shop")){
					newdiv1=createElement("div",{"id":"marketButton_npc","class":"link2 hoverBlack","style":"position:relative;width:80px;height:40px;background: url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0 0 transparent;"},market_beraterline.children[3]);
					createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;"},newdiv1,texte["SGH"]);
					newdiv1.addEventListener("click",showSGH,false);
				}
			}
	
			// Page of a single user
			/*
			if(userId!=""){
				canda=candtr[3].getElementsByTagName("a");
				if(canda[1]){ var thisUser=canda[1].innerHTML; }
				newtr=createElement("tr",{},candtable[0]);
				newtd=createElement("td",{},newtr);
				if (thisUser){igm(thisUser,newtd);}
				stats(userId,newtd);
			}
			*/
		}
		
		// Redesign of table
		err_trace="Redesign";
		var currId, currOffer, time, sum=[0,0];
		for(var v=0;v<marktoffers_rows.childElementCount;v++){
			err_trace="Redesign, row "+v;
			row=marktoffers_rows.children[v];
			if(row.childElementCount<6){ continue; }
			currId=/market_price_tt(\d+)/.exec(row.children[2].getAttribute("onmouseover"))[1];
			currOffer=null;
			for(var i=0;i<unsafeWindow.market_offers.length;i++){
				if(currId==unsafeWindow.market_offers[i].id){
					currOffer=unsafeWindow.market_offers[i];
					break;
				}
			}
			if(!currOffer){ continue; }
			row.children[3].removeAttribute("onmouseover");
			row_title=$("market_amount_tt"+currOffer["id"]);
			help=createElement("div",{},false,row_title.innerHTML);
			row_title.innerHTML="";
			row_title.appendChild(help);
			// TODO(Seberoth): What is time now?
			if(currOffer["zeit"]){
				time=parseInt(currOffer["zeit"],10)+0;
				if(countDays(time,now)==0){
					createElement("div",{},row_title,texte["seitX"].replace(/%1%/,getDaytimeStr(time,false,true)+"&nbsp;"+texte["uhr"]));
				}else{
					createElement("div",{},row_title,texte["seitX"].replace(/%1%/,getFormattedDateStr(time,2,false)+",&nbsp;"+getDaytimeStr(time,false,true)+"&nbsp;"+texte["uhr"]));
				}
			}
			var prodId=parseInt(currOffer["p"],10);
			var menge=parseInt(currOffer["a"],10);
			var preis=parseFloat(currOffer["pr"],10);
			if((pageId!=-1)&&(userId=="")&&(unsafeWindow.market_guild_filter==0)){
				createElement("div",{},row_title,texte["davor"]+": "+numberFormat(sum[0]));
			}
			sum[0] += menge;
			sum[1] += menge*preis;
			row.children[2].innerHTML=numberFormat(preis,2);
			row.setAttribute("offerId",currOffer["id"]);
			//GutPreis zeigen
			newdiv=createElement("div",{},false,numberFormat(gut[prodId],2));
			row.insertBefore(newdiv,row.children[6]);
			// own offers
			if((unsafeWindow.market_filter_own==0)&&(currOffer["s"])){
				row.children[5].setAttribute("class","market_buy market_noicon");
				row.children[5].setAttribute("onclick","");
			}
			if(NPC[0][prodId]&&((NPCSAISON[prodId]==undefined)||(NPCSAISON[prodId]))&&(preis>=NPC[0][prodId])){
				if(preisKlasse<1){
					preisKlasse++;
					row.style.borderTop="2px solid white";
				}
				if(valKauflimitNPC&&row.children[5]){ //zu teuer Link entfernen (NPC)
					if(unsafeWindow.market_filter_own==0){
						row.children[5].setAttribute("class","market_buy market_noicon");
						row.children[5].setAttribute("onclick","");
					}
					createElement("div",{},row_title,texte["ueberNPC"]+" ("+numberFormat(NPC[0][prodId],2)+")");
				}
				row.style.opacity="0.5";
				row.children[5].style.fontStyle="italic";
				if (0.9*preis>NPC[0][prodId]){ //111% NPC
					row.style.fontStyle="italic";
					if(preisKlasse<2){
						preisKlasse++;
						row.style.borderTop="2px dashed white";
					}
				}
			}else if(gut[prodId]!=0){
				var help=100*preis/gut[prodId];
				if(help<=valKauflimit[0][0]){
					if(row.children[5]){ row.children[5].style.backgroundColor="#"+valKauflimit[0][1]; } //billig Angebot highlight
				}else if(help>valKauflimit[1]){ //zu teuer Link entfernen (Limit)
					if(row.children[5]){
						if(unsafeWindow.market_filter_own==0){
							row.children[5].setAttribute("class","market_buy market_noicon");
							row.children[5].setAttribute("onclick","");
						}
						createElement("div",{},row_title,texte["ueberX"].replace(/%1%/,valKauflimit[1]+"%"));
					}
					row.style.opacity="0.7";
				}
			}
			if(row.children[5].getAttribute("class").search(/market_noicon/)==-1){ nothingToBuy=false; }
			
			if (row.children[4].children[0]&&(highlightUser[row.children[4].children[0].innerHTML])){
				row.children[4].children[0].style.backgroundColor="#"+highlightUser[row.children[4].children[0].innerHTML];
			}
			if (highlightProducts[1][prodId]){
				row.children[1].style.backgroundColor="#20b2aa";
			}
			row.addEventListener("mouseover",function(event){ showToolTip(event,$("market_amount_tt"+this.getAttribute("offerId")).innerHTML); },false);
		}
		if((unsafeWindow.market_filter_own==1)&&(userId=="")&&(unsafeWindow.market_guild_filter==0)){
			createElement("div",{},market_beraterline.children[0],sign_sum+"&nbsp;"+moneyFormatLimit(sum[1],100000));
		}
		// No offers
		if(sum[0]==0){
			// Page of a single product
			if((unsafeWindow.market_filter_own==0)&&(pageId!=-1)&&(userId=="")&&(unsafeWindow.market_guild_filter==0)){
				newdiv=createElement("div",{"style":"padding:2px;"},marktoffers_rows);
				createElement("div",{"style":"float:left;","class":"kp"+pageId},newdiv);
				createElement("div",{"onclick":"market_filter_name=''; market_filter_pid="+pageId+"; showOffers();","class":"market_product underline link","title":prodName[0][pageId]},newdiv,prodName[0][pageId]);
				if(NPC[0][pageId]){
					if((NPCSAISON[pageId]!=undefined)&&(!NPCSAISON[pageId])){
						createElement("div",{"class":"market_price"},newdiv);
						createElement("div",{"class":"market_amount"},newdiv);
						createElement("div",{"class":"market_seller"},newdiv);
					}else if(!isNaN(NPC[0][pageId])){
						createElement("div",{"class":"market_price"},newdiv,numberFormat(NPC[0][pageId],2));
						createElement("div",{"class":"market_amount"},newdiv,"0");
						newdiv1=createElement("div",{"class":"market_seller"},newdiv);
						createElement("span",{},newdiv1,"NPC");
					}else if (NPC[0][pageId].match(/^f/)){
						createElement("div",{"class":"market_price"},newdiv,numberFormat(3*parseFloat(NPC[0][pageId].replace("f",""),10),2));
						createElement("div",{"class":"market_amount"},newdiv,"0");
						newdiv1=createElement("div",{"class":"market_seller"},newdiv);
						createElement("span",{},newdiv1,"*NPC*");
					}else{
						createElement("div",{"class":"market_price"},newdiv);
						createElement("div",{"class":"market_amount"},newdiv);
						createElement("div",{"class":"market_seller"},newdiv);
					}
				}else{
					createElement("div",{"class":"market_price"},newdiv);
					createElement("div",{"class":"market_amount"},newdiv);
					createElement("div",{"class":"market_seller"},newdiv);
				}			
			}
		}
		marktoffers_rows=null;
		// Buttons
		err_trace="buttons";
		/*
		newdiv=createElement("div",{"id":"marketButton_current","class":"link hoverBlack","style":"position:absolute;top:475px;left:545px;width:80px;height:40px;font-size:8pt;background: url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},ALL);
		newdiv.addEventListener("click",function(){showMarket();},false);
		createElement("div",{"style":"position:absolute;top:7px;left:7px;width:67px;color:white;font-weight: bold;"},newdiv,texte["aktuelleAngebote"]);
		*/
		newdiv1=createElement("div",{"id":"marketButton_tablePrices","class":"link2 hoverBlack","style":"position:relative;width:80px;height:40px;background:url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},market_beraterline.children[4]);
		newdiv1.addEventListener("click",function(){
			buildInfoPanel("preise",unsafeWindow.market_filter_pid?prodTyp[0][unsafeWindow.market_filter_pid]:null);
		},false);
		createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;"},newdiv1,texte["preise"]);
	
		newdiv1=createElement("div",{"id":"marketButton_tableStock","class":"link2 hoverBlack","style":"position:relative;width:80px;height:40px;background:url('"+GFX+"stadt/uebersicht.gif') repeat scroll 0% 0% transparent;"},market_beraterline.children[5]);
		newdiv1.addEventListener("click",function(){
			buildInfoPanel("preise2",unsafeWindow.market_filter_pid?prodTyp[0][unsafeWindow.market_filter_pid]:null);
		},false);
		createElement("div",{"style":"position:absolute;top:13px;width:80px;font-weight:bold;text-align:center;"},newdiv1,texte["stock"]);
	
		market_beraterline=null;
		canda=null;candtable=null;candtr=null;candtd=null;canddiv=null;newa=null;newinput=null;newspan=null;newdiv=null;newdiv1=null;
	}catch(err){ GM_log("ERROR do_market ("+err_trace+")\n"+err); }
	}
	unsafeWindow._showOffers=unsafeWindow.showOffers;
	unsafeWindow.showOffers = function(page){
		unsafeWindow._showOffers(page);
		do_market();
		// GM_log("unsafeWindow.market_offers:\n"+print_r(unsafeWindow.market_offers,"",true,"\n"));		
		raiseEvent("gameOpenMarket");
	};
	unsafeWindow._openMarketNewOffer=unsafeWindow.openMarketNewOffer;
	unsafeWindow.openMarketNewOffer = function(){
		unsafeWindow._openMarketNewOffer();
		try{
			var err_trace="Init";
			var currId=unsafeWindow.market_filter_pid;
			if(currId!=-1){
				if(lastOffer[currId]){
					$("marketnewoffer_amount").value=lastOffer[currId][0];
					$("marketnewoffer_price1").value=lastOffer[currId][1];
					$("marketnewoffer_price2").value=(lastOffer[currId][2]<10?"0":"")+lastOffer[currId][2];
					if($("marketnewoffer_price_comb")){ $("marketnewoffer_price_comb").value=lastOffer[currId][1]+delimDeci+(lastOffer[currId][2]<10?"0":"")+lastOffer[currId][2]; }
				}else{
					$("marketnewoffer_amount").value=0;
				}
				keyup($("marketnewoffer_amount"));
		
				/*
				if ($("produkt_preis1")){
					$("lbl_produkt_max").setAttribute("class",$("lbl_produkt_max").getAttribute("class")+" link");
					$("lbl_produkt_max").addEventListener("click",function(){
						$("produkt_anzahl").value=this.innerHTML.replace(regDelimThou,"");
						keyup($("produkt_anzahl"));
					},false);
					$("produkt_anzahl").addEventListener("focus",checkPreis,false); // fired when offer-div opens
					$("preisschild").addEventListener("keyup",function(event){
						checkPreis();
						if (event.keyCode==13){
							var submitButton=$("preisschild").querySelector("#verkaufe_markt");
							if(submitButton.style.display!="none"){ click(submitButton); }
							submitButton=null;
						}
					},false);
					if(valJoinPreise){
						$("produkt_preis1").setAttribute("tabindex","0");
						$("produkt_preis2").setAttribute("tabindex","0");
						var newinput=createElement("input",{"id":"produkt_preis_ganz","type":"text","style":"position:absolute;left:0;top:0;background-color:#002300;color:#f0ffef;width:131px;text-align:right;border:1px solid #555;","tabindex":"2","maxlength":"9","name":"p_preis_ganz","class":"text thuge"},$("produkt_preis1").parentNode);
						newinput.addEventListener("keyup",function(event){
							if (event.keyCode==13){
								var submitButton=$("preisschild").querySelector("#verkaufe_markt");
								if(submitButton.style.display!="none"){ click(submitButton); }
								submitButton=null;
							}else{
								var preis=this.value.replace(regDelimThou,"").replace(regDelimDeci,".");
								var preis1=parseInt(preis,10);
								var preis2=(preis.search(/\./)!=-1?(preis+"00").substr(1+preis.search(/\./),2):"00");
								$("produkt_preis1").value=preis1;
								$("produkt_preis2").value=preis2;
								keyup($("produkt_preis1"));
							}
						},false);
						newinput=null;
					}
				}
				*/
				
				// coins
				function checkPreisCoins(){
					//GM_log("checkPreisCoins "+oldPricesInserted);
					window.setTimeout(function(){ // first let finish the functions
						if(oldPricesInserted==0){ //old offer set
							lastOffer[0]=[parseInt($("coinsanzahl").value,10),parseInt($("coinspreis").value,10),$("coinssollpreis").checked];
							try{
								GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lastOffer",implode(lastOffer));
							}catch(err){ GM_log("checkPreisCoins: 0 not saved!\n"+err); }
						}else{
							oldPricesInserted=0;
							if(lastOffer[0]){
								$("coinsanzahl").value=lastOffer[0][0];
								$("coinspreis").value=lastOffer[0][1];
								$("coinssollpreis").checked=lastOffer[0][2];
								unsafeWindow.chkAmount();
								unsafeWindow.calcMarketPrice();
							}
						}
						var currPreis=parseInt($("coinsmarktpreis").innerHTML,10);
						var currAnzahl=parseInt($("coinsanzahl").value,10);
						var currUserPreis=parseInt($("coinsuserpreis").innerHTML,10);
			
						if(protectMinRack){ //rack amount protection
							prodStock[0][0]=parseInt($("lbl_produkt_max").innerHTML.replace(regDelimThou,""),10);
							if(currAnzahl>prodStock[0][0]-prodMinRack[0][0]){
								currAnzahl=Math.max(0,prodStock[0][0]-prodMinRack[0][0]);
								$("coinsanzahl").value=currAnzahl;
							}
						}
						var newtable=createElement("table");
						var newtr;
						$("divBerInfoCoins").replaceChild(newtable,$("divBerInfoCoins").getElementsByTagName("table")[0]);
						if (gut[0]){
							$("coinspreisschild").querySelector("#verkaufe_markt").style.display=(((100*currPreis>valVerkaufLimitDown*gut[0]) && (100*currPreis<valVerkaufLimitUp*gut[0]))?"":"none");
							newtr=createElement("tr",{},newtable);
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["preis"]+": ");
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(gut[0],100));
						}
			
						newtr=createElement("tr",{},newtable);
						createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["wert"]+": ");
						createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(currUserPreis*currAnzahl,100));
			
						newtr=createElement("tr",{},newtable);
						createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["commission"]+": ");
						createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,numberFormat(((currPreis-currUserPreis)/currUserPreis)*100,1)+"%");
						if (preisBeob[0]){
							newtr=createElement("tr",{},newtable);
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,"min: ");
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(preisBeob[0][2],100));
						}
						if (gutBeob[0]){
							newtr=createElement("tr",{},newtable);
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["beobachtet"]+": ");
							createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(gutBeob[0],100));
						}
						newtable=null;newtr=null;
					},200);
				}
			/*
				if($("coinsauflager")){
					$("coinsauflager").setAttribute("class",$("coinsauflager").getAttribute("class")+" link");
					$("coinsauflager").addEventListener("click",function(){
						$("coinsanzahl").value=this.innerHTML;
						keyup($("coinsanzahl"));
					},false);
				}
				if($("coinspreisschild")){
					var newdiv=createElement("div",{"style":"position:absolute;top:0;left:330px;width:150px"},$("coinspreisschild"));
					newdiv=createElement("div",{"id":"divBerInfoCoins","style":"float:left;padding:3px;background-color:#002300;border:5px solid #594230;color:#f0ffef;font-weight:bold;"},newdiv);
					createElement("table",{},newdiv);
					newdiv=null;
			
					$("coinsanzahl").addEventListener("keyup",function(){ this.value=this.value.replace(/\D/g,""); },false);
					$("coinspreis").addEventListener("keyup",function(){ this.value=this.value.replace(/\D/g,""); },false);
					$("coinspreisschild").addEventListener("click",checkPreisCoins,false);
					$("coinspreisschild").addEventListener("keyup",function(event){
						checkPreisCoins();
						if (event.keyCode==13){
							var submitButton=$("preisschild").querySelector("#verkaufe_markt");
							if(submitButton.style.display!="none"){ click(submitButton); }
							submitButton=null;
						}
					},false);
			
					// bugfix: no focus when coinspreisschild opens
					$("coinspreisschild").addEventListener("DOMAttrModified",function(event){
						if((event.target.id=="coinspreisschild")&&(event.attrName=="style")){
							if(event.newValue.match(/display\:\s*block/)){
								if(oldPricesInserted!=0){
									checkPreisCoins(); // fired when offer-div opens
								}
							}else{
								if(oldPricesInserted==0){ oldPricesInserted=-1; }
							}
						}
					}, false);
				}
			
				cand=null;candtable=null;
*/		
			}
		}catch(err){ GM_log("ERROR openMarketNewOffer ("+err_trace+")\n"+err); }
	};

	unsafeWindow._calcMarketFee=unsafeWindow.calcMarketFee;
	unsafeWindow.calcMarketFee = function(){
		unsafeWindow._calcMarketFee();
		try{
			var err_trace="Init";
			var berater_box=$("marketnewoffer_berater");
			if(!berater_box){
				berater_box=createElement("div",{"style":"position:absolute;top:0px;width:175px;right:-160px;background-position:-140px 0px;","class":"market_popup"});
				newdiv=$("marketnewoffer");
				newdiv.insertBefore(berater_box,newdiv.lastElementChild);
				berater_box=createElement("div",{"id":"marketnewoffer_berater","style":"position:relative;margin-top:35px;"},berater_box);
			}
			berater_box.innerHTML="";
			var currId=unsafeWindow.market_filter_pid;
			if(currId!=-1){
				var currPreis=parseFloat($("marketnewoffer_price1").value+"."+$("marketnewoffer_price2").value,10);
				var currAnzahl=parseInt($("marketnewoffer_amount").value,10);
				// Stock amount
				err_trace="Stock amount";
				var newdiv;
				if(newdiv=$("marketcreateoffer_stockamount")){
					newdiv.innerHTML=numberFormat(prodStock[0][currId]);
				}				
				// Rack amount protection
				err_trace="Rack amount protection";
				if(protectMinRack){ 
					if(currAnzahl>prodStock[0][currId]-prodMinRack[0][currId]){
						currAnzahl=Math.max(0,prodStock[0][currId]-prodMinRack[0][currId]);
						$("marketnewoffer_amount").value=currAnzahl;
					}
				}
				// Block Submit Button
				err_trace="Submit Button";
				var submitButton = $("market_new_button");
				if(submitButton){
					var help=null;
					if(NPC[0][currId]){
						if(!isNaN(NPC[0][currId])){
							if(100*currPreis<20*NPC[0][currId]){ help=3; }
							else if(100*currPreis>300*NPC[0][currId]){ help=4; }
						}else if (NPC[0][currId].match(/^f/)){
							if(100*currPreis<2*parseFloat(NPC[0][currId].replace("f",""),10)){ help=3; }
							else if(100*currPreis>300*parseFloat(NPC[0][currId].replace("f",""),10)){ help=4; }
						}
					}
					if((help!=null)&&gut[currId]){
						if(100*currPreis<valVerkaufLimitDown*gut[currId]){ help=1; }
						else if(100*currPreis>valVerkaufLimitUp*gut[currId]){ help=2; }
					};
					if(help==null){
						submitButton.style.display="block";
						newdiv = $("market_new_button_block");
						if(newdiv){ newdiv.style.display="none"; }
					}else{
						submitButton.style.display="none";
						newdiv = $("market_new_button_block");
						if(!newdiv){
							newdiv=createElement("div",{"id":"market_new_button_block","class":"alertbox","style":"padding:2px;width:100%;text-align:center;"});
							insertAfter(newdiv,submitButton);
						}
						newdiv.style.display="block";
						switch(help){
						case 1: newdiv.innerHTML = "Too cheap"; break;
						case 2: newdiv.innerHTML = "Too expensive"; break;
						case 3: newdiv.innerHTML = "Not allowed - Too cheap"; break;
						case 4: newdiv.innerHTML = "Not allowed - Too expensive"; break;
						}
					}
					help=null;
				}
				submitButton=null;
				// Info Boards
				err_trace="berater_box";
				var newtable=createElement("table",{},berater_box);
				var newtr;
				newtr=createElement("tr",{},newtable);
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["preis"]+": ");
				if(gut[currId]){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(gut[currId],100));
				} else {
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,"--");
				}
				newtr=createElement("tr",{},newtable);
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["wert"]+": ");
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(currPreis*currAnzahl,100));
				newtr=createElement("tr",{},newtable);
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,"min: ");
				if (preisBeob[currId]){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(preisBeob[currId][2],100));
				}else{
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,"--");
				}
				newtr=createElement("tr",{},newtable);
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["beobachtet"]+": ");
				if (gutBeob[currId]){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(gutBeob[currId],100));
				}else{
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,"--");
				}
				newtr=createElement("tr",{},newtable);
				createElement("td",{"style":"color:#f0ffef;font-weight:bold;"},newtr,texte["hofpreis"]+": ");
				if(!NPC[0][currId]){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,"--");
				}else if(!isNaN(NPC[0][currId])){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,moneyFormatLimit(NPC[0][currId],100));
				}else if (NPC[0][currId].match(/^f/)){
					createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr,"*"+moneyFormatLimit(parseFloat(NPC[0][currId].replace("f",""),10),100));
				}else if (NPC[0][currId].match(/^c/)){
					coinsFormat(parseInt(NPC[0][currId].replace("c",""),10),createElement("td",{"style":"color:#f0ffef;font-weight:bold;text-align:right;"},newtr));
				}
				newtable=null;newtr=null;newdiv=null;
			}
			currId=null;
		
		}catch(err){ GM_log("ERROR calcMarketFee\n"+err); }
	}

	unsafeWindow._buyMarketOffer=unsafeWindow.buyMarketOffer;
	unsafeWindow.buyMarketOffer = function(id){
		unsafeWindow._buyMarketOffer(id);
		try{
			for(var i=0;i<unsafeWindow.market_offers.length;i++){
				if(id==unsafeWindow.market_offers[i].id){
					var money=parseFloat($("bar").innerHTML.replace(texte["waehrung"],"").replace(/\s+/g,"").replace(regDelimThou,"").replace(regDelimDeci,"."),10);
					$("marketbuyofferamount").value = Math.min(unsafeWindow.market_offers[i].a,Math.floor(money/unsafeWindow.market_offers[i].pr));
					unsafeWindow.calcMarketOfferCost();
					money=null;
					break;
				}
			}	
		}catch(err){ GM_log("ERROR buyMarketOffer\n"+err); }
	}
	
	unsafeWindow._marketAction=unsafeWindow.marketAction;
	unsafeWindow.marketAction = function(action,id,open){
		unsafeWindow._marketAction(action,id,open);
		try{
			if(action=="marketcreateoffer"){
				var currId=unsafeWindow.market_filter_pid;
				var amount=parseInt($("marketnewoffer_amount").value,10);
				var price1=parseInt($("marketnewoffer_price1").value,10);
				var price2=parseInt($("marketnewoffer_price2").value,10);
				lastOffer[currId]=[amount,price1,price2];
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_lastOffer",implode(lastOffer));
				currId=null;amount=null;price1=null;price2=null;
			}
		}catch(err){ GM_log("ERROR marketAction\n"+err); }
	};
	unsafeWindow._marketActionResponse=unsafeWindow.marketActionResponse;
	unsafeWindow.marketActionResponse = function(request,action,id,open){
		try{
			var result = unsafeWindow._chkRequest(request)
			if((result!=0)&&(result[0]!=0)&&(result[1]["offers"])){
				//GM_log("marketActionResponse "+result[1]["offers"].length);					
				// Save own offers
				var err_trace="Save own offers";
				var _ownMarketOffers=new Object();
				var marketOffersArr=new Array();
				var row,prod,preis,menge,menge_sum;
				err_trace="Save own offers";
				for(var v=0;v<result[1]["offers"].length;v++){
					row=result[1]["offers"][v];
					prod=parseInt(row["p"],10);
					preis=parseFloat(row["pr"],10);
					menge=parseInt(row["a"],10);
					if(row["s"]){
						if(!_ownMarketOffers[prod]){ _ownMarketOffers[prod]=new Object(); }
						_ownMarketOffers[prod][preis]=(_ownMarketOffers[prod][preis]?_ownMarketOffers[prod][preis]:0)+menge;
					}
					if(!marketOffersArr[prod]){ marketOffersArr[prod]=new Array(); }
					// TODO(Seberoth): What is time again?
					// marketOffersArr[prod].push([menge,preis,parseInt(row["zeit"],10)]);
					marketOffersArr[prod].push([menge,preis]);
				}
				// sort the ownMarketOffers-data
				_ownMarketOffers.sortObj(sortObjFunctions["productId"]);
				for(var v in _ownMarketOffers){
					if(!_ownMarketOffers.hasOwnProperty(v)){ continue; }
					_ownMarketOffers[v].sortObj(sortObjFunctions["float"]);
				}
				ownMarketOffers=_ownMarketOffers;
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_ownMarketOffers",implode(ownMarketOffers));			
				doMarketoffersNotepad();
				// calculate all observed prices
				err_trace="Observing prices";
				for(var v=0;v<prodBlock[0].length;v++){
					if((!prodBlock[0][v].match(/t/))&&(!prodBlock[0][v].match(/l/))){
						if(marketOffersArr[v]){
							// sort offers
							marketOffersArr[v].sort(function(a,b){
								return((a[1]==b[1])?(a[2]-b[2]):(a[1]-b[1]));
							});
							marketOffersArr[v]=marketOffersArr[v].slice(0,18);
							menge_sum=0;
							for(var w=0;w<marketOffersArr[v].length;w++){
								menge_sum += marketOffersArr[v][w][0];
							}
							gutBeob[v]=calcObservedPrice((prodTyp[0][v]=="z"?2:1),marketOffersArr[v]);
							if (valNimmBeob){
								if(!isNaN(NPC[0][v])){
									gut[v]=Math.min(gutBeob[v],NPC[0][v]);
								}else{
									gut[v]=gutBeob[v];
								}
							}
							if(!(preisBeob instanceof Array)){ preisBeob=new Array(); }
							preisBeob[v]=[true,now,marketOffersArr[v][0][1],marketOffersArr[v][marketOffersArr[v].length-1][1],menge_sum];
						}else{
							// no offers
							if (valNimmBeob){
								if(!isNaN(NPC[0][v])){
									gut[v]=NPC[0][v];
								}else{
									gut[v]=0;
								}
							}
							if(!(preisBeob instanceof Array)){ preisBeob=new Array(); }
							if(!(preisBeob[v]&&preisBeob[v][0])){
								preisBeob[v]=[false,now,,,0];
							}				
						}
					}
				}
				_ownMarketOffers=null;marketOffersArr=null;
				row=null;prod=null;preis=null;menge=null;menge_sum=null;
				if (valNimmBeob){
					GM_setValueCache(LNG+"_"+SERVER+"_gut",implode(gut));
					raiseEventTop("gameChangedGut");
				}
				GM_setValueCache(LNG+"_"+SERVER+"_gutBeob",implode(gutBeob));
				GM_setValueCache(LNG+"_"+SERVER+"_preisBeob",implode(preisBeob));
				raiseEventTop("gameChangedBeobPrice");
			}
		}catch(err){ GM_log("ERROR marketActionResponse ("+err_trace+")\nv="+v+"\n"+err); }
		unsafeWindow._marketActionResponse(request,action,id,open);
	}
	quicklinks();
	// Buy offer by pressing Enter
	if(newdiv=$("marketbuyofferamount")){
		newdiv.addEventListener("keyup",function(event){
			if(event.keyCode==13){
				unsafeWindow.calcMarketOfferCost();
				var newdiv=$("marketbuyofferbutton");
				if(newdiv.style.display=="block"){
					click(newdiv);
				}
				newdiv=null;
			}
		},false);
	}
	// Create offer enter stock amount
	if(newdiv=$("marketcreateoffer_stockamount")){
		newdiv.setAttribute("class","link");
		newdiv.addEventListener("click",function(event){
			var newdiv=$("marketnewoffer_amount");
			if(newdiv){
				newdiv.value=prodStock[0][unsafeWindow.market_filter_pid];
				keyup(newdiv);
			}
			newdiv=null;
		},false);
	}	
	
	// Notepad for Non-Premium
	err_trace="Notepad for Non-Premium";
	if((newdiv=$("sub_notepad"))&&(newdiv.style.display=="none")){
		newdiv=insertAfter(createElement("div",{"id":"beraterNotepad","class":"submenueitem link","style":"display:block;"}),newdiv);
		createElement("img",{"src":GFX+"guild/contract.gif","style":"width:15px;height:15px;"},newdiv);
		newdiv.addEventListener("mouseover",function(event){ showToolTip(event,unsafeWindow.lng_t_notizen); },false);
		newdiv.addEventListener("click",function(){
			$("notepadentry").value=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_notepad","");
			unsafeWindow.calcNotepadLetters();
			unsafeWindow.showDiv("notepad");
		},false);
		newdiv=$("notepadheader");
		newdiv.getElementsByTagName("img")[0].removeAttribute("onclick");
		newdiv.getElementsByTagName("img")[0].addEventListener("click",function(){
			GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_notepad",$("notepadentry").value,72);
			unsafeWindow.hideDiv("notepad");
		},false);
	}

	// BuyNotepad
	err_trace="BuyNotepad";
	var modeBuyNotepad=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeBuyNotepad",0);
	function doBuyNotepad(){
	try{
		var err_trace="init";
		if(!show["buyNotepad"]){ return false; } // no calculation if table is hidden
		var newdiv=$("buyNotepad");
		if(newdiv){
		/* rack type 0 (farm) */
			err_trace="type 0";
			var prodMissing=new Object();
			var drawProductLines=false;
			// calculate missing products
			err_trace="type 0, missing products";
			for(var v=0;v<prodNameSort[0].length;v++){
				var prod=prodNameSort[0][v];
				if((!prodBlock[0][prod].match(/t/))&&(!prodBlock[0][prod].match(/l/))){
					var amount=prodMinRack[0][prod]-prodStock[0][prod];
					if (amount>0){
						prodMissing[prod]=[amount,amount*(gut[prod]?gut[prod]:0)];
					}
				}
			}
			// sorting
			err_trace="type 0, sorting";
			switch(modeBuyNotepad){
			case 0:	drawProductLines=true; break;
			case 1:	drawProductLines=true;
			prodMissing.sortObj(function(a,b){
				if(prodTyp[0][a[0]]==prodTyp[0][b[0]]){
					return(b[1][0]-a[1][0]);
				}else{
					return({"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[0][a[0]]]-{"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[0][b[0]]]);
				}
			}); break;
			case 2:	drawProductLines=true;
			prodMissing.sortObj(function(a,b){
				if(prodTyp[0][a[0]]==prodTyp[0][b[0]]){
					return(a[1][0]-b[1][0]);
				}else{
					return({"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[0][a[0]]]-{"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[0][b[0]]]);
				}
			}); break;
			case 3:	prodMissing.sortObj(function(a,b){return (a[1][0]-b[1][0]);}); break;
			case 4:	prodMissing.sortObj(function(a,b){return (a[1][0]-b[1][0]);},true); break;
			case 5:	prodMissing.sortObj(function(a,b){return (a[1][1]-b[1][1]);}); break;
			case 6:	prodMissing.sortObj(function(a,b){return (a[1][1]-b[1][1]);},true); break;
			case 7:	prodMissing.sortObj(function(a,b){return (a[0]-b[0]);},true); break;
			}

			// creating table
			err_trace="type 0, table";
			newdiv.innerHTML="";
			var newtable=createElement("table",{"border":"0","cellspacing":"0","cellpadding":"0"},newdiv);
			var newtr=createElement("tr",{"class":"link"},newtable);
			newtr.addEventListener("click",function(){
				modeBuyNotepad=(modeBuyNotepad+1)%7;
				GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_modeBuyNotepad",modeBuyNotepad);
				doBuyNotepad();
			},false);
			newtr.addEventListener("mouseover",function(event){showToolTip(event,"Sortingmode: "+["Producttype, id","Producttype, amount","Producttype, amount descending","amount","amount descending","value","value descending","id"][modeBuyNotepad]+"<br>Click to change");},false);
			var newtd=createElement("td",{"colspan":"4","style":"border-bottom:1px solid black;text-align:center;"},newtr,texte["fehlt"]);

			var oldType=null;
			var newType=null;
			var help=0; //TODO review
			for(var prod in prodMissing){
				if(!prodMissing.hasOwnProperty(prod)){ continue; }
				var amountForFarmis=valMinRackFarmis?((totalFarmis[0]&&totalFarmis[0][prod]?totalFarmis[0][prod]:0)-(prodStock[0]&&prodStock[0][prod]?prodStock[0][prod]:0)):0;
				var str='<table class="white">';
				str += '<tr><th colspan="3" style="border-bottom:1px solid white;">'+texte["goToMarketOfX"].replace(/%1%/,prodName[0][prod])+'</th></tr>';
				str += '<tr><td>'+texte["minRack"]+'</td><td></td><td style="text-align:right;">'+numberFormat(prodMinRackInit[0][prod])+'</td></tr>';
				if(totalQuest["farm"]&&totalQuest["farm"][0][prod]){ 
					str += '<tr><td>'+texte["quest"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalQuest["farm"][0][prod])+'</td></tr>'; 
				}
				if(totalQuest["lodge"]&&totalQuest["lodge"][0][prod]){
					str += '<tr><td>'+texte["lodgequest"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalQuest["lodge"][0][prod])+'</td></tr>';
				}
				if(valMinRackRecursive&&totalRecursive[0]&&totalRecursive[0][prod]){ 
					str += '<tr><td>'+texte["recursive"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalRecursive[0][prod])+'</td></tr>'; 
				}
				if(valMinRackFarmis&&totalFarmis[0]&&totalFarmis[0][prod]){ str += '<tr><td>'+unsafeWindow.customerarecalled.replace(/%FARMI%/,"")+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalFarmis[0][prod])+'</td></tr>'; }
				str += '<tr><td>'+texte["bestand"]+'</td><td>-</td><td style="text-align:right;">'+numberFormat(prodStock[0][prod])+'</td></tr>';
				if(valMinRackGrowing){
					if(totalErnte[0][prod]){
						amountForFarmis -= totalErnte[0][prod];
						str += '<tr><td>'+texte["produktion"]+'</td><td>-</td><td style="text-align:right;">'+numberFormat(totalErnte[0][prod])+'</td></tr>';
					}
					if(totalPowerups[prod]){
						amountForFarmis -= totalPowerups[prod];
						str += '<tr><td>'+texte["powerups"]+'</td><td>-</td><td style="text-align:right;">'+numberFormat(totalPowerups[prod])+'</td></tr>';
					}
				}
				if(prodMinRackAddon[0][prod]){
					for(var k in prodMinRackAddon[0][prod]){
						if(!prodMinRackAddon[0][prod].hasOwnProperty(k)){ continue; }
						str += '<tr><td>'+k+'</td><td>'+(prodMinRackAddon[0][prod][k]>0?'+':'-')+'</td><td style="text-align:right;">'+numberFormat(prodMinRackAddon[0][prod][k])+'</td></tr>';
					}
				}
				str += '<tr><td colspan="3" style="border-bottom:1px solid white;"></td></tr>';
				str += '<tr><td>'+texte["marktpreis"]+'</td><td></td><td style="text-align:right;">'+moneyFormat(gut[prod])+'</td></tr>';
				str += '<tr><td>'+texte["wert"]+'</td><td></td><td style="text-align:right;">'+moneyFormatInt(prodMissing[prod][1])+'</td></tr>';
				str += '</table>';
				newType=prodTyp[0][prod];
				newtr=createElement("tr",{"class":"link hoverBgCc9"+((drawProductLines&&(oldType!=null)&&(oldType!=newType))?" borderTop1dashedBlack":""),"prod":prod,"mouseOverText":str},newtable);
				oldType=newType;
				newtr.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
				newtr.addEventListener("mouseover",function(event){showToolTip(event,this.getAttribute("mouseOverText"));},false);
				newtd=createElement("td",{},newtr);
				produktPic(0,prod,newtd);
				createElement("td",{"style":"text-align:right;"},newtr,numberFormat(prodMissing[prod][0]));
				if(amountForFarmis>0){
					createElement("td",{"style":"padding-left:3px;text-align:right;"},newtr,"("+numberFormat(amountForFarmis)+")");
				}else{
					createElement("td",{},newtr);
				}
				createElement("td",{"style":"padding-left:3px;"},newtr,prodName[0][prod]);
			}
			help=null;
			
			if(newtable.childElementCount==1){
				newtr=createElement("tr",{},newtable);
				createElement("td",{"colspan":"3","style":"text-align:center;"},newtr,"---");
			}

		/* rack type 1 (forestry) */
			err_trace="type 1";
			var newtr=createElement("tr",{},newtable);
			var newtd=createElement("td",{"colspan":"4","style":"border-bottom:1px solid black;text-align:center;width:100%;"},newtr);

			drawProductLines=false;
			prodMissing=new Object();
			// calculate missing products
			err_trace="type 1, missing products";
			for(var prod in prodMinRack[1]){
				if(!prodMinRack[1].hasOwnProperty(prod)){ continue; }
				var amount=prodMinRack[1][prod]-(prodStock[1][prod]?prodStock[1][prod]:0);
				if (amount>0){
					prodMissing[prod]=[amount,0]; //'0'==price
				}
			}
			// sorting
			err_trace="type 1, sorting";
			switch(modeBuyNotepad){
			case 0:	drawProductLines=true;
			prodMissing.sortObj(function(a,b){
				if(prodTyp[1][a[0]]==prodTyp[1][b[0]]){
					return(a[0]-b[0]);
				}else{
					return({"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[1][a[0]]]-{"c":0,"v":1,"e":2,"o":3,"fw1":4,"fw2":5,"fw3":6,"fw4":7,"z":8}[prodTyp[1][b[0]]]);
				}
			}); break;
			case 1:	drawProductLines=true;
			prodMissing.sortObj(function(a,b){
				if(prodTyp[1][a[0]]==prodTyp[1][b[0]]){
					return(b[1][0]-a[1][0]);
				}else{
					return({"f1":0,"f2":1,"f3":2,"f4":3,"f5":4}[prodTyp[1][a[0]]]-{"f1":0,"f2":1,"f3":2,"f4":3,"f5":4}[prodTyp[1][b[0]]]);
				}
			}); break;
			case 2:	drawProductLines=true;
			prodMissing.sortObj(function(a,b){
				if(prodTyp[1][a[0]]==prodTyp[1][b[0]]){
					return(a[1][0]-b[1][0]);
				}else{
					return({"f1":0,"f2":1,"f3":2,"f4":3,"f5":4}[prodTyp[1][a[0]]]-{"f1":0,"f2":1,"f3":2,"f4":3,"f5":4}[prodTyp[1][b[0]]]);
				}
			}); break;
			case 3:	prodMissing.sortObj(function(a,b){return (a[1][0]-b[1][0]);}); break;
			case 4:	prodMissing.sortObj(function(a,b){return (a[1][0]-b[1][0]);},true); break;
			case 5:	prodMissing.sortObj(function(a,b){return (a[1][1]-b[1][1]);}); break;
			case 6:	prodMissing.sortObj(function(a,b){return (a[1][1]-b[1][1]);},true); break;
			case 7:	prodMissing.sortObj(function(a,b){return (a[0]-b[0]);},true); break;
			}
			//prodMissing.sortObj();
			err_trace="type 1, table";
			oldType=null;
			newType=null;
			for(var prod in prodMissing){
				if(!prodMissing.hasOwnProperty(prod)){ continue; }
				var amountForForestryFarmis=valMinRackForestryFarmis?((totalFarmis[1]&&totalFarmis[1][prod]?totalFarmis[1][prod]:0)-(prodStock[1]&&prodStock[1][prod]?prodStock[1][prod]:0)):0;

				var str='<table class="white">';
				str += '<tr><th colspan="3" style="border-bottom:1px solid white;">'+prodName[1][prod]+'</th></tr>';
				str += '<tr><td>'+texte["minRack"]+'</td><td></td><td style="text-align:right;">'+numberFormat(prodMinRackInit[1][prod])+'</td></tr>';
				if(totalQuest["farm"]&&totalQuest["farm"][1][prod]){ 
					str += '<tr><td>'+texte["quest"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalQuest["farm"][1][prod])+'</td></tr>'; 
				}
				if(totalQuest["lodge"]&&totalQuest["lodge"][1][prod]){
					str += '<tr><td>'+texte["lodgequest"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalQuest["lodge"][1][prod])+'</td></tr>';
				}
				if(valMinRackRecursive&&totalRecursive[1]&&totalRecursive[1][prod]){ str += '<tr><td>'+texte["recursive"]+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalRecursive[1][prod])+'</td></tr>'; }
				if(valMinRackForestryFarmis&&totalFarmis[1]&&totalFarmis[1][prod]){ str += '<tr><td>'+unsafeWindow.customerarecalled.replace(/%FARMI%/,"")+'</td><td>+</td><td style="text-align:right;">'+numberFormat(totalFarmis[1][prod])+'</td></tr>'; }
				str += '<tr><td>'+texte["bestand"]+'</td><td>-</td><td style="text-align:right;">'+numberFormat(prodStock[1][prod])+'</td></tr>';

				if(valMinRackGrowing){
					if(totalErnte[1][prod]){
						amountForForestryFarmis -= totalErnte[1][prod];
						str += '<tr><td>'+texte["produktion"]+'</td><td>-</td><td style="text-align:right;">'+numberFormat(totalErnte[1][prod])+'</td></tr>';
					}
				}
				if(prodMinRackAddon[1][prod]){
					for(var k in prodMinRackAddon[1][prod]){
						if(!prodMinRackAddon[1][prod].hasOwnProperty(k)){ continue; }
						str += '<tr><td>'+k+'</td><td>'+(prodMinRackAddon[1][prod][k]>0?'+':'-')+'</td><td style="text-align:right;">'+numberFormat(prodMinRackAddon[1][prod][k])+'</td></tr>';
					}
				}
				if(prodRequire[1][prod]){
					str += '<tr><th colspan="3" style="border-bottom:1px solid white;">Required per production</th></tr>'; //TODO texte
					for(i in prodRequire[1][prod]){
						if(!prodRequire[1][prod].hasOwnProperty(i)){continue;}
						str += '<tr><td>';
						str += prodName[prodRequire[1][prod][i][0]][prodRequire[1][prod][i][1]];
						str += '</td><td></td><td style="text-align:right;">'+numberFormat(prodRequire[1][prod][i][2])+'</td></tr>';
					}
					// str += '<tr><td>Data not fetched</td><td>+</td><td style="text-align:right;">?</td></tr>'; //TODO texte
				}
				if(prodYield[1][prod]){
					str += '<tr><th colspan="3" style="border-bottom:1px solid white;">Yield per production</th></tr>'; //TODO texte
					str += '<tr><td>'+prodName[1][prod]+'</td><td></td><td style="text-align:right;">'+numberFormat(prodYield[1][prod])+'</td></tr>';
					// str += '<tr><td>Data not fetched</td><td>+</td><td style="text-align:right;">?</td></tr>'; //TODO texte
				}
				str += '</table>';

				newType=prodTyp[1][prod];
				newtr=createElement("tr",{"class":"hoverBgCc9"+((drawProductLines&&(oldType!=null)&&(oldType!=newType))?" borderTop1dashedBlack":""),"iProd":prod,"mouseOverText":str,"style":(prodBlock[1][prod].match(/b/)?"color:red;":"")},newtable);//TODO color
				oldType=newType;
				newtr.addEventListener("mouseover",function(event){showToolTip(event,this.getAttribute("mouseOverText"));},false);
				newtd=createElement("td",{},newtr);
				produktPic(1,prod,newtd);
				createElement("td",{"style":"text-align:right;"+(prodBlock[1][prod].match(/[lq]/)&&prodBlock[1][prod].match(/t/)?"color:red;":"")},newtr,numberFormat(prodMissing[prod][0]));
				if(amountForForestryFarmis>0){
					createElement("td",{"style":"padding-left:3px;text-align:right;"+(prodBlock[1][prod].match(/[lq]/)&&prodBlock[1][prod].match(/t/)?"color:red;":"")},newtr,"("+numberFormat(amountForForestryFarmis)+")");
				}else{
					createElement("td",{},newtr);
				}
				createElement("td",{"style":"padding-left:3px;"+(prodBlock[1][prod].match(/[lq]/)&&prodBlock[1][prod].match(/t/)?"color:red;":"")},newtr,prodName[1][prod]);
				//str += '<tr><td colspan="5">Quest not reached</td></tr>'; //TODO texte
			}

			if(newtable.childElementCount==2){
				newtr=createElement("tr",{},newtable);
				createElement("td",{"colspan":"4","style":"text-align:center;"},newtr,"---");
			}
			newtable=null;newtr=null;newtd=null;
		}
		newdiv=null;
	}catch(err){ GM_log("ERROR doBuyNotepad ("+err_trace+")\nprod="+prod+" \n"+err); }		
	}
	newdiv=ALL.getElementsByClassName("rahmen_hoch")[2];
	newdiv.firstElementChild.style.marginBottom="-90px";
	newdiv=createElement("div",{"style":"position:relative;display:block;white-space:nowrap;"},newdiv);
	newdiv1=createElement("div",{"id":"buyNotepadOpener","class":"link","style":"display:inline-block;vertical-align:top;height:25px;width:20px;background:no-repeat scroll center top #000000;"},newdiv);
	createElement("div",{"id":"buyNotepad","style":"display:"+(show["buyNotepad"]?"inline-block":"none")+";vertical-align:top;border:2px inset black;background-color:white;padding:3px;max-height:200px;overlfow:;overflow:hidden;overflow-y:scroll;"},newdiv);
	newdiv1.style.backgroundImage="url('"+GFX+"arrow_"+(show["buyNotepad"]?"left":"right")+".png')";
	newdiv1.addEventListener("click",function(){
		show["buyNotepad"]=!show["buyNotepad"];
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_show",implode(show));
		if(show["buyNotepad"]){
			this.style.backgroundImage="url('"+GFX+"arrow_left.png')";
			$("buyNotepad").style.display="inline-block";
			doBuyNotepad();
		}else{
			this.style.backgroundImage="url('"+GFX+"arrow_right.png')";
			$("buyNotepad").style.display="none";
		}
	},false);

	// MarketoffersNotepad
	err_trace="MarketoffersNotepad";
	function doMarketoffersNotepad(){
		if(!show["marketoffersNotepad"]){ return false; } // no calculation if table is hidden
		var newdiv=$("marketoffersNotepad");
		if(newdiv){
			newdiv.innerHTML="";
			var newtable=createElement("table",{"border":"0","cellspacing":"0","cellpadding":"0"},newdiv);
			var newtr=createElement("tr",{"class":"link"},newtable);
			var newtd=createElement("td",{"colspan":"5","style":"border-bottom:1px solid black;text-align:center;"},newtr,texte["marktstand"]);
			newtr.addEventListener("mouseover",function(event){
				var str='<table class="white">';
				str += '<tr><th colspan="2" style="border-bottom:1px solid white">'+texte["zumMarktstand"]+'</th></tr>';
				str += '<tr><td>'+sign_sum+'</td><td style="text-align:right;">'+moneyFormatInt(parseInt(this.getAttribute("value"),10))+'</td></tr>';
				str += '</table>';
				showToolTip(event,str);
			},false);
			newtr.addEventListener("click",function(){showMarketStall();},false);

			var sumTotal=0;
			var oldType=null;
			var newType=null;
			for(var prod in ownMarketOffers){
				if(!ownMarketOffers.hasOwnProperty(prod)){ continue; }
				newType=prodTyp[0][prod];
				for(var elem in ownMarketOffers[prod]){
					if(!ownMarketOffers[prod].hasOwnProperty(elem)){ continue; }
					var price=parseFloat(elem,10);
					sumTotal += ownMarketOffers[prod][price]*price;
					newtr=createElement("tr",{"class":"link hoverBgCc9"+(((oldType!=null)&&(oldType!=newType))?" borderTop1dashedBlack":""),"prod":prod,"value":(ownMarketOffers[prod][price]*price)},newtable);
					oldType=newType;
					newtr.addEventListener("mouseover",function(event){
						showGoToMarketToolTip(event,this.getAttribute("prod"),null,'<tr><td>'+sign_sum+'</td><td style="text-align:right;">'+moneyFormatInt(parseInt(this.getAttribute("value"),10))+'</td></tr>');
					},false);
					newtr.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
					newtd=createElement("td",{},newtr);
					produktPic(0,prod,newtd);
					createElement("td",{"style":"text-align:right;"},newtr,numberFormat(ownMarketOffers[prod][price]));
					createElement("td",{"style":"padding-left:3px;"},newtr,prodName[0][prod]);
					createElement("td",{"style":"padding-left:3px;text-align:right;"},newtr,numberFormat(Math.floor(price)));
					createElement("td",{"style":""},newtr,numberFormat(price,2).slice(-3).replace("00","--"));
				}
			}

			newtable.firstElementChild.setAttribute("value",sumTotal);
			if(newtable.childElementCount==1){
				newtr=createElement("tr",{},newtable);
				createElement("td",{"colspan":"5","style":"text-align:center;"},newtr,"---");
			}
			newtable=null;newtr=null;newtd=null;
		}
		newdiv=null;
	}
	newdiv=createElement("div",{"style":"position:relative;margin-top:5px;display:block;white-space:nowrap;"},ALL.getElementsByClassName("rahmen_hoch")[2]);
	newdiv=createElement("div",{"id":"marketoffersNotepadOpener","class":"link","style":"display:inline-block;vertical-align:top;height:25px;width:20px;background:no-repeat scroll center top #000000;"},newdiv);
	createElement("div",{"id":"marketoffersNotepad","style":"display:"+(show["marketoffersNotepad"]?"inline-block":"none")+";vertical-align:top;border:2px inset black;background-color:white;padding:3px;"},$("marketoffersNotepadOpener").parentNode);
	newdiv.style.backgroundImage="url('"+GFX+"arrow_"+(show["marketoffersNotepad"]?"left":"right")+".png')";
	newdiv.addEventListener("click",function(){
		show["marketoffersNotepad"]=!show["marketoffersNotepad"];
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_show",implode(show));
		if(show["marketoffersNotepad"]){
			this.style.backgroundImage="url('"+GFX+"arrow_left.png')";
			$("marketoffersNotepad").style.display="inline-block";
		}else{
			this.style.backgroundImage="url('"+GFX+"arrow_right.png')";
			$("marketoffersNotepad").style.display="none";
		}
		doMarketoffersNotepad();
	},false);
	doMarketoffersNotepad();

	document.addEventListener("gameChangedOwnMarketOffers",function(){
		window.setTimeout(function(){
			ownMarketOffers=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_ownMarketOffers"),"event:gameChangedOwnMarketOffers/ownMarketOffers",{});
			doMarketoffersNotepad();
		},0);
	},false);
	// Points and level.  levelLog[day]=[points,rank,market sales,contract sales,farmi money]
	err_trace="Points and level";
	var levelLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog","{}"),"do_main/levelLog",{});

	const LEVEL_POINTS=[0,0,58,2420,6620,15620,27900,58700,101700,163100,211900,276900,359000,467000,730000,1190000,1750000,2680000,3900000,5660000,7850000,10590000,15300000,20640000,26020000,37340000,50030000,65160000,85030000,108900000,139150000,175520000,222430000,276920000,345930000,429330000,535520000,669000000,797010000,927020000,1205126000,1566663800,2036662940,2647661820,3441960360,4500000000,5851140640,9950270440,16920320540,29000000000,99000000000]; // task_new_level
	if(levelLog[todayServerStr]==undefined){ levelLog[todayServerStr]=[0,null,0,0,0]; }
	levelLog[todayServerStr][0]=parseInt($("pkt").innerHTML.replace(/\D/g,""),10);
	function getDailyRanking(){
		GM_xmlhttpRequest({
			method: "GET",
			url: "http://s"+SERVER+"."+GAMEPAGES[LNG]+"/stadt/stats.php?type=1&self=1",
			headers: {"Content-type": "application/x-www-form-urlencoded"},
			onload: function(response){
				if(levelLog[todayServerStr]==undefined){ levelLog[todayServerStr]=[0,null,0,0,0]; }
				var help=(new RegExp(";psbn&"+FARMNAME.reverse()+">.*?<\\.(\\d+)>")).exec(response.responseText.replace(/\s+/g,"").reverse());
				if(help){
					levelLog[todayServerStr][1]=parseInt(help[1].reverse(),10);
				}else{
					help=(new RegExp(">.*?<\\.(\\d+)>")).exec(response.responseText.replace(/\s+/g,"").reverse());
					if(help){
						levelLog[todayServerStr][1]=parseInt(help[1].reverse(),10);
					}
				}
				GM_setValue2(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog),73);
			}
		});
	}
	if(!levelLog[todayServerStr][1]){ getDailyRanking(); }
	function plotLevelProgressBar(){
		//todayStr=getDateStr(now,2,false);
		if(levelLog[todayServerStr]==undefined){ levelLog[todayServerStr]=[0,null,0,0,0]; }
		levelLog[todayServerStr][0]=parseInt($("pkt").innerHTML.replace(/\D/g,""),10);
		var levelsum=LEVEL_POINTS[USERLEVEL+1]-LEVEL_POINTS[USERLEVEL-1];
		var levelSize=959;
		var newdiv=$("levelProgressBar");
		if(newdiv){ removeElement(newdiv); }
		if(USERLEVEL<LEVEL_POINTS.length){
			newdiv=createElement("div",{"class":"link","id":"levelProgressBar","style":"float:left;width:"+levelSize+"px;position:relative;top:-2px;left:18px;"},content_table.firstElementChild.children[2].firstElementChild);
			newdiv.addEventListener("click",function(){buildInfoPanel("level");},false);
			newdiv.addEventListener("mouseover",function(event){
				var node=event.target;
				var mouseOverText=node.getAttribute("mouseOverText");
				while((node!=this)&&(!mouseOverText)){
					node=node.parentNode;
					mouseOverText=node.getAttribute("mouseOverText");
				}
				if(mouseOverText){ showToolTip(event,mouseOverText); }
				node=null;mouseOverText=null;
			},false);

			var newdiv1=bar(levelSize*(LEVEL_POINTS[USERLEVEL]-LEVEL_POINTS[USERLEVEL-1])/levelsum,1,1);
			newdiv1.style.cssFloat="left";
			newdiv1.setAttribute("mouseOverText",texte["level"]+" "+(USERLEVEL-1)+": "+numberFormat(LEVEL_POINTS[USERLEVEL-1],0)+"-"+numberFormat(LEVEL_POINTS[USERLEVEL],0));
			newdiv.appendChild(newdiv1);

			newdiv1=bar(levelSize*(LEVEL_POINTS[USERLEVEL+1]-LEVEL_POINTS[USERLEVEL])/levelsum,levelLog[todayServerStr][0]-LEVEL_POINTS[USERLEVEL],LEVEL_POINTS[USERLEVEL+1]-LEVEL_POINTS[USERLEVEL]);
			newdiv1.style.cssFloat="left";
			newdiv1.style.marginLeft=Math.ceil(2+levelSize*(LEVEL_POINTS[USERLEVEL]-LEVEL_POINTS[USERLEVEL-1])/levelsum)+"px";
			newdiv1.setAttribute("mouseOverText",texte["level"]+" "+(USERLEVEL)+": "+numberFormat(LEVEL_POINTS[USERLEVEL],0)+"-"+numberFormat(LEVEL_POINTS[USERLEVEL+1],0));
			newdiv.appendChild(newdiv1);

			for(var v in levelLog){
				if(!levelLog.hasOwnProperty(v)){ continue; }
				if((LEVEL_POINTS[USERLEVEL-1]<levelLog[v][0])&&(levelLog[v][0]<LEVEL_POINTS[USERLEVEL+1])){
					// save full data for the last 2 levels
					newdiv1=createElement("div",{"mouseOverText":v+"<br>"+numberFormat(levelLog[v][0]),"style":"position:absolute;width:0;margin-top:2px;height:12px;border-right:1px solid white;"},newdiv);
					if (levelLog[v][0]<LEVEL_POINTS[USERLEVEL]) newdiv1.style.marginLeft=Math.floor(2+levelSize*(levelLog[v][0]-LEVEL_POINTS[USERLEVEL-1])/levelsum)+"px";
					else newdiv1.style.marginLeft=Math.floor(4+levelSize*(levelLog[v][0]-LEVEL_POINTS[USERLEVEL-1])/levelsum)+"px";
					help=v.split(".");
					if (new Date(parseInt(help[2],10),parseInt(help[1],10)-1,parseInt(help[0],10)).getDay()=="0") newdiv1.style.borderColor="red";
				}else{
					// join data to monthly
					if(v.match(/^\d+\.\d+\.\d+$/)){
						var w=v.replace(/^(\d+\.)/,"");
						if(levelLog[w]==undefined){
							levelLog[w]=[0,,0,0,0];
							levelLog.sortObj(sortObjFunctions["date"]);
						}
						if(levelLog[w][0]<levelLog[v][0]){
							levelLog[w][0]=levelLog[v][0];
							levelLog[w][1]=levelLog[v][1];
						}
						levelLog[w][2] += levelLog[v][2];
						levelLog[w][3] += levelLog[v][3];
						levelLog[w][4] += levelLog[v][4];
						delete levelLog[v];
					}
				}
			}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog));
			newdiv1=null;
		}
		newdiv=null;
	}
	plotLevelProgressBar();
	unsafeWindow._updateMenuHandler=unsafeWindow.updateMenuHandler;
	unsafeWindow.updateMenuHandler = function(){
		unsafeWindow._updateMenuHandler();
		var result=checkRequest(unsafeWindow.oAjax);
		if(result&&result[0]!=0){
			if (result.carpentry_bonus){
				unsafeData.carpentry_bonus=result.carpentry_bonus;
			}
			window.setTimeout(function(){
				// calcTotalFarmis();
				// loadProductData();
				updateProductDataFarm();
				plotLevelProgressBar();
				calcProdMinRack();
				// calcProdMinRackInit();
				if(USERLEVEL<parseInt(unsafeWindow.currentuserlevel,10)){
					raiseEvent("gameUserlevelUp");
				}
			},0);
		}
	};
	unsafeWindow.updateMenu(); // -> updateMenuHandler

	// Removing Advertising end on Advertising Abort
	unsafeWindow._cancelAdResponse=unsafeWindow.cancelAdResponse;
	unsafeWindow.cancelAdResponse = function(request){
		var result=checkRequest(request);
		if(result&&result[0]!=0){
			var cell=$("alertAdvertEnd");
			if(cell){ removeElement(cell); }
			cell=null;
		}
		unsafeWindow._cancelAdResponse(request);
	};

	// Sprechblase
	err_trace="Bubble";
	//createElement("div",{"id":"sprcontent2","style":"position:absolute;top:35px;left:323px;z-index:100;width:200px;height:80px;overflow:auto;display:none;"},$("sprcontent").parentNode);//same style as #sprcontent
	createElement("div",{"id":"sprcontent2","style":"position:absolute;top:20px;left:323px;z-index:100;width:200px;height:90px;overflow:auto;display:none;"},$("sprcontent").parentNode);//same style as #sprcontent
	function hideBlase(){
		$("sprcontent").style.display="";
		$("sprcontent2").innerHTML="";
		$("sprcontent2").style.display="none";
	}
	function showBlase(zoneNrF){
	try{
		$("sprcontent").style.display="none";
		var bubble=$("sprcontent2");
		bubble.style.display="";
		bubble.innerHTML="";
		if (zoneBlock[zoneNrF].match(/p/)){
			createElement("div",{"class":"tnormal"},bubble,unsafeWindow.inforequirepremium);
		}else if (zoneBlock[zoneNrF].match(/q/)){
			createElement("div",{"class":"tnormal"},bubble,unsafeWindow.questblock);
		}else if(BUILDINGTYPE[zoneTyp[zoneNrF]]==0){
			createElement("div",{"class":"tnormal","style":"font-weight:bold;"},bubble,unsafeWindow.buildinginfos[0][zoneTyp[zoneNrF]][10]);
		}else{
			var time = (zoneEndTimes[zoneNrF]&&(zoneEndTimes[zoneNrF]!=NEVER))?(zoneEndTimes[zoneNrF]+unsafeWindow.Zeit.Verschiebung):NEVER;
			//GM_log("showBlase zoneNr:"+zoner+" prod:"+prod+" time:"+time);
			if(time==NEVER){
				createElement("font",{"class":"tmenu","style":"font-weight:bold;"},bubble,texte[zoneNrF]+" "+texte["unbeschaeftigt"]);
				// createElement("font",{"class":"tnormal","style":"font-weight:bold;"},bubble,texte["feldLeer"]);
			}else{
				var prod = zoneEndProducts[zoneNrF]?zoneEndProducts[zoneNrF]:null;
				if(prod!=null){
					switch(getLocation(zoneNrF)){
					case "windmill":
						createElement("div",{"class":"fm"+prod,"style":"position:absolute;top:5px;left:0;"},bubble);
						newdiv=createElement("div",{"style":"position:absolute;top:5px;left:55px;"},bubble);
						createElement("font",{"class":"tmenu","style":"font-weight:bold;"},createElement("div",{},newdiv),prodName[3][prod]); // unsafeWindow.formulas[0][prod][2]
					break;
					case "forestry":
						createElement("div",{"class":"f_symbol"+prod,"style":"position:absolute;top:5px;left:0;"},bubble);
						newdiv=createElement("div",{"style":"position:absolute;top:5px;left:55px;"},bubble);
						createElement("font",{"class":"tmenu","style":"font-weight:bold;"},createElement("div",{},newdiv),prodName[1][prod]);
					break;
					default:
						createElement("div",{"class":"tt"+prod,"style":"position:absolute;top:5px;left:0;"},bubble);
						newdiv=createElement("div",{"style":"position:absolute;top:5px;left:55px;"},bubble);
						createElement("font",{"class":"tmenu","style":"font-weight:bold;"},createElement("div",{},newdiv),prodName[0][prod]);
					}
				}

				var newfont=createElement("font",{"class":"tmenu"},createElement("div",{},newdiv));
				if (time<now){
					if(time+20*60*60<now){
						newfont.innerHTML=texte["fertigSeitX"].replace(/%1%/,getFormattedDateStr(time));
					}else{
						newfont.innerHTML=texte["fertigSeitX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]);
					}
				}else if (time<NEVER){
					var endDay=countDays(now,time);
					if (endDay==0){
						newfont.innerHTML=texte["readyAtX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]);
					}else if ((endDay==1)&&(texte["readyAtX_day1"])){
						newfont.innerHTML=texte["readyAtX_day1"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]);
					}else if ((endDay==2)&&(texte["readyAtX_day2"])){
						newfont.innerHTML=texte["readyAtX_day2"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]);
					}else{
						newfont.innerHTML=new Date(1000*time).toLocaleString();
					}
				}
				newfont=null;
			}
		}
		bubble=null;newdiv=null;
	}catch(err){ GM_log("ERROR showBlase zoneNrF="+zoneNrF+"\n"+err); }
	}

	// Lager / Rack
	err_trace="Rack";
	newdiv=createElement("div",{"style":"display:none;"},$("lager_info"));//position:absolute;top:50px;left:58px;display:none;
	createElement("img",{"src":GFX+"adtime.gif","style":"float:left;width:14px;height:14px;margin-left:5px;"},newdiv);
	createElement("div",{"id":"lager_zeit_ziel","class":"tnormal","style":"float:left;margin-left:5px;"},newdiv);
	newdiv=createElement("div",{"id":"sendStockingContract","class":"link playerContract","style":"position:absolute;top:155px;left:10px;"},$("lager").firstElementChild);
	createElement("div",{},newdiv);
	newdiv.addEventListener("mouseover",function(event){
		if(prodBlock[0][unsafeWindow.selected].match(/t/)){
			showToolTip(event,"---");
		}else{
			showToolTip(event,texte["XmitVertragAuslagern"].replace(/%1%/,prodName[0][unsafeWindow.selected]));
		}
	},false);
	newdiv.addEventListener("click",function(event){
		try{
			if(!prodBlock[0][unsafeWindow.selected].match(/t/)){
				var thisdata=new Object();
				thisdata["to"]=FARMNAME;
				thisdata["fillContract"]=new Object();
				thisdata["fillContract"][unsafeWindow.selected]=[prodStock[0][unsafeWindow.selected],1];
				GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeNew",implode(thisdata));
				showMultiframePage("vertraege/new.php");
			}
		}catch(err){ GM_log("ERROR listener sendStockingContract.click\n"+err); }
	},false);
	function doLagerZeit(zoneNr){
	try{
		// GM_log("doLagerZeit zoneNr="+zoneNr);
		if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["buildingid"]!="1"){ return false; }
		var divLagerZeitZiel=$("lager_zeit_ziel");
		if ((unsafeWindow.mode==0)&&(prodTyp[0][unsafeWindow.selected]=="v")){
			var bonus=unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["waterbonus"];
			if(unsafeWindow.selected==unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["specialwaterbonus"][0]){ bonus += unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["specialwaterbonus"][1]; }
			bonus=1-(bonus/100);
			// var growtime=calcGrowDuration(unsafeWindow.rackElement[unsafeWindow.selected].duration/1000,bonus);
			var growtime=calcGrowDuration(60*prodGrowTime[0][unsafeWindow.selected],bonus);
			$("lager_zeit").innerHTML=getTimeStr(growtime)+"&nbsp;"+texte["stunden"];
			if (divLagerZeitZiel.parentNode.style.display == "none"){ divLagerZeitZiel.parentNode.style.display=""; }
			divLagerZeitZiel.innerHTML="=&nbsp;"+getDaytimeStr(now+growtime)+"&nbsp;"+texte["uhr"];
		}else{
			if (divLagerZeitZiel.parentNode.style.display!="none"){ divLagerZeitZiel.parentNode.style.display="none"; }
		}
		divLagerZeitZiel=null;
	}catch(err){ GM_log("ERROR doLagerZeit zoneNr="+zoneNr+"\n"+err); }
	}
	unsafeWindow._selectRackItem=unsafeWindow.selectRackItem;
	unsafeWindow.selectRackItem = function(id){
		unsafeWindow._selectRackItem(id);
		try{
			if($("gardenmaincontainer").style.display!="none"){
				var zoneNr=/parent.cache_me\((\d+?),120/.exec($("gardenarea").innerHTML);
				if(zoneNr){
					zoneNr=parseInt(zoneNr[1],10);
					doLagerZeit(zoneNr);
				}
			}
		}catch(err){ GM_log("ERROR selectRackItem id="+id+"\n"+err); }
	};
	function doRack(){
		try{
			var cand=$("rackItems").getElementsByClassName("tklein2");
			for(var v=0;v<cand.length;v++){
				var currProd=parseInt(cand[v].parentNode.id.replace("rackitem",""),10);
				var cell=$(cand[v].parentNode.id+"format");
				if(!cell){
					cell=cand[v].parentNode.parentNode;
					cell.setAttribute("class",(cell.getAttribute("class")+" link").replace(/(^|\s+)link\s+/g," ").replace(/^\s+/,""));
					cand[v].style.display="none";
					cell=createElement("div",{"id":"rackitem"+currProd+"format"},cand[v].parentNode);
				}
				var str=numberFormat(prodStock[0][currProd],0,"","").replace(/(\d{3,})(\d{3})/,"$1k").replace(/(\d+)(\d{3})/g,"$1"+delimThou+"$2");
				if(cell.innerHTML!=str){ cell.innerHTML=str; }
				str=cand[v].getAttribute("class")+(prodStock[0][currProd]<prodMinRack[0][currProd]?" lowrack":""); // .replace("tklein2","formattedRackItem")
				if(cell.getAttribute("class")!=str){ cell.setAttribute("class",str); }
				cell=null;
			}
			cand=null;
		}catch(err){ GM_log("ERROR doRack\nv="+v+"\n"+err); }
	}

	var valMoveAnimals=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMoveAnimals","[]"),"do_main/valMoveAnimals",[]);
	var animalMove=[,,[false,0,0,255,10,10,505],[false,0,0,280,1,0,525],[false,0,0,280,1,25,500],,,,,,,[false,2,20,120,4,0,200]];
	// executed,speedvert,top,bottom,speedhor,left,right
	function moveAnimals(mode){
		//GM_log("moveAnimals "+mode);
		if(($("innermaincontainer").style.display == "block")&&($("animalline"+mode))){
			var cand=$("animalline"+mode).getElementsByTagName("img");
			for(var v=0;v<cand.length;v++){
				cand[v].style.top=(Math.max(animalMove[mode][2],Math.min(animalMove[mode][3],parseInt(cand[v].style.top,10)+animalMove[mode][1]*getRandom(-1,1))))+"px";
				cand[v].style.left=(Math.max(animalMove[mode][5],Math.min(animalMove[mode][6],parseInt(cand[v].style.left,10)+animalMove[mode][4]*getRandom(-1,1))))+"px";
			}
			cand=null;
			window.setTimeout(function(){moveAnimals(mode);},100);
		}else{
			animalMove[mode][0]=false;
		}
	}

	// events general =============================================================================
	err_trace="events general";
	$("errorbox").addEventListener("DOMAttrModified", function(){
		if(valClickErrorbox){ // hide errorbox
			if($("errorbox").style.display=="block"){
				$("errorbox").style.display="none";
				$("transp").style.display="none";
				$("transp3").style.display="none";
			}
		}
	},false);

	// rack
	for(var v in prodName[0]){
		if(!prodName[0].hasOwnProperty(v)){ continue; }
		if(v==0){ continue; } // Coins
		if (!unsafeWindow.rackElement[v]){ prodStock[0][v]=0; } // not available
		// else if ("undefined" === typeof(unsafeWindow.rackElement[v].id)){ prodStock[0][v]=0; } // empty elements
		else if ("undefined" === typeof(unsafeWindow.rackElement[v].number)){ prodStock[0][v]=0; } // no stock available
		else if (!unsafeWindow.rackElement[v].number){ prodStock[0][v]=0; } // no stock available
		else { prodStock[0][v]=parseInt(unsafeWindow.rackElement[v].number,10); }
	}
	GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock));
	unsafeWindow.updateRackBusy=false;
	unsafeWindow._updateRack=unsafeWindow.updateRack;
	unsafeWindow.updateRack = function(rack,init){
		var cell=$("divUpdateRack");
		if(!cell){
			cell=createElement("div",{"id":"divUpdateRack","class":"blackbox","style":"position:absolute;top:20%;left:50%;font-weight:bold;"},$("rackItems"),"Rack updating");
			cell.style.marginLeft=(-(cell.offsetWidth)/2)+"px";
		}
		cell.style.display="block";
		cell=null;
		unsafeWindow.updateRackBusy=true;
		unsafeWindow._updateRack(rack, init);
	};
	unsafeWindow._sortRackNew=unsafeWindow.sortRackNew;
	unsafeWindow.sortRackNew = function(type){
		unsafeWindow._sortRackNew(type);
		try{
			// save rack amounts
			for(var v in prodName[0]){
				if(!prodName[0].hasOwnProperty(v)){ continue; }
				if(v==0){ continue; } // Coins
				if (!unsafeWindow.rackElement[v]){ prodStock[0][v]=0; } // not available
				// else if ("undefined" === typeof(unsafeWindow.rackElement[v].id)){ prodStock[0][v]=0; } // empty elements
				else if ("undefined" === typeof(unsafeWindow.rackElement[v].number)){ prodStock[0][v]=0; } // no stock available
				else if (!unsafeWindow.rackElement[v].number){ prodStock[0][v]=0; } // no stock available
				else { prodStock[0][v]=parseInt(unsafeWindow.rackElement[v].number,10); }
			}		
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock));
			var cell=$("divUpdateRack");
			if(cell){ cell.style.display="none"; }
			cell=null;
			window.setTimeout(function(){
				calcProdMinRack(); // -> doBuyNotepad,doRack
				unsafeWindow.updateRackBusy=false;
				raiseEvent("gameUpdateRack");
			},0);
		}catch(err){ GM_log("ERROR sortRackNew type="+type+"\n"+err); }
	};
	unsafeWindow._sortRack=unsafeWindow.sortRack;
	unsafeWindow.sortRack = function(type){
		unsafeWindow._sortRack(type);
		doRack();
	};
	/*
	function doRackNavi(){
	try{
		if(unsafeWindow.racktype!=2){  // Oil: no navi
			if(unsafeWindow.userracks>1){
				if(unsafeWindow._currRack=="0"){
					// Left arrow to last rack
					var div = unsafe$("racknavileft");
					div.className = "link racknavi";
					div.onmouseover = function(e) { unsafeWindow.showDiv("racknavileftinfo"); }
					div.onmouseout = function(e) { unsafeWindow.hideDiv("racknavileftinfo"); }
					div.onclick = function(e) { unsafeWindow.updateRack(Math.min(unsafeWindow.userracks,(unsafeWindow.premium==1?3:2))-1); }
					$("racknavileftinfo").innerHTML = unsafeWindow.rack_tt_info+"&nbsp;"+Math.min(unsafeWindow.userracks,(unsafeWindow.premium==1?3:2));
					div=null;
				} else if (parseInt(unsafeWindow._currRack,10)==Math.min(unsafeWindow.userracks,(unsafeWindow.premium==1?3:2))-1){
					// Right arrow to first rack
					var div = unsafe$("racknaviright");
					div.className = "link racknavi";
					div.onmouseover = function(e) { unsafeWindow.showDiv("racknavirightinfo"); }
					div.onmouseout = function(e) { unsafeWindow.hideDiv("racknavirightinfo"); }
					div.onclick = function(e) { unsafeWindow.updateRack("0"); }
					$("racknavirightinfo").innerHTML = unsafeWindow.rack_tt_info+"&nbsp;1";
					div=null;
				}
			}
		}
	}catch(err){ GM_log("ERROR doRackNavi\n"+err); }
	}
	doRackNavi();	
	unsafeWindow._initRackNavi=unsafeWindow.initRackNavi;
	unsafeWindow.initRackNavi = function(){
		unsafeWindow._initRackNavi();
		doRackNavi();
	};
	*/
	if(newdiv=$("rackItems")){
		newdiv.addEventListener("dblclick",function(event){
			try{
				//GM_log("dblclick on "+event.target+" id="+event.target.id+" parentNode.id="+event.target.parentNode.id);
				var currId=null;
				var node=event.target;
				while((currId==null)&&(node!=this)){
					if(node.id.match(/rackitem\d+/)){
						currId=/rackitem(\d+)/.exec(node.id)[1];			
					}else{
						node=node.parentNode;
					}
				}
				if((currId!=null)&&(!prodBlock[0][currId].match(/t/))){ showMarket(currId); }
			}catch(err){GM_log("ERROR listener #rackItems.dblclick\n"+err);}
		},false);
	}
	unsafeWindow._linfo=unsafeWindow.linfo;
	unsafeWindow.linfo = function(title,amount,id,offset,felder,kategorie){
		unsafeWindow._linfo(title,amount,id,offset,felder,kategorie);
		var newdiv;
		var rackPopup=$("rackPopup");
		if (!isNaN(NPC[0][id])){
			newdiv=createElement("div",{"class":"tmenu","style":"position:relative;height:13px;width:172px;top:-75px;padding-left:20px;background: url('"+GFX+"lager/flaeche.gif') left top transparent;background-position:0px -155px;"},rackPopup);
			createElement("span",{"style":"float:left;width:60px;"},newdiv,texte["hofpreis"]+": ");
			createElement("span",{"style":"float:left;width:100px;text-align:right;"},newdiv,moneyFormat(NPC[0][id]));
		}
		if(!prodBlock[0][id].match(/t/)){
			newdiv=createElement("div",{"class":"tmenu","style":"position:relative;height:13px;width:172px;top:-75px;padding-left:20px;background: url('"+GFX+"lager/flaeche.gif') left top transparent;background-position:0px -155px;"},rackPopup);
			createElement("div",{"style":"display:inline-block;width:60px;"},newdiv,texte["marktpreis"]+": ");
			createElement("div",{"style":"display:inline-block;width:100px;text-align:right;"},newdiv,moneyFormat(gut[id]));
			newdiv=createElement("div",{"class":"tmenu","style":"position:relative;height:13px;width:172px;top:-75px;padding-left:20px;background: url('"+GFX+"lager/flaeche.gif') left top transparent;background-position:0px -155px;"},rackPopup);
			createElement("div",{"style":"display:inline-block;width:60px;"},newdiv,texte["wert"]+": ");
			createElement("div",{"style":"display:inline-block;width:100px;text-align:right;"},newdiv,moneyFormatInt(gut[id]*prodStock[0][id]));
			newdiv=createElement("div",{"class":"tmenu","style":"position:relative;height:25px;width:172px;top:-75px;padding-left:20px;background: url('"+GFX+"lager/flaeche.gif') left top transparent;background-position:0px -155px;"},rackPopup);
			createElement("div",{"style":"width:160px;"},newdiv,texte["clickDouble"]+": "+texte["goToMarket"]);
		}
		newdiv=null;rackPopup=null;
	};
	unsafeWindow._globalcommitbox=unsafeWindow.globalcommitbox;
	unsafeWindow.globalcommitbox = function(content,onclick,onclick2){
		unsafeWindow._globalcommitbox(content,onclick,onclick2);
		raiseEvent("gameOpenGlobalCommitBox");
	}
	unsafeWindow._globalBox=unsafeWindow.globalBox;
	unsafeWindow.globalBox = function(f, a, e, c, b){
		unsafeWindow._globalBox(f, a, e, c, b);
		raiseEvent("gameOpenGlobalBox");
	}

	if(newdiv=$("coins")){
		newdiv1=newdiv.cloneNode(true);
		newdiv1.id="coinsFormat";
		newdiv1.innerHTML=numberFormat(prodStock[0][0]);
		newdiv.style.display="none";
		newdiv.parentNode.appendChild(newdiv1);
		newdiv.parentNode.setAttribute("class","link");
		newdiv.parentNode.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,0); },false);
		newdiv.parentNode.addEventListener("click",function(){ showMarket(0); },false);
	}

	if(LNG=="se"){ $("bar").innerHTML=$("bar").innerHTML.replace(/\.(\d\d) /,",$1 "); }
	unsafeWindow._updatePlayerInfo=unsafeWindow.updatePlayerInfo;
	unsafeWindow.updatePlayerInfo = function(money,coins,points,level,deco){
		unsafeWindow._updatePlayerInfo(money,coins,points,level,deco);
		// GM_log("updatePlayerInfo money="+money+" coins="+coins+" points="+points+" level="+level+" deco="+deco);
		if(money){
			if(LNG=="se"){
				money=money.replace(/\.(\d\d) /,",$1 ");
				$("bar").innerHTML=money;
			}
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_bargeld",money.replace(texte["waehrung"],"").replace(/\s+/g,"").replace(regDelimThou,"").replace(regDelimDeci,"."));
		}
		if(coins){
			var c=parseInt(coins,10);
			if(!isNaN(c)){
				prodStock[0][0]=c;
				$("coinsFormat").innerHTML=numberFormat(c);
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock));
			}
		}
	};
	document.addEventListener("gameDoGetData",function(){
		window.setTimeout(loadProductData,0);
	},false);
	document.addEventListener("gameChangedBeobPrice",function(){
		window.setTimeout(function(){
			// GM_log("publish GMpreisBeob");
			top.unsafeData.preisBeob=explode(GM_getValue(LNG+"_"+SERVER+"_preisBeob","[]"),"eventListener@gameChangedBeobPrice/preisBeob",[]).clone();
		},0);
	},false);
	document.addEventListener("gameChangedGut",function(){
		window.setTimeout(function(){
			gut=explode(GM_getValue(LNG+"_"+SERVER+"_gut","[]"),"eventListener@gameChangedGut/gut",[]);
			top.unsafeData.gut=gut.clone();
			calcFarmiCost();
		},0);
	},false);
	document.addEventListener("gameChangedLevelLog",function(){
		window.setTimeout(function(){
			levelLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog","{}"),"eventListener@gameChangedLevelLog/levelLog",{});
		},0);
	},false);
	document.addEventListener("gameChangedProdMinRackInit",function(){
		window.setTimeout(function(){
			//if(valMinRackMan){ prodMinRackInit=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_prodMinRackInit","[]")); }
			calcProdMinRackInit();
		},0);
	},false);

	// events farm ================================================================================
	err_trace="events farm";
	function doGameFarmSwitch(){ // farm switched
		try{
			if(DEVMODE_FUNCTION){ GM_log("BEGIN doGameFarmSwitch"); }
			if(unsafeWindow.userfarminfos&&unsafeWindow.userfarminfos[unsafeWindow.farm]){
				gameLocation=["farm",unsafeWindow.farm-1];
				unsafeData.gameLocation=gameLocation.clone();
				// Farm zones
				for(var zoneNr=1;zoneNr<=6;zoneNr++){
					var zoneNrF=zoneNr+6*gameLocation[1];
					// GM_log(zoneNrF+"\n"+print_r(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr],"",true,"\n"));
					zoneTyp[zoneNrF]=parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["buildingid"],10);
					nodes["zonetimer_"+zoneNr]["state"]="farmChange";
	
					//if (zoneTyp[zoneNrF]==0){ zoneBlock[zoneNrF]=true; } //empty zone
					//else if (zoneTyp[zoneNrF]==6){ zoneBlock[zoneNrF]=true; } //Club
					zoneBlock[zoneNrF]="";
					if(BUILDINGTYPE[zoneTyp[zoneNrF]]==0){
						zoneBlock[zoneNrF]+="t"; //blocked by type (Club & Zimmerei)
					}
					if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["questblock"]){
						zoneBlock[zoneNrF]+="q"; //blocked by quest
					}
					if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["bulldozecost"]){
						zoneBlock[zoneNrF]+="b"; //blocked by payment
					}
					if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["status"]=="0"){
						zoneBlock[zoneNrF]+="s"; //blocked by status
					}
					if ((unsafeWindow.premium!=1) && (unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["premium"]==1)){
						zoneBlock[zoneNrF]+="p"; //premium-zone but no premium-account
					}
					if(zoneBlock[zoneNrF]&&isMultiSlotZone(zoneNrF)){
						for(var slot=1;slot<=3;slot++){ // TODO dynamic slot-amount
							zoneBlock[zoneNrF+"."+slot]=zoneBlock[zoneNrF];
						}
					}
	
					if (BUILDINGTYPE[zoneTyp[zoneNrF]]==1){
						// Field
						zoneAnimals[zoneNrF]=0;
						//waterlog GM_log("userfarminfos farm="+(gameLocation[1]+1)+" position="+zoneNr+":\n"+print_r(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr],"",true,"\n"));
						zoneBonus[zoneNrF]=parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["waterbonus"],10); // the normal waterbonus
						if(questData["farm"]["1"]["nr"]>170){ zoneBonus[zoneNrF]+=5; } // global bonus gained by quest 170
						zoneBonusSpecialProduct[zoneNrF]=unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["specialwaterbonus"][0]; // the id of special plant
						zoneBonusSpecialAmount[zoneNrF]=parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["specialwaterbonus"][1],10); // additional bonus for special plant
					}else if (BUILDINGTYPE[zoneTyp[zoneNrF]]>1){
						// Stables and Factories
						zoneAnimals[zoneNrF]=parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["animals"],10);
						zoneBonus[zoneNrF]=unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["time"];
					}
					//updateZoneTimer(zoneNr);
				}
				for(var v=0;v<totalAnimals.length;v++){
					if(totalAnimals[zoneTyp[v]]>0){totalAnimals[zoneTyp[v]]=0;}
				}
				for(var i=1;i<ALL_ZONES["farm"].length;i++){
					if(zoneAnimals[ALL_ZONES["farm"][i]]>0){totalAnimals[zoneTyp[ALL_ZONES["farm"][i]]]+=zoneAnimals[ALL_ZONES["farm"][i]];}
				}
				lastGiess=null;
				lastErnte=null;
				// City
				if(unsafeWindow.cities){
					zoneBlock["windmill"]=(unsafeWindow.cities>1?"":"l");
				}
				// Forestry
				if(unsafeWindow.userfarminfos[gameLocation[1]+1]["forestry"]==1){
					zoneBlock["forest"]="";
				}else{
					for(var j=0;j<ALL_ZONES["forestry"].length;j++){
						zoneBlock[ALL_ZONES["forestry"][j]]="q";
					}
				}
				// Saving
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneTyp",implode(zoneTyp));
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock));
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneAnimals",implode(zoneAnimals));
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonus",implode(zoneBonus));
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialProduct",implode(zoneBonusSpecialProduct));
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialAmount",implode(zoneBonusSpecialAmount));
				unsafeData.zoneTyp=zoneTyp.clone();
				unsafeData.zoneBlock=zoneBlock.clone();
				unsafeData.zoneAnimals=zoneAnimals.clone();
				unsafeData.zoneBonus=zoneBonus.clone();
				unsafeData.zoneBonusSpecialProduct=zoneBonusSpecialProduct.clone();
				unsafeData.zoneBonusSpecialAmount=zoneBonusSpecialAmount.clone();
			}
			raiseEvent("gameUpdateFarm"); // raised too often here?
			if(DEVMODE_FUNCTION){GM_log("End doGameFarmSwitch");}
		}catch(err){GM_log("doGameFarmSwitch \n"+err);}
	}
	function makeZoneTimers(zoneNr,type,style,append){ // type="zonetimer" || "zoneTimerWater"
		// GM_log("makeZoneTimers zoneNr="+zoneNr+" type="+type+" style="+style);
		if(nodes[type+"_"+zoneNr]){ return false; }
		nodes[type+"_"+zoneNr]=new Object();
		nodes[type+"_"+zoneNr]["state"]="hidden";

		nodes[type+"_"+zoneNr]["node"]=createElement("div",{"id":type+"_"+zoneNr,"class":type,"style":"z-index:3;margin:1px 0px;padding:2px;"+style},append,"---");
		nodes[type+"_"+zoneNr]["node"].setAttribute("state","hidden");
		nodes[type+"_"+zoneNr]["node"].addEventListener("mouseover",function(event){
			var type=this.id.split("_");
			var zoneNr=type[1];
			type=type[0];
			var zoneNrF;
			switch(zoneNr){
			case "globalWindmill": zoneNrF="windmill";break;
			case "globalForest":case "forest": zoneNrF="forest";break;
			case "globalSawmill":case "sawmill": zoneNrF="sawmill";break;
			case "globalCarpentry":case "carpentry": zoneNrF="carpentry";break;
			case "foodworld-1":case "globalFoodworld-1": zoneNrF="foodworld-1";break;
			case "foodworld-2":case "globalFoodworld-2": zoneNrF="foodworld-2";break; // is the globalFoodworld-n stuff needed here?			
			default: zoneNrF=parseInt(zoneNr,10)+6*gameLocation[1];
			}
			showBlase(zoneNrF);
			var newDiv1=createElement("div");
			var newTable=createElement("table",{"class":"white","border":"0","cellspacing":"0","cellpadding":"0"},newDiv1);
			var newTr=createElement("tr",{},newTable);
			var newTd=createElement("th",{"style":"border-bottom:1px solid white;","colspan":2},newTr,isNaN(zoneNrF)?texte[zoneNrF]:unsafeWindow.buildinginfos[0][zoneTyp[zoneNrF]][10]);
			if(type=="zonetimer"){
				var time = (zoneEndTimes[zoneNrF]&&zoneEndTimes[zoneNrF]!=NEVER)?(zoneEndTimes[zoneNrF]+unsafeWindow.Zeit.Verschiebung):NEVER;
				var endDay=countDays(now,time);
				newTr=createElement("tr",{},newTable);
				if(time==NEVER){
					createElement("td",{"colspan":2},newTr,"---");
				} else if (time<now){
					if(time+20*60*60<now){
						createElement("td",{"colspan":2},newTr,texte["fertigSeitX"].replace(/%1%/,getFormattedDateStr(time)));
					}else{
						createElement("td",{"colspan":2},newTr,texte["fertigSeitX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
					}				
				} else if (endDay==0){
					createElement("td",{"colspan":2},newTr,texte["readyAtX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
				} else if ((endDay==1)&&(texte["readyAtX_day1"])){
					createElement("td",{"colspan":2},newTr,texte["readyAtX_day1"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
				} else if ((endDay==2)&&(texte["readyAtX_day2"])){
					createElement("td",{"colspan":2},newTr,texte["readyAtX_day2"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
				} else{ 
					createElement("td",{"colspan":2},newTr,texte["readyAtX"].replace(/%1%/,new Date(1000*time).toLocaleString())); 
				}
				newTr=createElement("tr",{"style":"border-top:1px solid white;"},newTable);
				createElement("td",{"style":"border-top:1px solid white;","colspan":2},newTr,texte["yield"]+":");
				for(var k=0;k<zoneErnte[zoneNrF].length;k++){
					newTr=createElement("tr",{},newTable);
					newTd=createElement("td",{},newTr);
					produktPic(zoneErnte[zoneNrF][k][0],zoneErnte[zoneNrF][k][1],newTd);
					createElement("span",{},newTd,numberFormat(zoneErnte[zoneNrF][k][2])+"&nbsp;"+prodName[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]]);
					newTd=createElement("td",{"style":"padding-left:5px;"},newTr);
					if(zoneErnte[zoneNrF][k][3]>0){ pointsFormat(zoneErnte[zoneNrF][k][3],"div",newTd); }
				}
			}else{ // zonetimerWater
				var time = (zoneWaterTimes[zoneNrF]&&zoneWaterTimes[zoneNrF]!=NEVER)?(zoneWaterTimes[zoneNrF]+unsafeWindow.Zeit.Verschiebung):NEVER;
				var endDay=countDays(now,time);
				newTr=createElement("tr",{},newTable);
				if(time==NEVER){
					createElement("td",{"colspan":2},newTr,"---");
				} else if(time<now){
					createElement("td",{"colspan":2},newTr,texte["waterNeeded"]);
					// if(time+20*60*60<now){
					// 	createElement("td",{"colspan":2},newTr,texte["fertigSeitX"].replace(/%1%/,getFormattedDateStr(time)));
					// }else{
					// 	createElement("td",{"colspan":2},newTr,texte["fertigSeitX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
					// }				
				} else if (endDay==0){
					createElement("td",{},newTr,texte["waterNeededAtX"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
				} else if ((endDay==1)&&(texte["waterNeededAtX_day1"])){
					createElement("td",{},newTr,texte["waterNeededAtX_day1"].replace(/%1%/,getDaytimeStr(time)+"&nbsp;"+texte["uhr"]));
				} else{ 
					createElement("td",{},newTr,texte["waterNeededAtX"].replace(/%1%/,new Date(1000*time).toLocaleString())); 
				}
			}
			showToolTip(event,newDiv1.innerHTML);
			endDay=null;newDiv1=null;newTable=null;newTr=null;newTd=null;
			zoneNr=null;type=null;time=null;
		},false);
		nodes[type+"_"+zoneNr]["node"].addEventListener("mouseout",hideBlase,false);
	}
	function updateZoneTimer(timerName,zoneNrS){
		// GM_log("updateZoneTimer timerName="+timerName+" zoneNrS="+zoneNrS+" isSlot="+isSlot);
		try{
		var cell;
		var zoneNrF=zoneNrS.toString().replace(/\.\d+$/g,"");;
		var iGarden=getLocation(zoneNrF);
		if(!isNaN(iGarden)){ iGarden="farm"; }
		var zT=zoneEndTimes[zoneNrS]?zoneEndTimes[zoneNrS]:NEVER;
		var zTw=zoneWaterTimes[zoneNrS]?zoneWaterTimes[zoneNrS]:NEVER;
		var zP=zoneEndProducts[zoneNrS]?zoneEndProducts[zoneNrS]:null;

		// if(zT!=null && typeof zT=="object"){zT = zT[0];}
		// if(zTw!=null && typeof zTw=="object"){zTw = zTw[0];}
		// if(zP!=null && typeof zP=="object"){zP = zP[0];}

		// if(zT&&!zoneBlock[zoneNrF]&&(zoneTyp[zoneNrF]==undefined||(zoneTyp[zoneNrF]!=undefined&&BUILDINGTYPE[zoneTyp[zoneNrF]]>0))){
		if((!zoneBlock[zoneNrF])&&(isNaN(zoneNrF)||(BUILDINGTYPE[zoneTyp[zoneNrF]]>0))){
			if(zT<=unsafeWindow.Zeit.Server){ //READY
				nodes["zonetimer_"+timerName]["node"].setAttribute("endtime",unsafeWindow.Zeit.Server);
				if(nodes["zonetimer_"+timerName]["state"]!="ready"){
					nodes["zonetimer_"+timerName]["state"]="ready";
					nodes["zonetimer_"+timerName]["node"].setAttribute("state","ready");
					nodes["zonetimer_"+timerName]["node"].setAttribute("product",((zP!=null)?zP:""));
					nodes["zonetimer_"+timerName]["node"].innerHTML=texte["fertig"].toUpperCase()+"!";
					raiseEvent("nodeModifiedZone"+(timerName+"").capitalize());
				}
				hideZoneTimer(timerName,"zoneTimerWater");
				if(!isNaN(zoneNrF)){
					if(zoneTyp[zoneNrF]==1){ //Add exclamation
						cell=$("zoneinfo"+timerName);
						if (cell&&(cell.childElementCount==0)){ createElement("img",{"src":GFX+"incoming.gif","style":"position:absolute;top:30px;"},cell); }
					}
					if(nodes["imgNeedWater"+timerName]){ //Remove droplet
						if(nodes["imgNeedWater"+timerName]["node"]){ removeElement(nodes["imgNeedWater"+timerName]["node"]); }
						delete nodes["imgNeedWater"+timerName];
					}
				}
			}else if (zT==NEVER){ // empty
				nodes["zonetimer_"+timerName]["node"].setAttribute("endtime",unsafeWindow.Zeit.Server);
				if(nodes["zonetimer_"+timerName]["state"]!="empty"){
					//GM_log("updateZoneTimer EMPTY zonetime"+timerName+" old-state:"+nodes["zonetimer_"+timerName]["state"]);
					nodes["zonetimer_"+timerName]["state"]="empty";
					nodes["zonetimer_"+timerName]["node"].setAttribute("state","empty");
					nodes["zonetimer_"+timerName]["node"].setAttribute("product","");
					nodes["zonetimer_"+timerName]["node"].innerHTML="---";
					raiseEvent("nodeModifiedZone"+(timerName+"").capitalize());
					//raiseEvent("gameZoneEmpty"); //TODO
				}
				hideZoneTimer(timerName,"zoneTimerWater");
				if(!isNaN(zoneNrF)){
					if(zoneTyp[zoneNrF]==1){ //Add exclamation
						cell=$("zoneinfo"+timerName);
						if (cell&&(cell.childElementCount==0)){ createElement("img",{"src":GFX+"incoming.gif","style":"position:absolute; top:30px;"},cell); }
					}
					if(nodes["imgNeedWater"+timerName]){ //Remove droplet
						if(nodes["imgNeedWater"+timerName]["node"]){ removeElement(nodes["imgNeedWater"+timerName]["node"]); }
						delete nodes["imgNeedWater"+timerName];
					}
				}
			}else{ // running
				nodes["zonetimer_"+timerName]["node"].innerHTML=getTimeStr(zT-unsafeWindow.Zeit.Server);
				if(nodes["zonetimer_"+timerName]["state"]!="busy"){
					//GM_log("updateZoneTimer BUSY zonetime"+timerName+" old-state:"+nodes["zonetimer_"+timerName]["state"]);
					nodes["zonetimer_"+timerName]["state"]="busy";
					nodes["zonetimer_"+timerName]["node"].setAttribute("state","busy");
					nodes["zonetimer_"+timerName]["node"].setAttribute("endtime",zT);
					nodes["zonetimer_"+timerName]["node"].setAttribute("product",((zP!=null)?zP:""));
					raiseEvent("nodeModifiedZone"+(timerName+"").capitalize());
				}
				if(zTw<zT){
					if(nodes["zoneTimerWater_"+timerName]){
						if(unsafeWindow.Zeit.Server<zTw){
							nodes["zoneTimerWater_"+timerName]["node"].innerHTML=getTimeStr(zTw-unsafeWindow.Zeit.Server);
							if(nodes["zoneTimerWater_"+timerName]["state"]!="busy"){
								nodes["zoneTimerWater_"+timerName]["state"]="busy";
								nodes["zoneTimerWater_"+timerName]["node"].setAttribute("state","busy");
								nodes["zoneTimerWater_"+timerName]["node"].setAttribute("endtime",zTw);
							}
						}else{
							if(nodes["zoneTimerWater_"+timerName]["state"]!="ready"){
								nodes["zoneTimerWater_"+timerName]["state"]="ready";
								nodes["zoneTimerWater_"+timerName]["node"].setAttribute("state","ready");
								nodes["zoneTimerWater_"+timerName]["node"].setAttribute("endtime",unsafeWindow.Zeit.Server);
								nodes["zoneTimerWater_"+timerName]["node"].innerHTML=texte["fertig"].toUpperCase()+"!";
							}
						}
					}	
				}else{
					hideZoneTimer(timerName,"zoneTimerWater");
				}
				if(zoneTyp[zoneNrF]==1){
					if((cell=$("zoneinfo"+timerName))&&cell.firstElementChild){ removeElement(cell.firstElementChild); }
					if(valWaterNeeded[iGarden]&&(zTw<unsafeWindow.Zeit.Server)){ //watering needed
						if(nodes["imgNeedWater"+timerName]&&nodes["imgNeedWater"+timerName]["node"]){
							if(nodes["imgNeedWater"+timerName]["state"]==""){
								nodes["imgNeedWater"+timerName]["state"]="hidden";

								nodes["imgNeedWater"+timerName]["node"].style.display="none";
							}else{
								nodes["imgNeedWater"+timerName]["state"]="";
								nodes["imgNeedWater"+timerName]["node"].style.display="";
							}
						}else{
							if((cell=$("zoneinfo"+timerName))&&cell.firstElementChild){ // Controlle if the zone is filled
								nodes["imgNeedWater"+timerName]=new Object();
								nodes["imgNeedWater"+timerName]["state"]="";
								nodes["imgNeedWater"+timerName]["node"]=createElement("img",{"id":"imgNeedWater"+timerName,"src":GFX+"garten/gegossen_static.gif"},cell.firstElementChild);
							}
						}
					}else if(nodes["imgNeedWater"+timerName]){
						if(nodes["imgNeedWater"+timerName]["node"]){ removeElement(nodes["imgNeedWater"+timerName]["node"]); }
						delete nodes["imgNeedWater"+timerName];
					}
				}
			}
		}else{
			hideZoneTimer(timerName,"zonetimer");
			hideZoneTimer(timerName,"zoneTimerWater");
			if(zoneTyp[zoneNrF]==1){
				if((cell=$("zoneinfo"+timerName))&&cell.firstElementChild){ removeElement(cell.firstElementChild); }
				if(nodes["imgNeedWater"+timerName]){
					if(nodes["imgNeedWater"+timerName]["node"]){ removeElement(nodes["imgNeedWater"+timerName]["node"]); }
					delete nodes["imgNeedWater"+timerName];
				}
			}
		}
		cell=null;
	}catch(err){GM_log("ERROR updateZoneTimer timerName:"+timerName+" zoneNrS:"+zoneNrS+"\n"+err);}
	}
	function hideZoneTimer(timerName,type){ //type="zonetime" || "zoneTimerWater"
		try{
			if(nodes[type+"_"+timerName]&&nodes[type+"_"+timerName]["state"]!="hidden"){
				nodes[type+"_"+timerName]["state"]="hidden";
				nodes[type+"_"+timerName]["node"].setAttribute("state","hidden");
				nodes[type+"_"+timerName]["node"].removeAttribute("endtime");
				nodes[type+"_"+timerName]["node"].removeAttribute("product");
				nodes[type+"_"+timerName]["node"].innerHTML="---";
			}
		}catch(err){GM_log("ERROR hideZoneTimer timerName="+timerName+" type="+type+"\n"+err);}
	}
	function checkReadyZone(zoneNrS){
	try{
		var zoneNrF=zoneNrS.toString().replace(/\.\d+$/g,"");;
		var iGarden=getLocation(zoneNrF);
		if(!isNaN(iGarden)){ iGarden="farm"; }
		var readyZoneAdded=0;
		var zT=zoneEndTimes[zoneNrS]?zoneEndTimes[zoneNrS]:NEVER;
		var zTw=zoneWaterTimes[zoneNrS]?zoneWaterTimes[zoneNrS]:NEVER;

		// if(zT!=null && typeof zT=="object"){zT = zT[0];}
		// if(zTw!=null && typeof zTw=="object"){zTw = zTw[0];}

		// if(zT&&!zoneBlock[zoneNrF]&&(zoneTyp[zoneNrF]==undefined||(zoneTyp[zoneNrF]!=undefined&&BUILDINGTYPE[zoneTyp[zoneNrF]]>0))){
		if((!zoneBlock[zoneNrF])&&(isNaN(zoneNrF)||(BUILDINGTYPE[zoneTyp[zoneNrF]]>0))){
			if(zT<=unsafeWindow.Zeit.Server){ //READY
				if(unsafeData.readyZone[zoneNrS]&&(unsafeData.readyZone[zoneNrS][1]=="r")){
					if(!unsafeData.readyZone[zoneNrS][2]){ unsafeData.readyZone[zoneNrS][2]=true; }
				}else{
					if(DEVMODE){GM_log("checkReadyZone readyZone add=READY zoneNrS="+zoneNrS);}
					unsafeData.readyZone[zoneNrS]=[getLocation(zoneNrF),"r",true];
					readyZoneAdded=1;
				}
			}else if (zT==NEVER){ // empty
				if(unsafeData.readyZone[zoneNrS]&&(unsafeData.readyZone[zoneNrS][1]=="e")){
					if(!unsafeData.readyZone[zoneNrS][2]){ unsafeData.readyZone[zoneNrS][2]=true; }
				}else{
					unsafeData.readyZone[zoneNrS]=[getLocation(zoneNrF),"e",true];
					readyZoneAdded=1;
				}
			}else{ // running (unsafeWindow.Zeit.Server<zT)
				if(valWaterNeeded[iGarden]&&(zTw<unsafeWindow.Zeit.Server)&&(zoneBonus[zoneNrF]>0)){
					//zTw<zT removes the watertimer if ready later then the field timer
					if(unsafeData.readyZone[zoneNrS]&&(unsafeData.readyZone[zoneNrS][1]=="w")){
						if(!unsafeData.readyZone[zoneNrS][2]){ unsafeData.readyZone[zoneNrS][2]=true; }
					}else{
						if(DEVMODE){GM_log("checkReadyZone readyZone add:WATER zoneNrS:"+zoneNrS);}
						unsafeData.readyZone[zoneNrS]=[getLocation(zoneNrF),"w",true];
						readyZoneAdded=1;
					}
				}else if(unsafeData.readyZone[zoneNrS]){
					if(DEVMODE){GM_log("checkReadyZone readyZone add:DELETE zoneNrS:"+zoneNrS);}
					delete unsafeData.readyZone[zoneNrS];
				}
			}
		}
		return readyZoneAdded;
	}catch(err){GM_log("ERROR checkReadyZone zoneNrS="+zoneNrS+"\n"+err);}
	}
	// Farm filling
	// initZones > getUserFarmInfos > userFarmInfosResponse > getTimeEvents >
	// unsafeWindow._initZones=unsafeWindow.initZones;
	// unsafeWindow.initZones = function(farmid){
	// 	unsafeWindow._initZones(farmid);
	// }
	
	unsafeWindow._timeEventsResponse=unsafeWindow.timeEventsResponse;
	unsafeWindow.timeEventsResponse = function(request){
		unsafeWindow._timeEventsResponse(request);
		if(checkRequest(request)){
			doGameFarmSwitch(); // also: timeEventsResponse->updateZone->doZone->doGameFarmSwitch
			// raiseEvent("gameUpdateFarm");
			//GM_log("timeEventsResponse end");
		}
	};

	function drawZoneNavi(zoneNrF,container){
	try{
		// GM_log("drawZoneNavi zoneNrF="+zoneNrF);
		var newdiv=$("zoneNavi");
		if(newdiv){ removeElement(newdiv); }
		newdiv=createElement("div",{"id":"zoneNavi"},container);
		var newdiv1;
		var c=[null,null,null];
		for(var i=0;i<ALL_ZONES["farm"].length;i++){
			if(ALL_ZONES["farm"][i]==zoneNrF){
				c[1]=i;break;
			}
		}
		if(c[1]!=null){
			c[2]=((c[1]+1)%ALL_ZONES["farm"].length);
			while(zoneBlock[ALL_ZONES["farm"][c[2]]]||(zoneTyp[ALL_ZONES["farm"][c[2]]]!=zoneTyp[zoneNrF])){
				c[2]=((c[2]+1)%ALL_ZONES["farm"].length);
			}
			if (c[1]!=c[2]){
				c[0]=((c[1]+ALL_ZONES["farm"].length-1)%ALL_ZONES["farm"].length);
				while(zoneBlock[ALL_ZONES["farm"][c[0]]]||(zoneTyp[ALL_ZONES["farm"][c[0]]]!=zoneTyp[zoneNrF])){
					c[0]=((c[0]+ALL_ZONES["farm"].length-1)%ALL_ZONES["farm"].length);
				}
				if (c[0]!=c[2]){
				newdiv1=createElement("div",{"class":"link leftarrow","zone":ALL_ZONES["farm"][c[0]]},newdiv);
				newdiv1.addEventListener("click",function(){
					var zone=parseInt(this.getAttribute("zone"),10);
					if(this.parentNode){ removeElement(this.parentNode); }
					goToFarmZone(zone);
					zone=null;
				},false);
				newdiv1.addEventListener("mouseover",function(event){ 
					var zone=parseInt(this.getAttribute("zone"),10);
					showToolTip(event,"Go to zone "+Math.ceil(zone/6)+"."+(1+((zone-1)%6))); 
					zone=null;
				},false);
				}
				newdiv1=createElement("div",{"class":"link rightarrow","zone":ALL_ZONES["farm"][c[2]]},newdiv);
				newdiv1.addEventListener("click",function(){
					var zone=parseInt(this.getAttribute("zone"),10);
					if(this.parentNode){ removeElement(this.parentNode); }
					goToFarmZone(zone);
					zone=null;
				},false);
				newdiv1.addEventListener("mouseover",function(event){ 
					var zone=parseInt(this.getAttribute("zone"),10);
					showToolTip(event,"Go to zone "+Math.ceil(zone/6)+"."+(1+((zone-1)%6))); 
					zone=null;
				},false);
			}
		}
		newdiv=null;newdiv1=null;
	}catch(err){GM_log("ERROR drawZoneNavi zoneNrF="+zoneNrF+"\n"+err);}
	}
	function doZone(zoneNr){
	try{
		//GM_log("Begin doZone "+zoneNr);
		if(unsafeWindow.farm){
			var divZone=$("zone"+zoneNr);
			if((gameLocation[0]!="farm")||(gameLocation[1]!=unsafeWindow.farm-1)){
				doGameFarmSwitch();
				//GM_log("doZone "+zoneNr+" continue");
			}
			var zoneNrF=zoneNr+6*gameLocation[1];
			var buildinginfoname=(zoneTyp[zoneNrF]==1&&unsafeWindow.userfarminfos[gameLocation[1]+1]["forestry"]!=undefined?(zoneNr%3==0?'buildinginfo_right':'buildinginfo_left'):'buildinginfo');

			// zone is blocked
			divZone.style.opacity=(zoneBlock[zoneNrF].match(/[pq]/)?0.5:1);

			if(zoneTyp[zoneNrF]==0){
				if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["bulldozecost"]){
					// rocked zones
					if(!$("bulldozecost"+zoneNr)){
						createElement("div",{"id":"bulldozecost"+zoneNr,"class":"blackbox","style":"position:absolute;"},divZone,moneyFormatInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["bulldozecost"]));
					}
					// Zone-MouseOver
					newdiv=divZone.getElementsByTagName("div")[0];
					if(newdiv){
						newdiv.addEventListener("mouseover",function(event){
							var zoneNr=parseInt(containerId(this).replace("zone",""),10);
							var info = $("bulldozetooltip"+zoneNr);
							if(info){
								showToolTip(event,info.innerHTML,this);
							}
							info=null;
						},false);
					}
				}else{
					// unbuild zones
					// Zone-MouseOver
					newdiv=divZone.getElementsByTagName("img")[0];
					if(newdiv){
						newdiv.addEventListener("mouseover",function(event){
							var zoneNr=parseInt(containerId(this).replace("zone",""),10);
							var info = $("emptyfieldtooltip"+zoneNr);
							if(info){
								showToolTip(event,info.innerHTML,this);
							}
							info=null;
						},false);
					}
				}
				zoneProductionData[zoneNrF]=[[{},{}],0,0,true];
				processZoneProductionData(zoneNrF);
			}else if (BUILDINGTYPE[zoneTyp[zoneNrF]]==0){
				// club
				var newdiv;
				// "Reallocate building"-Button
				if(newdiv=$("reallocatebuildingbutton"+zoneNr)){ removeElement(newdiv.parentNode); }
				// Zone-Mouseover
				divZone.children[0].addEventListener("mouseover",function(event){
					var info = this.querySelector(".buildinginfo");
					if(info){
						showToolTip(event,info.innerHTML,this);
					}
					info=null;
				},false);
				zoneProductionData[zoneNrF]=[[{},{}],0,0,true];
				processZoneProductionData(zoneNrF);
				newdiv=null;
			}else{
				var newdiv;
				if(!$("zone"+zoneNr+"Berater")){
					createElement("h1",{"id":"zone"+zoneNr+"Berater","style":"display:none;"},divZone);
					// Destruct-Button (done by CSS)
					// if(newdiv=$("buildingdestructbutton"+zoneNr)){ removeElement(newdiv); }
					// Level-Stars
					var help=divZone.querySelector("#levelstars").childElementCount; // TODO replace by stored zoneLevel
					// userfarminfos[farm][position]["level"]
					// Upgrade-Button
					if(BUILDING_UPGRADES[zoneTyp[zoneNrF]]&&BUILDING_UPGRADES[zoneTyp[zoneNrF]][help]){
						var newdiv1=$("updateinfo"+zoneNr);
						if (newdiv1){
							newdiv1.innerHTML="";
							if(isNaN(BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1])){
								createElement("div",{"style":"font-weight:bold;"},newdiv1,texte["ausbauenFuerX"].replace(/%1%/,BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1].replace("c","")+"&nbsp;"+texte["coins"]));
							}else if(unsafeData.carpentry_bonus){
								createElement("div",{"style":"font-weight:bold;"},newdiv1,texte["ausbauenFuerX"].replace(/%1%/,moneyFormatInt((1-unsafeData.carpentry_bonus/100)*BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1])));
							}else{
								createElement("div",{"style":"font-weight:bold;"},newdiv1,texte["ausbauenFuerX"].replace(/%1%/,moneyFormatInt(BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1])));
							}
							newdiv=$("buildingupdatebutton"+zoneNr);
							newdiv.parentNode.id="zoneupdatebutton"+zoneNr;
							newdiv.parentNode.addEventListener("mouseover",function(event){
								showToolTip(event,$(this.id.replace("zoneupdatebutton","updateinfo")).innerHTML,this);
							},false);

						}else if(valSpoilerZoneUpdate){
							newdiv=createElement("div",{"id":"zoneupdatebutton"+zoneNr},$("zonebuttons"+zoneNr));
							newdiv.addEventListener("mouseover",function(event){
								showToolTip(event,$(this.id.replace("zoneupdatebutton","updateinfo")).innerHTML,this);
							},false);
							createElement("img",{"id":"buildingupdatebutton"+zoneNr,"src":GFX+"buildingupdatebutton_off.png","style":"width:25px;height:25px;"},newdiv);
							createElement("div",{"style":"position:absolute;top:0;left:0;width:19px;height:19px;border:3px solid #117711;border-radius:15px;","onmouseout":"changeButton('buildingupdatebutton"+zoneNr+"',0,"+zoneNr+");hideDiv('updateinfo"+zoneNr+"');","onmouseover":"changeButton('buildingupdatebutton"+zoneNr+"',1,"+zoneNr+"); showDiv('updateinfo"+zoneNr+"');"},newdiv);
							newdiv1=createElement("div",{"id":"updateinfo"+zoneNr,"style":"display:none;position:absolute;top:75px;left:35px;z-index:100;","class":"blackbox"},divZone);
							createElement("div",{"style":"font-weight:bold;border-bottom:1px solid white;"},newdiv1,texte["levelXneeded"].replace(/%1%/,BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][0])+"<br>");
							createElement("div",{},newdiv1,texte["ausbauenFuerX"].replace(/%1%/,(isNaN(BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1]))?BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1].replace("c","")+"&nbsp;"+texte["coins"]:moneyFormatInt(BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][1])));
						}
						if(newdiv1){
							var help2=BUILDING_UPGRADES[zoneTyp[zoneNrF]][help-1][2]-BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][2];
							if(help2>0){
								if(zoneTyp[zoneNrF]==1){
									if(help>3){
										createElement("div",{"style":"border-top:1px solid white;"},newdiv1,unsafeWindow.updatetext[7].replace(/%MORE%/,numberFormat(100*help2)));
									}else{
										createElement("div",{"style":"border-top:1px solid white;"},newdiv1,unsafeWindow.updatetext[6].replace(/%MORE%/,numberFormat(100*(1-BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][2]))));
									}
								}else{
									createElement("div",{"style":"border-top:1px solid white;"},newdiv1,unsafeWindow.updatetext[2].replace(/%MORE%/,numberFormat(100*help2)));
								}
							}
							help2=BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][3]-BUILDING_UPGRADES[zoneTyp[zoneNrF]][help-1][3];
							if(help2>0){ // more animals
								createElement("div",{"style":"border-top:1px solid white;"},newdiv1,unsafeWindow.updatetext[1].replace(/%MORE%/,numberFormat(BUILDING_UPGRADES[zoneTyp[zoneNrF]][help][3])));
								var animalCost=0;
								for(var nr=1;nr<=help2;nr++){
									animalCost += Math.round(ANIMALCOST[zoneTyp[zoneNrF]][0]+(totalAnimals[zoneTyp[zoneNrF]]+nr)*ANIMALCOST[zoneTyp[zoneNrF]][1]);
								}
								createElement("div",{},newdiv1,"(+"+help2+",&nbsp;"+moneyFormatInt(animalCost)+")");
							}
						}
						newdiv1=null;
					}
					if(zoneTyp[zoneNrF]>0 /* !=1 */){
					// TODO FIX IT for forestry 
						// Replace Level-Stars (else its blocks zone mouseover)
						divZone.querySelector(".bm"+zoneTyp[zoneNrF]).appendChild(divZone.querySelector("#levelstars"));
						// Zone-Mouseover
						// divZone.children[0].children[0].onmouseover = "";
						divZone.children[0].addEventListener("mouseover",function(event){
							var zoneNr=parseInt(containerId(this).replace("zone",""),10);
							var zoneNrF=zoneNr+6*gameLocation[1];
							doLagerZeit(zoneNr);
							var buildinginfo = this.querySelector(".buildinginfo");
							if(buildinginfo){
								if(!buildinginfo.querySelector(".berater")){
									createElement("div",{"class":"berater","style":"display:none;"},buildinginfo);
									var newTable,newTr,newTd,newDiv;
									newTable=createElement("table",{"class":"white","border":"0","cellspacing":"0","cellpadding":"0"},buildinginfo);
									if(BUILDINGTYPE[zoneTyp[zoneNrF]]==2){
										for(var output in BUILDING_INPUT[zoneTyp[zoneNrF]]){
											if(!BUILDING_INPUT[zoneTyp[zoneNrF]].hasOwnProperty(output)){ continue; }
											if(prodBlock[0][output]){ continue; }
											newTr=createElement("tr",{},newTable);
											newTd=createElement("td",{"style":"border-top:1px solid white;padding-right:5px;"},newTr);
											newDiv=createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd);
											produktPic(0,output,newDiv);
											createElement("span",{},newDiv,numberFormat(prodYield[0][output]*zoneAnimals[zoneNrF])+" "+prodName[0][output]);
											pointsFormat(prodYield[0][output]*zoneAnimals[zoneNrF]*prodPoints[0][output],"div",newTd);
											// var time=60*prodGrowTime[0][output]*(100-unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["time"])*unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["animals"];
											// 60*prodGrowTime[0][output]*(100-zoneBonus[zoneNrF])/100
											var time=[];
											time[0]=calcProductionTime(2,0,output,1-zoneBonus[zoneNrF]/100,BUILDING_INPUT[zoneTyp[zoneNrF]][output][0][0][1]/zoneAnimals[zoneNrF])[0];
											time[1]=calcProductionTime(2,0,output,1-zoneBonus[zoneNrF]/100,BUILDING_INPUT[zoneTyp[zoneNrF]][output][0][0][1]/zoneAnimals[zoneNrF],1)[0];
											for(var alt=1;alt<BUILDING_INPUT[zoneTyp[zoneNrF]][output].length;alt++){
												time[0]=Math.min(time[0],calcProductionTime(2,0,output,1-zoneBonus[zoneNrF]/100,BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][0][1]/zoneAnimals[zoneNrF])[0]);
												time[1]=Math.max(time[1],calcProductionTime(2,0,output,1-zoneBonus[zoneNrF]/100,BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][0][1]/zoneAnimals[zoneNrF],1)[0]);
											}
											createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd,getTimeStr(time[0])+" - "+getTimeStr(time[1]));
											for(var alt=0;alt<BUILDING_INPUT[zoneTyp[zoneNrF]][output].length;alt++){
												newTd=createElement("td",{"style":"border-top:1px solid white;border-left:1px dashed white;padding:0 5px;"},newTr);
												for(var i=0;i<BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt].length;i++){
													newDiv=createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd);
													produktPic(0,BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][0],newDiv);
													createElement("span",{},newDiv,"1 - "+numberFormat(calcProductionTime(2,0,output,1-zoneBonus[zoneNrF]/100,BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][0][1]/zoneAnimals[zoneNrF])[1])+" "+prodName[0][BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][0]]);
													createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd,getTimeStr(BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][1]/zoneAnimals[zoneNrF]));
												}
											}
										}
									}else if(BUILDINGTYPE[zoneTyp[zoneNrF]]==3){
										for(var output in BUILDING_INPUT[zoneTyp[zoneNrF]]){
											if(!BUILDING_INPUT[zoneTyp[zoneNrF]].hasOwnProperty(output)){ continue; }
											if(prodBlock[0][output]){ continue; }
											newTr=createElement("tr",{},newTable);
											newTd=createElement("td",{"style":"border-top:1px solid white;padding-right:10px;"},newTr);
											newDiv=createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd);
											produktPic(0,output,newDiv);
											createElement("span",{},newDiv,numberFormat(prodYield[0][output])+" "+prodName[0][output]);
											pointsFormat(prodYield[0][output]*prodPoints[0][output],"div",newTd);
											createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd,getTimeStr(60*prodGrowTime[0][output]*(100-zoneBonus[zoneNrF])/100));
											for(var alt=0;alt<BUILDING_INPUT[zoneTyp[zoneNrF]][output].length;alt++){
												newTd=createElement("td",{"style":"border-top:1px solid white;border-left:1px dashed white;padding:0 5px;"},newTr);
												for(var i=0;i<BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt].length;i++){
													newDiv=createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newTd);
													produktPic(0,BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][0],newDiv);
													createElement("span",{},newDiv,numberFormat(BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][1])+" "+prodName[0][BUILDING_INPUT[zoneTyp[zoneNrF]][output][alt][i][0]]);
												}
											}
										}
									}
									newTable=null;newTr=null;newTd=null;newDiv=null;
								}
								showToolTip(event,buildinginfo.innerHTML,this);
							}
							buildinginfo=null;zoneNr=null;zoneNrF=null;
						},false);
					}
					switch(zoneTyp[zoneNrF]){
					case 1:{ // field
						// Replace the SpecialWater Icon (else its mouseover is overlayered by zone mouseover)
						if(help=(/changeGardenSpecial\(\d+,(\d+)\)/).exec(divZone.innerHTML)){
							newdiv=divZone.getElementsByClassName("stt"+help[1])[0];
							newdiv.parentNode.parentNode.appendChild(newdiv);
						}
						// percentage of garbaged area
						if(zoneProductionData[zoneNrF]&&zoneProductionData[zoneNrF][2]&&(zoneProductionData[zoneNrF][2][1]<120)){
							createElement("div",{"class":"blackbox","style":"position:absolute;top:50px;left:50px;padding:4px;font-weight:bold;"},divZone.firstElementChild.firstElementChild,numberFormat(100*zoneProductionData[zoneNrF][2][1]/120)+"%");
						}
						if(newdiv=$("speedupgardenbutton"+zoneNr)){
							newdiv.parentNode.style.left="5px";
						}
						// Autoplant-Button
						if(newdiv=$("autoplantbutton"+zoneNr)){
							divZone.appendChild(newdiv.parentNode);
							newdiv.parentNode.setAttribute("zoneNr",zoneNr);
							newdiv.parentNode.addEventListener("mouseover",function(event){
								showToolTip(event,$("autoplantinfo"+this.getAttribute("zoneNr")).innerHTML,this);
							},false);
						}
						// SpeedUp-Button
						if(newdiv=$("speedupgardenbutton"+zoneNr)){
							divZone.appendChild(newdiv.parentNode);
							newdiv.parentNode.setAttribute("zoneNr",zoneNr);
							newdiv.parentNode.addEventListener("mouseover",function(event){
								showToolTip(event,$("speedupgardenbuttoninfo"+this.getAttribute("zoneNr")).innerHTML,this);
							},false);
						}
					break;}
					case 2:{ // chicken
						// more animals
						createElement("img",{"src":GFX+"chickenmapani2.gif","style":"position:absolute;top:30px;left:10px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"chickenmapani2.gif","style":"position:absolute;top:30px;left:50px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"chickenmapani1.gif","style":"position:absolute;top:50px;left:70px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"chickenmapani1.gif","style":"position:absolute;top:60px;left:30px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"chickenmapani1.gif","style":"position:absolute;top:80px;left:30px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"chickenmapani2.gif","style":"position:absolute;top:100px;left:50px;"},divZone.firstElementChild.firstElementChild);
					break;}
					case 4:{ // sheep
						// more animals
						createElement("img",{"src":GFX+"sheep_ani01.gif","style":"position:absolute;top:60px;left:30px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"sheep_ani02.gif","style":"position:absolute;top:30px;left:10px;"},divZone.firstElementChild.firstElementChild);
					break;}
					case 12:{ // goats
						// more animals
						createElement("img",{"src":GFX+"goat_ani_01.gif","style":"position:absolute;top:105px;left:50px;"},divZone.firstElementChild.firstElementChild);
						createElement("img",{"src":GFX+"goat_ani_02.gif","style":"position:absolute;top:75px;left:30px;"},divZone.firstElementChild.firstElementChild);
					break;}
					case 13:{
						if(newdiv=$("farm_production_current13_"+zoneNr)){ divZone.appendChild(newdiv); }
					}
					case 14:{
						if(newdiv=$("farm_production_current14_"+zoneNr)){ divZone.appendChild(newdiv); }
					}
					}
					raiseEvent("nodeModifiedZone"+zoneNr);
				}
				// "Reallocate building"-Button
				if(newdiv=$("reallocatebuildingbutton"+zoneNr)){ removeElement(newdiv.parentNode); }
				// Zone Info - showing current production
				var divZoneInfo=divZone.querySelector('div[onmouseover*="showDiv(\'timeevent'+zoneNr+'\'\);"]');
				if(!divZoneInfo){
					divZoneInfo=$("farm_production_current"+zoneTyp[zoneNrF]+"_"+zoneNr);
					if(!divZoneInfo){
						divZoneInfo=$("zoneinfo"+zoneNr);
						if(!divZoneInfo){
							divZoneInfo=createElement("div",{"id":"zoneinfo"+zoneNr},divZone);
						}
					}
				}
				if(!$("timeevent"+zoneNr)){
					createElement("div",{"id":"timeevent"+zoneNr,"class":"blackbox"},divZone);
				}
				if(!divZoneInfo.getAttribute("hasEventListener_mouseover")){
					divZoneInfo.setAttribute("hasEventListener_mouseover",true);
					divZoneInfo.addEventListener("mouseover",function(event){
						var zoneNr=parseInt(containerId(this).replace("zone",""),10);
						var zoneNrF=zoneNr+6*gameLocation[1];
						var info=this.querySelector(".berater");
						if(!info){
							info=createElement("div",{"class":"berater","style":"display:none;"},this);
							var points=0;
							var newdiv=createElement("div",{},info,texte["yield"]+":");
							for(var k=0;k<zoneErnte[zoneNrF].length;k++){
								newdiv=createElement("div",{"style":"height:15px"},info);
								produktPic(zoneErnte[zoneNrF][k][0],zoneErnte[zoneNrF][k][1],newdiv);
								createElement("span",{},newdiv,numberFormat(zoneErnte[zoneNrF][k][2])+"&nbsp;"+prodName[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]]);
								points += zoneErnte[zoneNrF][k][3];
							}
							pointsFormat(points,"div",info);
							newdiv=null;points=null;
						}
						showToolTip(event,info.innerHTML,this);
						info=null;
					},false);
				}
				// divZoneInfo.addEventListener("mouseout",function(){$(this.id.replace("zoneinfo","timeevent")).style.display="none";},false);

				if(zoneBlock[zoneNrF]){
					zoneProductionData[zoneNrF]=[[{},{}],0,0,true];
					processZoneProductionData(zoneNrF);
				}else{
					if (zoneTyp[zoneNrF]==1){
						// Field
						divZoneInfo.setAttribute("class","v"+zoneMainprod[zoneNrF]);
						if (zoneEndTimes[zoneNrF]<=now){
							if (divZoneInfo.childElementCount==0){ createElement("img",{"src":GFX+"incoming.gif", "style":"position:absolute; top:30px;"},divZoneInfo); }
						}else{
							if (divZoneInfo.childElementCount>0){ removeElement(divZoneInfo.firstElementChild); }
						}
					}else{
						// Stable and Factory
						// GM_log("userfarminfos:\n"+print_r(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr],"",true,"\n"));
						// fetch data for single-slot zones
						if(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["slot"]=="0"){
							var tempZoneProductionData=[[{},{}],0,0,true];
							if(parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["level"],10)>0){
								if ((!isNaN(unsafeWindow.run[zoneNr]))&&(parseInt(unsafeWindow.run[zoneNr],10)>0)){
									if (isNaN(unsafeWindow.time[zoneNr])){ // running interval but no time set
										GM_log("doZone BAD DATA zoneNrF="+zoneNrF+": run="+unsafeWindow.run[zoneNr]+"("+(typeof unsafeWindow.run[zoneNr])+") : time="+unsafeWindow.time[zoneNr]+"("+(typeof unsafeWindow.time[zoneNr])+")");
									}else{ // running
										var iPrTyp=0;
										var iProd=parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["productid"],10);
										var iTime=1+parseInt(unsafeWindow.time[zoneNr],10)+now-unsafeWindow.Zeit.Verschiebung;
										var iAmount=((BUILDINGTYPE[zoneTyp[zoneNrF]]==2)?parseInt(unsafeWindow.userfarminfos[gameLocation[1]+1][zoneNr]["animals"],10):1);
										if(!tempZoneProductionData[0][iPrTyp][iProd]){ tempZoneProductionData[0][iPrTyp][iProd]=[]; }
										tempZoneProductionData[0][iPrTyp][iProd].push([iAmount,iTime,NEVER]);
									}
								}else{ // empty
									tempZoneProductionData[1]=1;
									if(unsafeData.readyZone[zoneNrF]){
										if(unsafeData.readyZone[zoneNrF][1]!="e"){ unsafeData.readyZone[zoneNrF][1]="e"; }
										if(!unsafeData.readyZone[zoneNrF][2]){ unsafeData.readyZone[zoneNrF][2]=true; }
									}
								}
								tempZoneProductionData[2]=1;
							}
							zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
							processZoneProductionData(zoneNrF);
							var tempZoneProductionData=null;
						}
					}
				}
				newdiv=null;divZoneInfo=null;
			}
			divZone=null;
		}
		if(DEVMODE_FUNCTION){GM_log("End doZone "+zoneNr);}
	}catch(err){GM_log("ERROR doZone zoneNr:"+zoneNr+"\n"+err);}
	}

	unsafeWindow._updateZone=unsafeWindow.updateZone;
	unsafeWindow.updateZone = function(position,buildingid,level,empty,animals,status){
		//GM_log("updateZone "+position+":"+buildingid+":"+level+":"+empty+":"+animals+":"+status);
		unsafeWindow._updateZone(position,buildingid,level,empty,animals,status);
		doZone(parseInt(position,10));
	};

	// field
	function checkFieldTimes(){
		if(DEVMODE_FUNCTION) GM_log("Begin checkFieldTimes");
		var zoneNr=parseInt(/parent.cache_me\((\d+?),120/.exec($("gardenarea").innerHTML)[1],10);
		var zoneNrF=zoneNr+6*gameLocation[1];
		var newData=[[{},{}],[,0,0,,0],[,0,0,,0],true];

		// save garden-informations
		var helpArray=new Array();//planted fields
		var helpArray2=new Array();//empty fields
		var z,p,w;
		for(var v=1;v<=120;v++){
			z=parseInt(unsafeWindow.garten_zeit[v],10);
			p=unsafeWindow.garten_prod[v];
			switch(unsafeWindow.garten_kategorie[v]){
			case "v":{ // plants
				helpArray[v]=true;
				helpArray2[v]=false;
				if (z>0){
					if ((unsafeWindow.garten_x[v]==1)&&(unsafeWindow.garten_y[v]==1)){ // only first part of a plant
						w=parseInt(unsafeWindow.garten_wasser[v],10)+86400;
						w=((w==86400)?1:(w<z?w:NEVER)); // watertime
						if(!newData[0][0][p]){ newData[0][0][p]=new Array(); }
						var notfound=true;
						for(var i=0;i<newData[0][0][p].length;i++){
							if(notfound&&(newData[0][0][p][i][1]==z)&&(newData[0][0][p][i][2]==w)){
								newData[0][0][p][i][0]++;
								notfound=false;
							}
						}
						if(notfound){ newData[0][0][p].push([1,z,w]); }
					}
					// only show one sprinkler
					if ((unsafeWindow.garten_x[v]==2)||(unsafeWindow.garten_y[v]!=unsafeWindow.garten_max_y[v])){
						if ($("w"+v).style.display!="none") $("w"+v).style.display="none";
					}else{
						if ($("w"+v).style.display!="") $("w"+v).style.display="";
					}
				}else{
					helpArray[v]=true;
					helpArray2[v]=true;
				}
			break;}
			case "z":{ // decorations
				helpArray[v]=false;
				helpArray2[v]=false;
				if ((unsafeWindow.garten_x[v]==1)&&(unsafeWindow.garten_y[v]==1)){ // only first part
					if(!newData[0][0][p]){ newData[0][0][p]=new Array(); }
					var notfound=true;
					for(var i=0;i<newData[0][0][p].length;i++){
						if(notfound&&(newData[0][0][p][i][1]==z)){
							newData[0][0][p][i][0]++;
							notfound=false;
						}
					}
					if(notfound){ newData[0][0][p].push([1,z]); }
				}
			break;}
			case "u":{ // garbage
				helpArray[v]=false;
				helpArray2[v]=false;
				if(!newData[0][0][p]){ newData[0][0][p]=1; }
				else{ newData[0][0][p]++; }
			break;}
			default:{ // empty fields , p==0
				helpArray[v]=true;
				helpArray2[v]=true;
			break;}
			}
		}
		// calculate current space
		for(var v=1;v<helpArray2.length;v++){
			if(helpArray2[v]){ newData[1][1]++; }
		}
		var help=helpArray2.clone();
		for(var v=1;v<help.length;v++){
			if((v%12!=0)&&help[v]&&help[v+1]){
				help[v+1]=false;
				newData[1][2]++;
			}
		}
		var help=helpArray2.clone();
		for(var v=1;v<help.length;v++){
			if((v%12!=0)&&help[v]&&help[v+1]&&help[v+12]&&help[v+13]){
				help[v+1]=false;
				help[v+12]=false;
				help[v+13]=false;
				newData[1][4]++;
			}
		}
		// calculate possible space
		for(var v=1;v<helpArray.length;v++){
			if(helpArray[v]){ newData[2][1]++; }
		}
		var help=helpArray.clone();
		for(var v=1;v<help.length;v++){
			if((v%12!=0)&&help[v]&&help[v+1]){
				help[v+1]=false;
				newData[2][2]++;
			}
		}
		var help=helpArray.clone();
		for(var v=1;v<help.length;v++){
			if((v%12!=0)&&help[v]&&help[v+1]&&help[v+12]&&help[v+13]){
				help[v+1]=false;
				help[v+12]=false;
				help[v+13]=false;
				newData[2][4]++;
			}
		}
		zoneProductionData[zoneNrF]=newData.clone();
		newData=null;
		if(DEVMODE){ GM_log("zoneProductionData["+zoneNrF+"]= "+ implode(zoneProductionData[zoneNrF])); }

		// calculate garden-informations
		processZoneProductionData(zoneNrF);
		// auto-watering
		if((top.unsafeData.autoAction==null)&&valAutoWater["farm"] && (zoneWaterTimes[zoneNrF]<unsafeWindow.Zeit.Server) && (lastGiess!=zoneNrF) && $("tooltipwaterall") && $("waterall")){
			top.unsafeData.autoAction="berater: field water";
			lastGiess=zoneNrF;
			window.setTimeout(function(div){
				click(div);
				top.unsafeData.autoAction=null;
			},500,$("waterall").firstElementChild);
		}
		//auto-cropping
		if((top.unsafeData.autoAction==null)&&valAutoCrop["farm"] && (zoneEndTimes[zoneNrF]<unsafeWindow.Zeit.Server) && (lastErnte!=zoneNrF) && $("tooltipcropall") && $("cropall")){
			top.unsafeData.autoAction="berater: field crop";
			lastErnte=zoneNrF;
			window.setTimeout(function(div){
				click(div);
				top.unsafeData.autoAction=null;
			},500,$("cropall").firstElementChild);
		}
		// update zone-icons
		doZone(zoneNr);
		// show croppings of this field
		var cell=$("currentFieldZoneErnte");
		var newdiv;
		if(cell){ cell.innerHTML=""; }
		else{ cell=createElement("div",{"id":"currentFieldZoneErnte","style":"position:absolute;top:40px;left:0;","class":"blackbox"},$("gardenmaincontainer")); }
		for(var k=0;k<zoneErnte[zoneNrF].length;k++){
			newdiv=createElement("div",{"style":"height:15px"},cell);
			produktPic(zoneErnte[zoneNrF][k][0],zoneErnte[zoneNrF][k][1],newdiv);
			createElement("span",{},newdiv,numberFormat(zoneErnte[zoneNrF][k][2])+"&nbsp;"+prodName[zoneErnte[zoneNrF][k][0]][zoneErnte[zoneNrF][k][1]]);
		}
		cell=null;newdiv=null;
		if(DEVMODE_FUNCTION){GM_log("End checkFieldTimes");}
	}
	document.addEventListener("gameFieldModified",checkFieldTimes,false);

	unsafeWindow._getGardenInfoResponse=unsafeWindow.getGardenInfoResponse;
	unsafeWindow.getGardenInfoResponse = function(request,position){
		unsafeWindow._getGardenInfoResponse(request,position);
		if((request.readyState==4)&&(request.status==200)){
			response = request.responseText;
			if(response!=0){
				// GM_log("getGardenInfoResponse position="+position+"\n"+print_r(eval('('+response+')'),"",true,"\n"));
				//waterlog GM_log("getGardenInfoResponse position="+position+"\nwater: "+print_r(eval('('+response+')')["water"],"",true,"\n"));
				var zoneNr=parseInt(position,10);
				var zoneNrF=zoneNr+6*gameLocation[1];
				//GM_log("event: gameOpenField "+zoneNrF);
				//Log(unsafeWindow.gartenshortinfo);
				if (!$("divErnteInfo")){ createElement("div",{"id":"divErnteInfo"},$("gardenmaincontainer")); }
				drawZoneNavi(zoneNrF,$("gardenmaincontainer"));
				doLagerZeit(zoneNr);
		
				//Klon des Anpflanzautomaten
				/*
				var newdiv;
				if($("gardencancel").childElementCount==1 && $("autoplantbutton"+zoneNr)){
					newdiv=$("autoplantbutton"+zoneNr).parentNode.cloneNode(true);
					newdiv.addEventListener("click",function(){$("gardenmaincontainer").setAttribute("style","display:none");},false);
					$("gardencancel").appendChild(newdiv);
				}
				newdiv=null;
				*/
				raiseEvent("gameOpenField");
				raiseEvent("gameFieldModified");
			}
		}
	};
	/*
	unsafeWindow._getGardenInfoProcessResponse=unsafeWindow.getGardenInfoProcessResponse;
	unsafeWindow.getGardenInfoProcessResponse = function getGardenInfoProcessResponse(request,position){
		unsafeWindow._getGardenInfoProcessResponse(request,position);
		if((request.readyState==4)&&(request.status==200)){
			GM_log("getGardenInfoProcessResponse "+position);
		}
	};
	*/
	unsafeWindow._PflanzResponse=unsafeWindow.PflanzResponse;
	unsafeWindow.PflanzResponse = function(request){
		unsafeWindow._PflanzResponse(request);
		if((request.readyState==4)&&(request.status==200)){
			//GM_log("PflanzResponse");
			raiseEvent("gameFieldModified");
		}
	};
	unsafeWindow._WasserResponse=unsafeWindow.WasserResponse;
	unsafeWindow.WasserResponse = function(request){
		unsafeWindow._WasserResponse(request);
		if((request.readyState==4)&&(request.status==200)){
			//GM_log("WasserResponse");
			raiseEvent("gameFieldModified");
		}
	};
	unsafeWindow._ErnteResponse=unsafeWindow.ErnteResponse;
	unsafeWindow.ErnteResponse = function(request){
		unsafeWindow._ErnteResponse(request);
		if((request.readyState==4)&&(request.status==200)){
			//GM_log("ErnteResponse");
			raiseEvent("gameFieldModified");
		}
	};
	unsafeWindow._AbrissResponse=unsafeWindow.AbrissResponse;
	unsafeWindow.AbrissResponse = function(request){
		unsafeWindow._AbrissResponse(request);
		if((request.readyState==4)&&(request.status==200)){
			//GM_log("AbrissResponse");
			raiseEvent("gameFieldDemolish");
			raiseEvent("gameFieldModified");
		}
	};

	$("gardenmaincontainer").addEventListener ("DOMAttrModified", function(event){
		if(this==event.target){
			//GM_log("gardenmaincontainer DOMAttrModified "+event.target.id+":"+event.attrName+":"+event.newValue);
			if(this.style.display!="block"){
				lastGiess=null;
				lastErnte=null;
				if ($("divErnteInfo")) removeElement($("divErnteInfo"));
				if ($("zoneNavi")) removeElement($("zoneNavi"));
				//if ($("lager_zeit_ziel").parentNode.style.display == "") $("lager_zeit_ziel").parentNode.style.display="none";
			}
		}
	},false);

	unsafeWindow._errorboxgarden=unsafeWindow.errorboxgarden;
	unsafeWindow.errorboxgarden = function(text,onclick){
		unsafeWindow._errorboxgarden(text,onclick);
		// Fix(Seberoth)
		// $("divErnteInfo").innerHTML=$("errorboxcontentgarden").innerHTML;
		$("divErnteInfo").innerHTML=document.getElementsByClassName('cropall_dialog_product')[0].innerHTML;
		$("divErnteInfo").style.display="block";
		if (valErnteMsg){
			// Fix(Seberoth)
			// $("errorboxgarden").style.display="none"; 
			$("globalbox").style.display="none";
			$("globaltransp").style.display="none";
		}
		// Fix(Seberoth)
		// var zoneNr=/refreshGarden\((\d)\)/.exec($("errorboxfootergarden").parentNode.innerHTML);
		var zoneNr=/refreshGarden\((\d)\)/.exec($("globalbox_button1").parentNode.innerHTML);
		if(zoneNr){
			zoneNr=zoneNr[1];
			unsafeWindow.refreshGarden(zoneNr);
		}
	};

	$("commitbox").addEventListener ("DOMAttrModified", function(event){
		if(this==event.target){
			if(this.style.display!="none"){
				if ($("autoplantproduct")){ // Anpflanzautomat vordefinieren
					if (!aktivAutomat && (unsafeWindow.kategorie=="v")){ $("autoplantproduct").value=unsafeWindow.selected; }
					aktivAutomat=true;
				}
			}else{ aktivAutomat=false; }
		}
	},false);

	// Farmhouse
	unsafeWindow._initFarmhouseResponse=unsafeWindow.initFarmhouseResponse;
	unsafeWindow.initFarmhouseResponse = function(request){
		unsafeWindow._initFarmhouseResponse(request);
		var result=checkRequest(request);
		if(result&&result[0]!=0){
		if(unsafeWindow.reallocatebuildinghead&&!$("reallocatebuildingbutton")){
			var newdiv=createElement("div",{"onclick":"initReallocateBuilding();showDiv('transp');","style":"position:absolute;top:70px;right:20px;","class":"link"},$("farmhousecontainer"));
			createElement("img",{"id":"reallocatebuildingbutton","onmouseout":"this.src=_GFX+'reallocatebuildingbutton_off.png';hideDiv('reallocatebuildinginfo');","onmouseover":"this.src=_GFX+'reallocatebuildingbutton_on.png';showDiv('reallocatebuildinginfo');","src":GFX+"reallocatebuildingbutton_off.png","class":"link","style":"width:25px;height:25px;"},newdiv);
			createElement("div",{"id":"reallocatebuildinginfo","style":"display:none;position:absolute;top:70px;right:50px;","class":"blackbox"},$("farmhousecontainer"),unsafeWindow.reallocatebuildinghead);
			newdiv=null;
		}
		}
	};
	unsafeWindow._feedAnimalResponse=unsafeWindow.feedAnimalResponse;
	unsafeWindow.feedAnimalResponse = function(request,position,product,amount){
		try{
			unsafeWindow._feedAnimalResponse(request,position,product,amount);
		}catch(err){GM_log("ERROR _feedAnimalResponse\n"+err);}
		try{
		var result=checkRequest(request);
		if(result&&result[0]!=0){
			doZone(position); // update production-data
			showBlase(parseInt(position,10)+(6*gameLocation[1])); // update the shown producing time
		}
		}catch(err){GM_log("ERROR feedAnimalResponse\n"+err);}
	};
	// stable and factory
	function doStable(){
	try{
		// GM_log("doStable "+unsafeWindow.currentposition);
		// TODO(Seberoth): Waypoint
		// var zoneNr=parseInt($("innermaincontainer").firstElementChild.firstElementChild.id.replace("button_cancel",""),10);
		var zoneNr=unsafeWindow.currentposition; // parseInt($("animal_line").children[0].id.split("_")[2],10);
		var zoneNrF=zoneNr+6*gameLocation[1];
		showBlase(zoneNrF);
		$("sprcontent2").addEventListener("DOMAttrModified",function(event){
			if(this==event.target){
				if($("innermaincontainer").style.display=="block"){
					if(this.style.display!=""){
						var zoneNr=parseInt($("innermaincontainer").firstElementChild.firstElementChild.id.replace("button_cancel",""),10);
						showBlase(zoneNr+(6*gameLocation[1]));
					}
				}else{
					removeEventListener("DOMAttrModified",arguments.callee,false);
				}
			}
		},false);
		drawZoneNavi(zoneNrF,$("building_inner"));
		var cand,newdiv;
		cand=$("innercontent").getElementsByClassName("feedproduct");
		for(var v=0;v<cand.length;v++){
			var currProd=parseInt(cand[v].getElementsByTagName("div")[1].getAttribute("class").replace("l",""),10);
			var str="blackbox"+(prodStock[0][currProd]<prodMinRack[0][currProd]?" lowrack":"");
			newdiv=$(cand[v].id+"_rackamount");
			if(!newdiv){
				newdiv=createElement("div",{"id":cand[v].id+"_rackamount","style":"position:absolute;top:-25px;left:-2px;font-weight:bold;"},cand[v]);
			}
			if(newdiv.getAttribute("class")!=str){ newdiv.setAttribute("class",str); }
			newdiv.innerHTML=numberFormat(prodStock[0][currProd],0,"","").replace(/(\d{3,})(\d{3})/,"$1k").replace(/(\d+)(\d{3})/g,"$1"+delimThou+"$2");
		}
		if (valAutoCrop["farm"]&&(div=$("commitboxcrop"))&&(div.style.display=="block")&&(div=$("commitboxfootercrop"))){
			window.setTimeout(function(div){ click(div); },500,div.firstElementChild);
		}

		for(var v=0;v<animalMove.length;v++){ if((valMoveAnimals[v])&&(!animalMove[v][0])&&($("animalline"+v))){
			animalMove[v][0]=true;
			moveAnimals(v);
			break;
		}}
		cand=null;newdiv=null;
		raiseEvent("gameOpenStable");
	}catch(err){GM_log("ERROR doStable\n"+err);}		
	}
	$("commitboxinner").addEventListener ("DOMAttrModified", function(event){
	try{
		if ((this==event.target)&&(this.style.display == "block")){
			if (!$("feedMax")){
				var cand=createElement("a",{"id":"feedMax","class":"link","style":"font-weight:bold;"});
				cand.innerHTML="max";
				$("commitboxcontentinner").firstElementChild.insertBefore(cand,$("feedamount").nextSibling);
				cand.addEventListener("click",function(){$("feedamount").value=216;keyup($("feedamount"));},false);
				cand=null;
			}
		}
	}catch(err){GM_log("ERROR listener commitboxinner.DOMAttrModified\n"+err);}
	},false);
	function doFactory(){
		//GM_log("doFactory "+unsafeWindow.currentposition);
		var zoneNr=parseInt($("innermaincontainer").firstElementChild.firstElementChild.id.replace("button_cancel",""),10);
		var zoneNrF=zoneNr+6*gameLocation[1];
		showBlase(zoneNrF);
		$("sprcontent2").addEventListener("DOMAttrModified",function(event){
			if(this==event.target){
				if($("innermaincontainer").style.display=="block"){
					if(this.style.display!=""){
						var zoneNr=parseInt($("innermaincontainer").firstElementChild.firstElementChild.id.replace("button_cancel",""),10);
						showBlase(zoneNr+(6*gameLocation[1]));
					}
				}else{
					removeEventListener("DOMAttrModified",arguments.callee,false);
				}
			}
		},false);
		drawZoneNavi(zoneNrF,$("innermaincontainer"));
		var cand,newdiv;
		if(!$("articleline"+unsafeWindow.locationinfo[6])){
			cand=createElement("div",{"id":"articleline"+unsafeWindow.locationinfo[6]},$("innercontent"));
     		for(var prodNr=0;prodNr<unsafeWindow.locationinfo["in"].length;prodNr++){
				newdiv=createElement("div",{"id":(gameLocation[1]+1)+"_"+zoneNr+"_article"+unsafeWindow.locationinfo["in"][prodNr],"class":"feedproduct","style":"position:absolute;top:54px;left:"+(55+60*prodNr)+"px;border:2px solid black;z-index:11;","prodNr":prodNr},cand);
				createElement("div",{"id":"articleimg"+unsafeWindow.locationinfo["in"][prodNr],"style":"position:absolute;","class":"l"+unsafeWindow.locationinfo["in"][prodNr]},createElement("div",{"style":"position:absolute;top:5px;left:5px;width:40px;height:40px;overflow:hidden;"},newdiv));
				newdiv.addEventListener("mouseover",function(event){ 
					var prodNr = parseInt(this.getAttribute("prodNr"),10);
					showToolTip(event,unsafeWindow.locationinfo["need"][prodNr]+"x "+prodName[0][unsafeWindow.locationinfo["in"][prodNr]]);
				},false);
			}
		}

		var cand=$("innercontent").getElementsByClassName("feedproduct");
		for(var v=0;v<cand.length;v++){
			var currProd=parseInt(cand[v].getElementsByTagName("div")[1].getAttribute("class").replace("l",""),10);
			var str="blackbox"+(prodStock[0][currProd]<prodMinRack[0][currProd]?" lowrack":"");
			if(!$(cand[v].id+"_rackamount")){ createElement("div",{"id":cand[v].id+"_rackamount","style":"position:absolute;top:-25px;left:-2px;font-weight:bold;"},cand[v]); }
			newdiv=$(cand[v].id+"_rackamount");
			if(newdiv.getAttribute("class")!=str){ newdiv.setAttribute("class",str); }
			newdiv.innerHTML=numberFormat(prodStock[0][currProd],0,"","").replace(/(\d{3,})(\d{3})/,"$1k").replace(/(\d+)(\d{3})/g,"$1"+delimThou+"$2");
		}
		if (valAutoCrop["farm"]&&(div=$("commitboxcrop"))&&(div.style.display=="block")&&(div=$("commitboxfootercrop"))){
			window.setTimeout(function(div){ click(div); },500,div.firstElementChild);
		}
		cand=null;newdiv=null;
		raiseEvent("gameOpenFactory");
	}
	function doFactoryOil(){
		//GM_log("doFactoryOil "+unsafeWindow.currentposition);
		var zoneNr=parseInt($("cancelscreen").firstElementChild.id.replace("button_cancel",""),10);
		var zoneNrF=zoneNr+6*gameLocation[1];
		showBlase(zoneNrF);
		drawZoneNavi(zoneNrF,$("innermaincontainer"));
		// createElement("div",{"style":"position:absolute;bottom:0;right:0;width:300px;height:450px;overflow:scroll;z-index:50;background:white;"},$("innermaincontainer"),print_r(unsafeWindow.locationinfo));
		// createElement("div",{"style":"position:absolute;bottom:0;right:0;width:300px;height:450px;overflow:scroll;z-index:50;background:white;"},$("innermaincontainer"),print_r(unsafeWindow.oilproduction));
		raiseEvent("gameOpenFactoryOil");
	}
	
	unsafeWindow._buildOilpressInner=unsafeWindow.buildOilpressInner;
	unsafeWindow.buildOilpressInner = function(position,buildingid,info){
		unsafeWindow._buildOilpressInner(position,buildingid,info);
		var zoneNr=position;
		var zoneNrF=zoneNr+6*gameLocation[1];
		var newDiv,newDiv1;
		var tempZoneProductionData=[[{},{}],0,0,true];
		var tempZoneProductionDataSlot;
		for(var slot=1;slot<=3;slot++){
			if((slot==1)||(!unsafeWindow.oilslots[slot]["block"])){
				zoneBlock[zoneNrF+"."+slot]="";
				tempZoneProductionDataSlot=[[{},{}],0,0,true];
				tempZoneProductionData[1]++;
				tempZoneProductionData[2]++;
				tempZoneProductionDataSlot[1]++;
				tempZoneProductionDataSlot[2]++;
				if(unsafeWindow.oilproduction[slot]){
					var iPrTyp=0;
					var iProd=unsafeWindow.oilproduction[slot]["pid"];
					var iTime=now+unsafeWindow.oilproduction[slot]["remain"];
					var endDay=countDays(now,iTime);
					newDiv=createElement("div",{"class":"blackbox","id":"oil_slot"+slot+"_prodinfo","style":"position:absolute;left:105px;top:0;white-space:nowrap;"},$("oil_slot"+slot));
					if(iTime<now){
						if(iTime+20*60*60<now){
							createElement("div",{},newDiv,texte["fertigSeitX"].replace(/%1%/,getFormattedDateStr(iTime)));
						}else{
							createElement("div",{},newDiv,texte["fertigSeitX"].replace(/%1%/,getDaytimeStr(iTime)+"&nbsp;"+texte["uhr"]));
						}				
					} else if (endDay==0){
						createElement("div",{},newDiv,texte["readyAtX"].replace(/%1%/,getDaytimeStr(iTime)+"&nbsp;"+texte["uhr"]));
					} else if ((endDay==1)&&(texte["readyAtX_day1"])){
						createElement("div",{},newDiv,texte["readyAtX_day1"].replace(/%1%/,getDaytimeStr(iTime)+"&nbsp;"+texte["uhr"]));
					} else if ((endDay==2)&&(texte["readyAtX_day2"])){
						createElement("div",{},newDiv,texte["readyAtX_day2"].replace(/%1%/,getDaytimeStr(iTime)+"&nbsp;"+texte["uhr"]));
					} else{ 
						createElement("div",{},newDiv,texte["readyAtX"].replace(/%1%/,new Date(1000*iTime).toLocaleString())); 
					}
					newDiv1=$("oil_slot"+slot+"_img_tt_time");
					if(newDiv1){ newDiv.appendChild(newDiv1); }
					newDiv1=createElement("div",{},newDiv); 
					produktPic(iPrTyp,iProd,newDiv1);
					createElement("span",{},newDiv1,numberFormat(unsafeWindow.oilproduction[slot]["amount"])+" "+prodName[iPrTyp][iProd]); 
					pointsFormat(unsafeWindow.oilproduction[slot]["amount"]*prodPoints[iPrTyp][iProd],"div",newDiv1);
		
					iTime-=unsafeWindow.Zeit.Verschiebung;
					tempZoneProductionData[1]--;
					if(!tempZoneProductionData[0][iPrTyp][iProd]){ tempZoneProductionData[0][iPrTyp][iProd]=[]; }
					tempZoneProductionData[0][iPrTyp][iProd].push([1,iTime,NEVER]);
					tempZoneProductionDataSlot[1]--;
					if(!tempZoneProductionDataSlot[0][iPrTyp][iProd]){ tempZoneProductionDataSlot[0][iPrTyp][iProd]=[]; }
					tempZoneProductionDataSlot[0][iPrTyp][iProd].push([1,iTime,NEVER]);
					//auto-cropping
					if((top.unsafeData.autoAction==null)&&valAutoCrop["farm"] && (newDiv=$("oil_slot"+slot+"_cropbutton")) && (newDiv.style.display=="block")){
						top.unsafeData.autoAction="berater: oil crop";
						window.setTimeout(function(div){
							click(div);
							top.unsafeData.autoAction=null;
						},500,newDiv);
					}
				}
				zoneProductionData[zoneNrF+"."+slot]=tempZoneProductionDataSlot.clone();
				processZoneProductionData(zoneNrF+"."+slot);
			} else {
				zoneBlock[zoneNrF+"."+slot]="b";
			}
		}
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock,"buildOilpressInner\zoneBlock"));
		zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
		processZoneProductionData(zoneNrF);
		var tempZoneProductionData=null;newDiv=null;newDiv1=null;
	};
	unsafeWindow._innerInfosResponse=unsafeWindow.innerInfosResponse;
	unsafeWindow.innerInfosResponse = function(request,position){
		unsafeWindow._innerInfosResponse(request,position);
		if(checkRequest(request)){
			if($("innermaincontainer").style.display == "block"){
				if(unsafeWindow.locationinfo["buildingid"]){ doFactoryOil(); }
				else if(unsafeWindow.locationinfo["in"]){ doFactory(); }
				else{ doStable(); }
			}
		}
	};
	unsafeWindow._buildingInnerActionResponse=unsafeWindow.buildingInnerActionResponse;
	unsafeWindow.buildingInnerActionResponse = function(request,action,farm,position){
		unsafeWindow._buildingInnerActionResponse(request,action,farm,position);
		if(checkRequest(request)){
			if($("building_inner").style.display == "block"){
				if(unsafeWindow.locationinfo["buildingid"]){ doFactoryOil(); }
				else if(unsafeWindow.locationinfo["in"]){ doFactory(); }
				else{ doStable(); }
			}
		}
	};
	// Club
	err_trace="Club";
	// Clubquest direct show
	var lastGuildQuestRequest=0;
	function clubQuestToolTip(data){
	try{
		var container=$("guildlink_tt_quest");
		container.innerHTML="";
		var newdiv=createElement("div",{"style":"position:absolute;top:5px;left:5px;"},container);
		var newspan=createElement("span",{"style":"margin-right:2px;"},newdiv);
		if(data!=0){
			createElement("img",{"src":GFX+'adtime.gif'},newspan);
			createElement("span",{"style":"font-weight:bold;"},newdiv,getTimeStr(data['remain']));
			if(data['questtype'] == 1 || data['questtype'] == 2){  // produkte oder geld in vorgegebener zeit
				var top=25;
				var left=0;
				var newdiv1;
				for(var i=1 ; i <= 2 ; i++){
					if(data['product' + i] > 0){
						data['sum' + i]=parseInt(data['sum' + i],10);
						data['amount' + i]=parseInt(data['amount' + i],10);
						var barleft=parseInt(Math.round((data['sum' + i] * 100) / data['amount' + i])-100,10);

						if(data['questtype'] == 2){
							data['sum' + i]=moneyFormat(data['sum' + i]);
							data['amount' + i]=moneyFormat(data['amount' + i]);
						}

						newdiv=createElement("div",{"style":'position:absolute; top:' + top + 'px; left:' + left + 'px;width:40px;height:15px;'},container);
						if(data['questtype'] == 1){
							newdiv1=createElement("div",{"style":"position:absolute; top:0; left:5px;height:15px;width:15px; overflow:hidden;"},newdiv);
							createElement("img",{"class":"kp" + data['product' + i], "style":"position:absolute;"},newdiv1);
						}
						else if(data['questtype'] == 2){
							newdiv1=createElement("div",{"style":"position:absolute; top:0; left:5px;height:15px;width:15px;"},newdiv);
							createElement("img",{"src":GFX+"money.gif","height":"15","width":"15"},newdiv1);
						}
						newdiv1=createElement("div",{"style":"position:absolute;top:0;left:23px;border:1px solid #000;background-color:#fff;width:100px;height:15px;overflow:hidden;"},newdiv);
						createElement("div",{"style":"position:absolute;top:0;left:"+barleft+"px;background-color:#f00;width:100px;height:25px;"},newdiv1);
						createElement("div",{"style":"position:absolute;top:0;left:0;width:100px;height:15px;color:black;font-weight:bold;text-align:center;"},newdiv1,numberFormat(data['sum' + i]));
						createElement("div",{"style":"position:absolute;top:20px;white-space:nowrap;left:5px;"},newdiv,(data['amount' + i]==data['sum' + i])?"":('<b>' + numberFormat(data['amount' + i]-data['sum' + i]) + '/' + numberFormat(data['amount' + i]) + '</b>'));
				top += 40;
				}	}
				newdiv1=null;
			}
		}else{
			newspan.innerHTML="---";
		}
		container=null;newdiv=null;newspan=null;
	}catch(err){GM_log("ERROR clubQuestToolTip\ndata="+implode(data)+"\n"+err);}
	}
	if((newdiv=$("speedlink_guild"))&&(newdiv1=$("speedlink_guild_tt"))){
		var str=newdiv1.innerHTML;
		newdiv1.innerHTML="";
		createElement("div",{"style":"border-bottom:1px solid white;"},newdiv1,str);
		createElement("div",{"id":"guildlink_tt_quest","style":"position:relative;width:130px;height:100px;"},newdiv1,"---");
		newdiv.addEventListener("mouseover",function(){
			if (now-lastGuildQuestRequest>30){ // 30 seconds delay to next request
				lastGuildQuestRequest=now;
				GM_xmlhttpRequest({
					method: "GET",
					url: "http://s"+SERVER+"."+GAMEPAGES[LNG]+"/guild/ajax/initguild.php?rid="+unsafeWindow.rid,
					headers: {"Content-type": "application/x-www-form-urlencoded"},
					onload: function(response){
						if(response.responseText!=0){
							var result=eval('(' + response.responseText + ')');
							if(result[0]!=0){
								clubQuestToolTip(result[0][2]);
							}
						}
					}
				});
			}
		},false);
	}

	// Clubquest updated
	unsafeWindow._setGuildQuestResponse=unsafeWindow.setGuildQuestResponse;
	unsafeWindow.setGuildQuestResponse = function(request){
		unsafeWindow._setGuildQuestResponse(request);
		var result=checkRequest(request);
		if(result){
			lastGuildQuestRequest=now;
			clubQuestToolTip(result[1]);
		}
	};

	// Clubdata loaded
	unsafeWindow._initGuildResponse=unsafeWindow.initGuildResponse;
	unsafeWindow.initGuildResponse = function(request){
		unsafeWindow._initGuildResponse(request);
		var result=checkRequest(request);
		if(result){
			lastGuildQuestRequest=now;
			clubQuestToolTip(result[0][2]);
		}
	};

	// Memberlist
	unsafeWindow._openMultiBox=unsafeWindow.openMultiBox;
	unsafeWindow.openMultiBox = function(id){
		if(id==5){
			$('guildmultiboxheader').innerHTML='<img class="link" src="' + unsafeWindow.imgpath + 'button_cancel_off.png" onclick="hideDiv(\'transp9\'); hideDiv(\'guildmultibox\');" onmouseover="this.src=\'' + unsafeWindow.imgpath + 'button_cancel_on.png\';" onmouseout="this.src=\'' + unsafeWindow.imgpath + 'button_cancel_off.png\';"></div>';
			$('guildmultiboxcontent').innerHTML='';
			unsafeWindow.showGuildQuestStats(2,1,0);
			for(var i=1;i<=3;i++){
				$('guildmultiboxmenue'+i).style.backgroundImage="url(" + unsafeWindow.imgpath + "leer.gif)";
			}
			$('guildmultiboxmenue4').style.backgroundImage="url(" + unsafeWindow.imgpath + "multiscreen_reiter4.jpg)";
			$('guildmultiboxheadline').innerHTML=unsafeWindow.guildmultibox_headline4;
			unsafeWindow.hideDiv('guildnewsticker');
			unsafeWindow.showDiv('transp9');
			unsafeWindow.showDiv('guildmultibox');
		}else{
			unsafeWindow._openMultiBox(id);
		}
	};
	$("guildmultiboxmenue4").setAttribute("onclick","openMultiBox(5)");

	unsafeWindow._getGuildMembersResponse=unsafeWindow.getGuildMembersResponse;
	unsafeWindow.getGuildMembersResponse = function(request){
		unsafeWindow._getGuildMembersResponse(request);
		if(request.readyState == 4 && request.status == 200){
			var canddiv=Array.prototype.slice.call($("guildmultiboxcontent").getElementsByClassName("guildmemberlist_even")).concat(Array.prototype.slice.call($("guildmultiboxcontent").getElementsByClassName("guildmemberlist_uneven")));
			var newdiv,newspan,newa;
			for(var v=0;v<canddiv.length;v++){
				newdiv=canddiv[v].children[1].firstElementChild;
				var thisUser=/(.*?)&nbsp;/.exec(newdiv.innerHTML);
				newdiv.innerHTML=newdiv.innerHTML.replace(thisUser[0],"");
				newspan=createElement("span");
				newspan.innerHTML="&nbsp;";
				newdiv.insertBefore(newspan,newdiv.firstElementChild);
				newa=createElement("a",{"class":"link2"});
				newa.innerHTML=thisUser[1];
				newdiv.insertBefore(newa,newdiv.firstElementChild);
				newa.addEventListener("click",function(){
					showShopframePage("http://s"+SERVER+"."+GAMEPAGES[LNG]+"/stadt/stats.php?search=1&searchterm="+this.innerHTML);
				},false);
				//newdiv.insertBefore(igm(thisUser[1]),newdiv.firstElementChild);
			}
			newdiv=null;newspan=null;newa=null;canddiv=null;
		}
	};
	// Questhistory
	unsafeWindow._showGuildQuestStatsResponse=unsafeWindow.showGuildQuestStatsResponse;
	unsafeWindow.showGuildQuestStatsResponse = function(request,type,page,self){
		unsafeWindow._showGuildQuestStatsResponse(request,type,page,self);
		var result=checkRequest(request);
		if(result&&result[0]!=0){
			window.setTimeout(function(){
				if(DEVMODE){ GM_log("showGuildQuestStatsResponse "+request+":"+type+"("+typeof type+"):"+page+"("+typeof page+"):"+self+"("+typeof self+")"); };

				var newdiv=$("chg_guildqueststats");
				newdiv.setAttribute("onchange","");
				newdiv.addEventListener("change",function(){
					var type=parseInt($("chg_guildqueststats").value,10);
					if(type<4){
						unsafeWindow.showGuildQuestStats(type,1,0);
					}else{
						showGuildQuestStatsLastDays(7);
					}
				},false);
				createElement("option",{"value":"4"},newdiv,texte["stat_days7"]);
				if(type>3){
					newdiv.value=type;
					newdiv.nextElementSibling.style.display="none";
				}

				//todayStr=getDateStr(now,2,false);
				var clubmemberLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_clubmemberLog","{}"),"showGuildQuestStatsResponse/clubmemberLog",{});
				for(var u in clubmemberLog){
					if(!clubmemberLog.hasOwnProperty(u)){ continue; }
					for(var v in clubmemberLog[u]){
						if(!clubmemberLog[u].hasOwnProperty(v)){ continue; }
						if(v=="0"){ continue; }
						// join old data
						var w=null;
						if(v.match(/^\d+\.\d+\.\d+$/)){
							if(now-getTime(v)>604800){ // 1 week (7*86400)
								w=v.replace(/^(\d+\.)/,"");
							}
						}else if(v.match(/^\d+\.\d+$/)){
							if(now-getTime(v)>16070400){ // 6 months (6*31*86400)
								w=v.replace(/^(\d+\.)/,"");
							}
						}
						if(w!=null){
							if(clubmemberLog[u][w]==undefined){
								clubmemberLog[u][w]=[0,{}];
								clubmemberLog[u].sortObj(sortObjFunctions["date"]);
							}
							clubmemberLog[u][w][0] += clubmemberLog[u][v][0];
							for(var prod in clubmemberLog[u][v][1]){
								if(!clubmemberLog[u][v][1].hasOwnProperty(prod)){ continue; }
								if(clubmemberLog[u][w][1][prod]==undefined){
									clubmemberLog[u][w][1][prod]=0;
									clubmemberLog[u][w][1].sortObj(sortObjFunctions["productId"]);
								}
								clubmemberLog[u][w][1][prod] += clubmemberLog[u][v][1][prod];
							}
							delete clubmemberLog[u][v];
						}
					}
				}

				var clubmembers=new Object();
				var clubmemberLogSum=new Object();
				for(var u in clubmemberLog){
					if(!clubmemberLog.hasOwnProperty(u)){ continue; }
					clubmemberLogSum[u]=[0,{}];
					for(var v in clubmemberLog[u]){
						if(!clubmemberLog[u].hasOwnProperty(v)){ continue; }
						if(v==todayStr){ continue; }
						clubmemberLogSum[u][0] += clubmemberLog[u][v][0];
						for(var w in clubmemberLog[u][v][1]){
							if(!clubmemberLog[u][v][1].hasOwnProperty(w)){ continue; }
							if(clubmemberLogSum[u][1][w]==undefined){
								clubmemberLogSum[u][1][w]=0;
								clubmemberLogSum[u][1].sortObj(sortObjFunctions["productId"]);
							}
							clubmemberLogSum[u][1][w] += clubmemberLog[u][v][1][w];
						}
					}
				}
				var container=$("guildmultiboxcontent");
				var newtable,newtable1,newtr,newtr1,newtd,newdiv1,cell;
				for(var v=0;v<container.childElementCount;v++){
					if(container.children[v].id.match(/^line\d+$/)){
						var lineNr=parseInt(/^line(\d+)$/.exec(container.children[v].id)[1],10);

						var thisUser=container.children[v].children[1].innerHTML;
						var thisPoints=parseInt(container.children[v].children[3].innerHTML,10);
						container.children[v].children[3].innerHTML=numberFormat(thisPoints);

						clubmembers[thisUser]=[thisPoints,{}];

						// reformat of info bubble
						cell=$("bartt"+lineNr);
						cell.style.whiteSpace="nowrap";
						cell.style.left="";
						cell.style.right="30px";
						for(var w=0;w+1<cell.childElementCount;w++){
							if(cell.children[w].style.clear == "both"){ continue; }
							var help=parseInt(cell.children[w].getAttribute("class").replace(/kp/,""),10);
							var help1=parseInt(cell.children[++w].innerHTML.replace(/&nbsp;/g,""),10);
							clubmembers[thisUser][1][help]=help1;
						}
						cell.innerHTML="";

						clubmembers[thisUser][1].sortObj(sortObjFunctions["productId"]);

						newtable=createElement("table",{"cellspacing":"0","class":"white","style":"display:inline-block;vertical-align:top;"},cell);
						var c=2;
						for(var w in clubmembers[thisUser][1]){
							if(!clubmembers[thisUser][1].hasOwnProperty(w)){ continue; }
							if(c==2){
								c=0;
								newtr=createElement("tr",{},newtable);
							}
							c++;
							newtd=createElement("td",{"class":"link hoverBgDarkgreen","style":"text-align:right;padding-right:5px;","prod":w},newtr);
							newtd.addEventListener("mouseover",function(event){
								showGoToMarketToolTip(event,this.getAttribute("prod"));
							},false);
							newtd.addEventListener("click",function(){
								showMarket(this.getAttribute("prod"));
							},false);
							produktPic(0,w,newtd).style.cssFloat="left";
							createElement("span",{},newtd,numberFormat(clubmembers[thisUser][1][w]));
						}

						if(type==2){ // all quests
							if(clubmemberLog[thisUser]==undefined){
								clubmemberLog[thisUser]=new Object();
								clubmemberLog[thisUser]["0"]=clubmembers[thisUser];
								clubmemberLogSum[thisUser]=clubmembers[thisUser];
							}
							if(clubmemberLog[thisUser][todayStr]==undefined){
								clubmemberLog[thisUser][todayStr]=[0,{}];
								clubmemberLog[thisUser].sortObj(sortObjFunctions["date"]);
							}
							clubmemberLog[thisUser][todayStr][0]=thisPoints-clubmemberLogSum[thisUser][0];
							for(var w in clubmembers[thisUser][1]){
								if(!clubmembers[thisUser][1].hasOwnProperty(w)){ continue; }
								var help=clubmembers[thisUser][1][w]-(clubmemberLogSum[thisUser][1][w]==undefined?0:clubmemberLogSum[thisUser][1][w]);
								if(help>0){
									if(clubmemberLog[thisUser][todayStr][1][w]==undefined){
										clubmemberLog[thisUser][todayStr][1][w]=help;
										clubmemberLog[thisUser][todayStr][1].sortObj(sortObjFunctions["productId"]);
									}else{
										clubmemberLog[thisUser][todayStr][1][w]=help;
									}
								}
							}
						}

						newtable=createElement("table",{"cellspacing":"0","class":"white","style":"display:inline-block;margin-left:5px;vertical-align:top;"},cell);
						var sum=0;
						for(var w in clubmemberLog[thisUser]){
							if(!clubmemberLog[thisUser].hasOwnProperty(w)){ continue; }
							sum += clubmemberLog[thisUser][w][0];
							if(w=="0"){ continue; }
							newtr=createElement("tr",{"class":"hoverBgDarkgreen"});
							newtable.insertBefore(newtr,newtable.firstElementChild);
							newdiv=createElement("div");
								newtable1=createElement("table",{"cellspacing":"0","class":"white","style":"display:inline-block;vertical-align:top;"},newdiv);
								var c=2;
								//var pkte=0;
								for(var prod in clubmemberLog[thisUser][w][1]){
									if(!clubmemberLog[thisUser][w][1].hasOwnProperty(prod)){ continue; }
									if(c==2){
										c=0;
										newtr1=createElement("tr",{},newtable1);
									}
									newtd=createElement("td",{"style":"text-align:right;padding-right:5px;"},newtr1);
									c++;
									produktPic(0,prod,newtd).style.cssFloat="left";
									createElement("span",{},newtd,numberFormat(clubmemberLog[thisUser][w][1][prod]));
									//pkte += POINTS[0][prod]*clubmemberLog[thisUser][w][1][prod];
								}
								//createElement("div",{},newdiv,numberFormat(0.05*Math.round(pkte)));
							if(newtable1.childElementCount>0){
								newtr.setAttribute("mouseOverText",newdiv.innerHTML);
								newtr.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseOverText")); },false);
							}
							createElement("td",{"style":"text-align:right;padding-right:5px;border-left:1px solid white;"},newtr,w);
							createElement("td",{"style":"text-align:right;padding-right:5px;"},newtr,numberFormat(sum));
							createElement("td",{"style":"text-align:right;padding-right:5px;"},newtr,(clubmemberLog[thisUser][w][0]>0)?("+"+numberFormat(clubmemberLog[thisUser][w][0])):"");
						}
					}
				}
				cell=null;newtable=null;newtable1=null;newtr=null;newtr1=null;newtd=null;newdiv1=null;
				GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_clubmemberLog",implode(clubmemberLog));
				container=null;newdiv=null;
			},0);
		}
	};
	// New mode for questhistory
	function showGuildQuestStatsLastDays(days){
	//GM_log("showGuildQuestStatsLastDays "+days);
		//todayStr=getDateStr(now,2,false);
		var startDay=new Date();
		startDay=((new Date(startDay.getFullYear(),startDay.getMonth(),startDay.getDate()-days)).getTime())/1000;

		var obj=[0,[],0,1,0];
		var clubmemberLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_clubmemberLog","{}"),"showGuildQuestStatsLastDays/clubmemberLog",{});
		var clubmemberLogSum=new Object();
		for(var u in clubmemberLog){
			if(!clubmemberLog.hasOwnProperty(u)){ continue; }
			var p=0;
			var help=new Object();
			for(var v in clubmemberLog[u]){
				if(!clubmemberLog[u].hasOwnProperty(v)){ continue; }
				if(v=="0"){ continue; }
				if(startDay<=getTime(v)){
					p += clubmemberLog[u][v][0];
					for(var w in clubmemberLog[u][v][1]){
						if(!clubmemberLog[u][v][1].hasOwnProperty(w)){ continue; }
						help[w]=(help[w]==undefined?0:help[w])+clubmemberLog[u][v][1][w];
					}

				}
			}
			var help2=new Array();
			for(var w in help){
				if(!help.hasOwnProperty(w)){ continue; }
				help2.push({"p":w,"a":help[w]});
			}
			obj[0]=1;
			obj[1].push({"n":u,"p":p,"products":help2,"c":(u==FARMNAME?1:0)});
			obj[2]++;
			obj[4]=Math.max(obj[4],p);
		}
		if(obj[0]==0){
			obj[1]="No data";
		}else{
			obj[1].sort(function(a,b){return (b["p"]-a["p"]);});
		}

		var request=new Object();
		request.readyState=4;
		request.status=200;
		request.responseText=implode(obj);
		//GM_log("responseText= "+implode(obj));
		unsafeWindow.showGuildQuestStatsResponse(request,4,1,0); //type,page,self
		/*
		request: [1,[
			{"n":"name1","p":17049,"products":[{"p":"id","a":amount},...],"c":1},
			...
		],nameCounter,pageNr,highestPoints]
		on error: [0,text]
		*/
	}

	// Clubquest reformat
	$("guildquestbox").addEventListener ("DOMAttrModified", function(event){
		if ((this==event.target)&&(this.style.display == "block")){
			if(!$("guildquestboxBerater")){

				createElement("h1",{"id":"guildquestboxBerater","style":"display:none;"},$("guildquestboxcontent"));
				var cand=$("questobjectives").getElementsByClassName("link");
				var newdiv;
				for(var v=0;v<cand.length;v++){
					newdiv=cand[v].getElementsByTagName("b")[0];
					var help=/(\d+)\/(\d+)/.exec(newdiv.innerHTML.replace(regDelimThou,""));
					help[1]=parseInt(help[1],10);
					help[2]=parseInt(help[2],10);
					newdiv.innerHTML=((help[1]==help[2])?"":(numberFormat(help[2]-help[1])+"/"+numberFormat(help[2])));
					createElement("div",{"style":"position:absolute;top:0;left:0;width:100px;height:15px;color:black;font-weight:bold;text-align:center;"},cand[v].getElementsByTagName("div")[2],numberFormat(help[1]));
				}
				cand=null;newdiv=null;
			}
		}
	},false);
	// Clubquest product submitting
	$("commitboxguild").addEventListener ("DOMAttrModified", function(event){
		if ((this==event.target)&&(this.style.display == "block")){
			if(!$("commitboxguildBerater")){
				createElement("h1",{"id":"commitboxguildBerater","style":"display:none;"},$("commitboxcontentguild"));
				if((help=$("commitboxguildokbutton").getAttribute("onclick")).match(/guildQuestAddProducts\((\d+)\)/)){
					var currProd=/guildQuestAddProducts\((\d+)\)/.exec(help)[1];
					var cand=$("commitboxcontentguild").getElementsByTagName("input")[0];
					cand.setAttribute("prod",currProd);
					// maximal value according to minRack
					cand.value=Math.max(0,Math.min(cand.value,prodStock[0][currProd]-prodMinRack[0][currProd]));
					createElement("div",{"id":"commitboxguildLowrack","class":"blackbox alertbox","style":"display:none;position:absolute;top:135px;left:0;"},$("commitboxcontentguild"),texte["alertWillLowRack"]);
					cand.addEventListener("keyup",function(){
						// warning if more than minRack allows
						var currProd=this.getAttribute("prod");
						var help=(prodStock[0][currProd]-parseInt(this.value,10)<prodMinRack[0][currProd]?"block":"none");
						var cell=$("commitboxguildLowrack");
						if(cell.style.display!=help){ cell.style.display=help; }
						cell=null;
					},false);
					cand=null;
				}
			}
		}
	},false);

	/*
	// wanna see all clubhouses ? ^^
	unsafeWindow._setBeauties=unsafeWindow.setBeauties;
	unsafeWindow.setBeauties = function setBeauties(){
		for(var v=0;v<15;v++){ // <- edit the 18 (=max) to see the steps
			unsafeWindow.guilddata[4][v]=v+1;
		}
		unsafeWindow._setBeauties();
	}
	*/

	// Friendslist
	unsafeWindow._showfriendslist=unsafeWindow.showfriendslist;
	unsafeWindow.showfriendslist = function(status){
		unsafeWindow._showfriendslist(status);
		var cand=$("friendslistcon").getElementsByClassName("friendslinename");
		// for(var v=0;v<cand.length;v++){
		// 	var player=cand[v].getElementsByTagName("div")[0].innerHTML.replace(/&nbsp;.*/g,"");
		// 	newspan=vertrag(player,cand[v].nextSibling);
		// }
		cand=$("friendslistcon").getElementsByTagName("img");
		for(var v=0;v<cand.length;v++){
			if(cand[v].getAttribute("src").match(/\/guild\/1\.gif/)){
				cand[v].addEventListener("mouseover",function(event){ showToolTip(event,unsafeWindow.guildrank[1]); },false);
			}else if(cand[v].getAttribute("src").match(/\/guild\/2\.gif/)){
				cand[v].addEventListener("mouseover",function(event){ showToolTip(event,unsafeWindow.guildrank[2]); },false);
			}else if(cand[v].getAttribute("src").match(/\/star\.png/)){
				cand[v].addEventListener("mouseover",function(event){ showToolTip(event,unsafeWindow.lng_t_premium); },false);
			}
		}
		cand=null;
	};

	// Friendpage loaded
	err_trace="Friendpage";
	unsafeWindow._setFriendInfoContent=unsafeWindow.setFriendInfoContent;
	unsafeWindow.setFriendInfoContent = function(status,sel){
		unsafeWindow._setFriendInfoContent(status,sel);
		if(status == 1){
			var container=$("friendlistinfoblock");
			var cand=container.getElementsByTagName("li");
			var nextQuest=parseInt(cand[5].children[1].innerHTML,10)+1;
			if(QUESTS["farm"]["1"][nextQuest]){
				cand[5].setAttribute("nextQuest",nextQuest);
				cand[5].addEventListener("mouseover",function(event){
					var nextQuest=this.getAttribute("nextQuest");
					var str="<div style='border-bottom:1px solid white'>"+texte["quest"]+"&nbsp;"+nextQuest+"</div>";
					for(var i=0;i<QUESTS["farm"]["1"][nextQuest][0].length;i++){
						if(typeof QUESTS["farm"]["1"][nextQuest][0][i][0]=="object"){
							for(var j=0;j<QUESTS["farm"]["1"][nextQuest][0][i].length;j++){					
								str += "<div>*"+numberFormat(QUESTS["farm"]["1"][nextQuest][0][i][j][2])+"&nbsp;"+prodName[QUESTS["farm"]["1"][nextQuest][0][i][j][0]][QUESTS["farm"]["1"][nextQuest][0][i][j][1]]+"</div>";
							}
						}else{
							str += "<div>"+numberFormat(QUESTS["farm"]["1"][nextQuest][0][i][2])+"&nbsp;"+prodName[QUESTS["farm"]["1"][nextQuest][0][i][0]][QUESTS["farm"]["1"][nextQuest][0][i][1]]+"</div>";
						}
					}
					
					showToolTip(event,str);
				},false);
			}
			cand=null;container=null;
		}
	};

	// Farmis
	err_trace="Farmis";
	// Buylist opening
	unsafeWindow._showCart=unsafeWindow.showCart;
	unsafeWindow.showCart = function(farmi){
		unsafeWindow._showCart(farmi);
		var cand=$top("cartheader").getElementsByTagName("span")[0];
		cand.style.fontWeight="bold";
		cand.setAttribute("class","link");
		cand.addEventListener("mouseover",function(event){ showToolTip(event,texte["zumSGH"]); },false);
		cand.addEventListener("click",showSGH,false);
        cand=null;
		createElement("div",{"id":"cartsubmitPerc","style":"position:absolute;top:-35px;width:70px;padding:2px;text-align:right;font-size:20px;font-weight:bold;"},$("cartsubmit"));

		// get farmi data
		var preis=parseFloat(unsafeWindow.farmisinfo[0][farmi]['price'],10);
		var thisFarmiData=new Array();
		for(var i=1;i<=7;i++){
			var prod=parseInt(unsafeWindow.farmisinfo[0][farmi]['p'+i],10);
			var menge=parseInt(unsafeWindow.farmisinfo[0][farmi]['a'+i],10);
			if((prod>0)&&(menge>0)){
				var wert=menge*gut[prod];
				thisFarmiData.push([prod,menge,wert]);
			}
		}

		// rebuild the table
		function showCartBuildTable(){
			var cartContent=$("cartcontent");
			cartContent.innerHTML="";
			var priceMissing=false;
			thisFarmiData.sort(function(a,b){return (b[2]-a[2]);});

			var newtr,newtd;
			var newtable=createElement("table",{"border":"0","cellspacing":"0","cellpadding":"2","style":"width:270px;"},cartContent);
			var sum=0;
			for(var v=0;v<thisFarmiData.length;v++){
				var prod=thisFarmiData[v][0];
				var menge=thisFarmiData[v][1];
				var wert=thisFarmiData[v][2];
				sum += wert;
				newtr=createElement("tr",{"class":((prodStock[0][prod]<menge)?("farmicart_missing"):((prodStock[0][prod]-menge<prodMinRack[0][prod]-((valMinRackFarmis&&totalFarmis[0]&&totalFarmis[0][prod])?totalFarmis[0][prod]:0))?"farmicart_lowrack":"")),"prod":prod},newtable);
				produktPic(0,prod,createElement("td",{},newtr));
				createElement("td",{"style":"text-align:right;color:#336;font-size:16px;font-weight:bold;"},newtr,numberFormat(menge));
				newtd=createElement("td",{"class":"link","style":"color:#336;font-size:16px;font-weight:bold;"},newtr,prodName[0][prod]);
				newtd.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.parentNode.getAttribute("prod")); },false);
				newtd.addEventListener("click",function(){showMarket(this.parentNode.getAttribute("prod"));},false);
				newtd=createElement("td",{"class":"link","nr":v,"style":"text-align:right;color:#336;font-size:14px;"},newtr);
				if(wert>0){
					newtd=createElement("div",{"style":"position:relative;height:100%;padding-left:5px;padding-right:5px;"},newtd);
					createElement("div",{"style":"position:absolute;left:0;height:100%;width:"+Math.ceil(100*wert/thisFarmiData[0][2])+"%;background-color:grey;opacity:0.6;z-index:-1;"},newtd);
					createElement("span",{"style":"width:100%;"},newtd,moneyFormatInt(wert));
				}else{
					newtd.style.backgroundColor="red";
					priceMissing=true;
				}
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["editPrice"]); },false);
				newtd.addEventListener("click",function(){
					var cell=this;
					while(cell.nodeName!="TD"){ cell=cell.parentNode; }
					var v=cell.getAttribute("nr");
					cell=$("cartcontentEditPrice");
					if(cell){ removeElement(cell); }
					var newtable=createElement("div",{"id":"cartcontentEditPrice","style":"z-index:10;position:absolute;right:0;top:0;display:block;border-radius:5px;","class":"blackbox"},$("cartcontent"));
					var newtable=createElement("table",{"cellspacing":"0","cellpadding":"0","border":"0","nr":v},newtable);
					var newtr=createElement("tr",{},newtable);
					createElement("td",{"colspan":"2","style":"color:black;text-align:center;padding-bottom:2px;white-space:nowrap;"},newtr,texte["editPrice"]);
					newtr=createElement("tr",{},newtable);
					createElement("td",{"colspan":"2","style":"color:black;border-bottom:1px solid black;text-align:center;padding-bottom:2px;white-space:nowrap;"},newtr,numberFormat(thisFarmiData[v][1])+"&nbsp;"+prodName[0][thisFarmiData[v][0]]);
					newtr=createElement("tr",{},newtable);
					createElement("td",{"style":"color:black;text-align:left;padding-top:2px;padding-right:10px;"},newtr,texte["marktpreis"]);
					createElement("td",{"style":"color:black;text-align:right;padding-top:2px;"},newtr,moneyFormat(gut[thisFarmiData[v][0]]));
					newtr=createElement("tr",{},newtable);
					createElement("td",{"style":"color:black;text-align:left;padding-right:10px;"},newtr,texte["hofpreis"]);
					createElement("td",{"style":"color:black;text-align:right;"},newtr,isNaN(NPC[0][thisFarmiData[v][0]])?"-":moneyFormat(NPC[0][thisFarmiData[v][0]]));
					newtr=createElement("tr",{"style":"height:22px;"},newtable);
					createElement("td",{"style":"color:black;text-align:left;padding-right:10px;"},newtr,texte["einzel"]);
					var newtd=createElement("td",{},newtr);
					cell=createElement("input",{"class":"text","type":"text","style":"color:black;text-align:right;width:60px;","value":numberFormat(thisFarmiData[v][2]/thisFarmiData[v][1],2),"maxlength":"8"},newtd);
					cell.addEventListener("change",function(){
						var help=parseFloat(this.value.replace(regDelimThou,"").replace(regDelimDeci,"."),10);
						if(!isNaN(help)){
							if(help<0){ help*=-1; }
							help=Math.round(100*help)/100;
							this.value=numberFormat(help,2);
							var v=this.parentNode.parentNode.parentNode.getAttribute("nr");
							thisFarmiData[v][2]=help*thisFarmiData[v][1];
							this.parentNode.parentNode.nextElementSibling.children[1].firstElementChild.value=numberFormat(thisFarmiData[v][2],2);
						}
					},false);
					newtr=createElement("tr",{"style":"height:22px;"},newtable);
					createElement("td",{"style":"color:black;text-align:left;padding-right:10px;"},newtr,texte["total"]);
					newtd=createElement("td",{},newtr);
					cell=createElement("input",{"class":"text","type":"text","style":"color:black;text-align:right;width:60px;","value":numberFormat(thisFarmiData[v][2],2),"maxlength":"9"},newtd);
					cell.addEventListener("change",function(){
						var help=parseFloat(this.value.replace(regDelimThou,"").replace(regDelimDeci,"."),10);
						if(!isNaN(help)){
							if(help<0){ help*=-1; }
							help=Math.round(100*help)/100;
							this.value=numberFormat(help,2);
							var v=this.parentNode.parentNode.parentNode.getAttribute("nr");
							thisFarmiData[v][2]=help;
							this.parentNode.parentNode.previousElementSibling.children[1].firstElementChild.value=numberFormat(thisFarmiData[v][2]/thisFarmiData[v][1],2);
						}
					},false);
					newtr=createElement("tr",{"style":"height:22px;"},newtable);
					newtd=createElement("td",{"colspan":"2","style":"color:black;border-top:1px solid black;text-align:center;padding-top:2px;"},newtr);
					cell=createElement("button",{"class":"link","type":"button","style":"color:black;"},newtd,texte["ok"]);
					cell.addEventListener("click",function(){
						removeElement(this.parentNode.parentNode.parentNode.parentNode);
						showCartBuildTable();
					},false);
					cell=null;newtable=null;newtr=null;newtd=null;
				},false);
			}

			newtr=createElement("tr",{},newtable);
			createElement("td",{"colspan":"2"},newtr);
			createElement("td",{"style":"text-align:right;color:#336;font-size:14px;"},newtr,"100%:");
			createElement("td",{"style":"padding-left:5px;padding-right:5px;border-top:1px solid #336;text-align:right;color:#336;font-size:14px;"},newtr,moneyFormatInt(sum));

			newtr=createElement("tr",{},newtable);
			createElement("td",{"colspan":"2"},newtr);
			createElement("td",{"style":"text-align:right;color:#336;font-size:14px;"},newtr,"90%:");
			createElement("td",{"style":"padding-left:5px;padding-right:5px;text-align:right;color:#336;font-size:14px;"},newtr,moneyFormatInt(0.9*sum));

			newtd=$("cartsubmitPerc");
			if(priceMissing){
				newtd.style.border="4px inset #336";
				newtd.style.color="#336";
				newtd.style.backgroundColor="transparent";
				newtd.innerHTML="--%";
			}else{
				if(100*preis<valFarmiLimits[0]*sum){ var col="red";var col2="#fcc"; }
				else if(100*preis<valFarmiLimits[1]*sum){ var col="#d80";var col2="#ff9"; }
				else{ var col="green";var col2="#80ff80"; }
				newtd.style.border="4px inset "+col;
				newtd.style.color=col;
				newtd.style.backgroundColor=col2;
				newtd.innerHTML=Math.round(100*preis/sum)+"%";
			}
			cartContent=null;newtable=null;newtr=null;newtd=null;
		}
		showCartBuildTable();
	};
	// Farmis displayed
	unsafeWindow._setFarmis=unsafeWindow.setFarmis;
	unsafeWindow.setFarmis = function(){
		unsafeWindow._setFarmis();
		calcFarmiCost();
		calcTotalFarmis();
		doFarmis();
	};

	// Reallocate Buildings
	err_trace="Reallocate Buildings";
	document.addEventListener("gameReallocateBuilding",function(){
		if(DEVMODE_FUNCTION){GM_log("Begin gameReallocateBuilding"); }
		try{
			var building1=unsafeData.reallocateBuildingSet[0];
			var building2=unsafeData.reallocateBuildingSet[1];
			var help;

			help=zoneEndTimes[building1].clone();
			zoneEndTimes[building1]=zoneEndTimes[building2].clone();
			zoneEndTimes[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndTimes",implode(zoneEndTimes,"gameReallocateBuilding\zoneEndTimes"));
			unsafeData.zoneEndTimes=zoneEndTimes.clone();

			help=zoneWaterTimes[building1].clone();
			zoneWaterTimes[building1]=zoneWaterTimes[building2].clone();
			zoneWaterTimes[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneWaterTimes",implode(zoneWaterTimes,"gameReallocateBuilding\zoneWaterTimes"));
			unsafeData.zoneWaterTimes=zoneWaterTimes.clone();

			help=zoneEndProducts[building1].clone();
			zoneEndProducts[building1]=zoneEndProducts[building2].clone();
			zoneEndProducts[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneEndProducts",implode(zoneEndProducts,"gameReallocateBuilding\zoneEndProdcuts"));
			unsafeData.zoneEndProducts=zoneEndProducts.clone();

			help=zoneErnte[building1].clone();
			zoneErnte[building1]=zoneErnte[building2].clone();
			zoneErnte[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneErnte",implode(zoneErnte,"gameReallocateBuilding\zoneErnte"));
			unsafeData.zoneErnte=zoneErnte.clone();

			help=zoneTyp[building1].clone();
			zoneTyp[building1]=zoneTyp[building2].clone();
			zoneTyp[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneTyp",implode(zoneTyp,"gameReallocateBuilding\zoneTyp"));
			unsafeData.zoneTyp=zoneTyp.clone();

			help=zoneBlock[building1].clone();
			zoneBlock[building1]=zoneBlock[building2].clone();
			zoneBlock[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock,"gameReallocateBuilding\zoneBlock"));
			unsafeData.zoneBlock=zoneBlock.clone();

			zoneAnimals[building1]=zoneAnimals.splice(building2,1,zoneAnimals[building1])[0]; // this is a "swap"
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneAnimals",implode(zoneAnimals,"gameReallocateBuilding\zoneAnimals"));
			unsafeData.zoneAnimals=zoneAnimals.clone();

			help=zoneBonus[building1].clone();
			zoneBonus[building1]=zoneBonus[building2].clone();
			zoneBonus[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonus",implode(zoneBonus,"gameReallocateBuilding\zoneBonus"));
			unsafeData.zoneBonus=zoneBonus.clone();

			help=zoneProductionData[building1].clone();
			zoneProductionData[building1]=zoneProductionData[building2].clone();
			zoneProductionData[building2]=help;
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneProductionData",implode(zoneProductionData,"gameReallocateBuilding\zoneProductionData"));
			unsafeData.zoneProductionData=zoneProductionData.clone();

			zoneBonusSpecialProduct[building1]=zoneBonusSpecialProduct.splice(building2,1,zoneBonusSpecialProduct[building1])[0]; // this is a "swap"
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialProduct",implode(zoneBonusSpecialProduct,"gameReallocateBuilding\zoneBonusSpecialProduct"));
			unsafeData.zoneBonusSpecialProduct=zoneBonusSpecialProduct.clone();

			zoneBonusSpecialAmount[building1]=zoneBonusSpecialAmount.splice(building2,1,zoneBonusSpecialAmount[building1])[0]; // this is a "swap"
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonusSpecialAmount",implode(zoneBonusSpecialAmount,"gameReallocateBuilding\zoneBonusSpecialAmount"));
			unsafeData.zoneBonusSpecialAmount=zoneBonusSpecialAmount.clone();

			zoneMainprod[building1]=zoneMainprod.splice(building2,1,zoneMainprod[building1])[0]; // this is a "swap"
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneMainprod",implode(zoneMainprod,"gameReallocateBuilding\zoneMainprod"));
			unsafeData.zoneMainprod=zoneMainprod.clone();

		}catch(err){GM_log("ERROR gameReallocateBuilding \n"+err);}
		if(DEVMODE_FUNCTION){GM_log("End  gameReallocateBuilding"); }
	},false);
	unsafeWindow._reallocateBuilding=unsafeWindow.reallocateBuilding;
	unsafeWindow.reallocateBuilding = function(set){
		unsafeWindow._reallocateBuilding(set);
		//reallocateBuilding('farm1,zone1,farm2,zone2');
		unsafeData.reallocateBuildingSet=[(6*set[0])+set[1],(6*set[2])+set[3]];
		raiseEvent("gameReallocateBuilding");
	};

	// events forestry ==============================================================================
	err_trace="events forestry";

	/*
	$("globalcommitbox").addEventListener ("DOMAttrModified", function(event){
		try{
		var help;
		if ((this==event.target)&&(this.style.display == "block") && (help=$("forestry_questentry_value"))){
			var max = $("globalcommitbox").innerHTML.match(/chkForestryQuestEntryValue\(\d+,\d+,(\d+)\)/i);
			GM_log("max:"+implode(max));
			if (max && max[1]){
				help.value = max[1];
				keyup(help);
			}
		}
	}catch(err){GM_log("ERROR globalcommitbox \n"+err);}
	},false);
	
	Arrays:
	forestry_area_run       : >0 if growing
    forestry_area_time      : seconds till end of growing
    forestry_area_watertime : seconds till next watering (<=0 if water needed)
    forestry_area_name      : Name of tree if growing
	forestry_area_pid       : tree id {1,2,3,...}
	*/
/*
	unsafeWindow._forestryAjaxAction=unsafeWindow.forestryAjaxAction;
	unsafeWindow.forestryAjaxAction = function(action,position,pid,slot){
		// GM_log("forestryAjaxAction action="+action+" position="+position+" pid="+pid+" slot="+slot);
		// GM_log("currentslot="+unsafeWindow.currentslot);
		// open menu again
		// if((position==1)||(position==2)){
		if(position==2){
			if((action=="startproduction")||(action=="cancelproduction")||(action=="cropproduction")){
				document.addEventListener("gameOpenForestry",function(position){ return function(){
					document.removeEventListener("gameOpenForestry",arguments.callee,false);
					var div=$("forestry_building_click"+position);
					if(div){ click(div); }
					div=null;
				}}(position),false);
			}
		}
		unsafeWindow._forestryAjaxAction(action,position,pid,slot);
	}
*/
	unsafeWindow._initForestryResponse=unsafeWindow.initForestryResponse;
	unsafeWindow.initForestryResponse = function(request,uprack,upmenu,action,pos,tutorialstep,position){
	try{
		unsafeWindow._initForestryResponse(request,uprack,upmenu,action,pos,tutorialstep,position);
		var result = checkRequest(request);
		if(result && result[0]!=0){
			if(DEVMODE_FUNCTION){ GM_log("BEGIN initForestryResponse request="+request+" uprack="+uprack+" upmenu="+upmenu+" action="+action+" pos="+pos+" tutorialstep="+tutorialstep); }
			unsafeWindow.farm=""; //Hack for the scripts
			unsafeWindow.city=""; //Hack for the scripts
			// GM_log("forestry: result:\n"+print_r(result,"",true,"\n"));
			if(unsafeWindow.forestry_unlock){
				try{
					/* forestry_production_products{stock}{iProd}
					{0} = 36000 // Time
					{1}{1}{1} = 30 //points you get with harwisting this product
					{1}{1}{2} = 1 //amount it will produce
					{1}{1}{3} = 1 //stock number
					{1}{1}{4}{0} = 1 //campain number after which it can be used
					{1}{1}{4}{1} = 3 //quest number after which it can be used
					{1}{1}{5} = 21 //What can i make of this: stock 2 =[{0:product,1:amount}]; stock 1 = product; stock 3,4 = 0;
					{1}{1}{6} = 0 //What do i need for this: stock 4 =[{0:product,1:amount}]; stock 1 to 3 = 0
					{1}{1}{7} = 3 //something with the price.. but this could change dayly
					{1}{1}{8} = 0 //stock 5: [prod,amount] to be payed to get this forestry_area[][block] of the field.
					{1}{1}{9} = Fijnspar //NAME
					{1}{1}{10}{0} = 1 //only at stock 1
					{1}{1}{10}{1} = 2 //only at stock 1
					{1}{1}{11} = 0 ->stock 3: fid needed to produce
					{1}{1}{12} = 0 //item for in the farmbuilding
					*/
					//make prodName[1] && prodYield[1] && prodRequire[1] = [[type,fId,amount]]
					var store,stock,fId,bChanged=false,help,building;
					for(var stock in result[4]){ //forestry_production_products==initForestryResponce->result[4]
						if (!result[4].hasOwnProperty(stock)){ continue; }
						for(var fId in result[4][stock]){
							if (!result[4][stock].hasOwnProperty(fId)){ continue; }
							help=result[4][stock][fId];
							// if (!prodName[1][fId]){
							// 	prodName[1][fId] = help[9]; // set prodName[1]
							// 	//GM_log("initForestryResponse ADD prodName production fId:"+fId+" name:"+prodName[1][fId]);
							// 	bChanged=true;
							// }
							prodTyp[1][fId]="f"+stock;
							prodPoints[1][fId]=help[1];
							//GM_log("prodYield fId:"+fId+" [5]:"+typeof help[5]);
							building=getForestryUserBuilding(stock-1);
							prodStockMax[1][fId]=building?unsafeWindow.forestry_user_buildings[building]["capacity"]:0;
							if(stock==1){
								prodYield[1][fId]=1;
								prodYield[1][help[5]]=1;
								prodRequire[1][fId]=[[1,parseInt(fId,10),1]];
								prodRequire[1][help[5]]=[[1,parseInt(fId,10),1]];
								prodGrowTime[1][fId]=help[0]/60;
							}else if(stock==2){//forestry
								// [4]{2}{23}[5][0][0] = 47 //id
								// [4]{2}{23}[5][0][1] = 7 //#
								// for(var i=0;i<help[5].length;i++){
									 //prodYield[1][help[5][i][0]]=help[5][i][1];
									 //prodRequire[1][help[5][i][0]]=[[1,parseInt(fId,10),1]];
								// }
							}else if(stock==3){//sawmill
								prodYield[1][fId]=help[2];
								prodRequire[1][fId]=[[1,help[11],1]];
								building=getForestryUserBuilding(1);
								if(!prodGrowTime[1][fId]){
									if(building&&unsafeWindow.forestry_user_buildings[building]["boni"]){
										prodGrowTime[1][fId]=((help[0]*100)/(100-unsafeWindow.forestry_user_buildings[building]["boni"]))/60;
									}else{
										prodGrowTime[1][fId]=help[0]/60;
									}
								}
							}else if(stock==4){//carpentry
								//[4]{4}{101}[6][0][0] = 41 //id
								//[4]{4}{101}[6][0][1] = 4 //#
								prodYield[1][fId]=1;
								prodRequire[1][fId]=new Array();
								for(var i=0;i<help[6].length;i++){

									prodRequire[1][fId].push([1,help[6][i][0],help[6][i][1]]);
								}
								building=getForestryUserBuilding(2);
								if(!prodGrowTime[1][fId]){
									if(building&&unsafeWindow.forestry_user_buildings[building]["boni"]){
										prodGrowTime[1][fId]=((help[0]*100)/(100-unsafeWindow.forestry_user_buildings[building]["boni"]))/60;
									}else{
										prodGrowTime[1][fId]=help[0]/60;
									}
								}
							}
						}
					}
					stock=null;fId=null;help=null;
					prodPoints[1].sortObj();
					//GM_log("initForestryResponse prodPoints:"+implode(prodPoints,"prodPoints"));
					GM_setValueCache(LNG+"_"+SERVER+"_prodPoints",implode(prodPoints,"initForestryResponse\prodPoints"));
					prodTyp[1].sortObj();
					//GM_log("initForestryResponse prodTyp:"+implode(prodTyp,"prodTyp"));
					GM_setValueCache(LNG+"_"+SERVER+"_prodTyp",implode(prodTyp,"initForestryResponse\prodTyp"));
					prodYield[1].sortObj();
					//GM_log("initForestryResponse prodYield:"+implode(prodYield,"prodYield"));
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodYield",implode(prodYield,"initForestryResponse\prodYield"));
					prodRequire[1].sortObj();
					//GM_log("initForestryResponse prodRequire:"+implode(prodRequire,"prodRequire"));
					GM_setValueCache(LNG+"_"+SERVER+"_prodRequire",implode(prodRequire,"initForestryResponse\prodRequire"));
					prodGrowTime[1].sortObj();
					//GM_log("initForestryResponse prodGrowTime:"+implode(prodGrowTime,"prodGrowTime"));
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodGrowTime",implode(prodGrowTime,"initForestryResponse\prodGrowTime"));
					prodStockMax[1].sortObj();
					//GM_log("initForestryResponse prodStockMax:"+implode(prodStockMax,"prodStockMax"));
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStockMax",implode(prodStockMax,"initForestryResponse\prodStockMax"));
					//make prodName[1] && forestry_stock
					prodStock[1]=new Object();
					for(store in result[3]){ //forestry_stock
						if (!result[3].hasOwnProperty(store)){ continue; }
						for(fId in result[3][store]){
							if (!result[3][store].hasOwnProperty(fId)){ continue; }
							// if (!prodName[1][fId]){
							// 	prodName[1][fId] = result[3][store][fId]["name"]; // set prodName[1]
							// 	//GM_log("initForestryResponse ADD prodName stock fId:"+fId+" name:"+prodName[1][fId]);
							// 	bChanged=true;
							// }
							if(!prodStock[1][fId]) prodStock[1][fId]=0;
							prodStock[1][fId] += parseInt(result[3][store][fId]["amount"],10);
						}
					}
					for(fId in prodName[1]){
						if (!prodName[1].hasOwnProperty(fId)){ continue; }
						if(!prodStock[1][fId]){ prodStock[1][fId]=0; }
					}
					//GM_log("initForestryResponse prodStock:"+implode(prodStock,"prodStock"));
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock,"initForestryResponse\prodStock"));

					for(fId in prodName[1]){
						if(!prodName[1].hasOwnProperty(fId)){continue;}

						stock=prodTyp[1][fId].replace("f","");
						if(!!prodTyp[1][fId]&&!(result[4][stock]&&result[4][stock][fId])&&!prodBlock[1][fId].match(/b/)){
							prodBlock[1][fId]+="b";
						}
					}
					store=null;fId=null;
					prodStock[1].sortObj();
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock));

					//forestry_farmis
					var farmi, i;
					totalFarmis[1]=new Object();
					for(farmi in result[5]){ //forestry_farmis==initForestryResponce->result[5]
						if (!result[5].hasOwnProperty(farmi)){ continue; }
						for(i in result[5][farmi]["products"]){
							if (!result[5][farmi]["products"].hasOwnProperty(i)){ continue; }
							fId = result[5][farmi]["products"][i]["product"];
							// if (!prodName[1][fId]){
							// 	prodName[1][fId] = result[5][farmi]["products"][i]["name"]; // set prodName[1]
							// 	//GM_log("initForestryResponse ADD prodName farmis fId:"+fId+" name:"+prodName[1][fId]);
							// 	bChanged=true;
							// }
							if(!totalFarmis[1][fId]) totalFarmis[1][fId]=0;
							totalFarmis[1][fId] += parseInt(result[5][farmi]["products"][i]["amount"],10);
						}
					}
					totalFarmis[1].sortObj();
					//GM_log("initForestryResponse totalFarmis:"+implode(totalFarmis));
					GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_totalFarmis",implode(totalFarmis));

					if(bChanged){
						prodName[1].sortObj();
						//GM_log("initForestryResponse bChanged:"+ bChanged+" prodName:"+implode(prodName));
						GM_setValueCache(LNG+"_"+SERVER+"_prodName",implode(prodName));
					}
				}catch(err){GM_log("ERROR initForestryResponse \n"+err);}

				updateProductDataForestry();
				doForestry();
				raiseEvent("gameOpenForestry");
			}
			calcProdMinRack();
			if(DEVMODE_FUNCTION){ GM_log("END initForestryResponse"); }
		}
		}catch(err){GM_log("ERROR initForestryResponse \n"+err);}
	};

	var container = $("forestry_sawmill_productbox");
	var treeContainer, el1, el2;
	// Redesign sawmill
	for(var treeId=1;treeId<=5;treeId++){
		treeContainer = createElement("div",{"id":"forestry_sawmill_productbox_tree"+treeId,"style":"height:40px;"},container);
		el1 = createElement("div",{"id":"forestry_sawmill_productbox_log"+treeId,"class":"forestry_slot_product f_symbol"+(20+treeId),"style":"display:block;border-right:2px solid black;"},treeContainer);
		createElement("div",{"id":"forestry_sawmill_productbox_log"+treeId+"_amount","style":"position:absolute;top:-13px;"},el1)				
		for(var i=-2;i<=0;i++){
			if(el1=$("forestry_slot_products"+(treeId*3+i))){
				treeContainer.appendChild(el1);
				createElement("div",{"id":"forestry_slot_products"+(treeId*3+i)+"_amount","style":"position:absolute;top:-13px;"},el1);
				if(el2=$("forestry_slot_products_name"+(treeId*3+i))){
					el1.addEventListener("mouseover",function(){
						// $(this.id+"_endtime").innerHTML=0;
						var nr=this.id.replace("forestry_slot_products","");
						var div=$("forestry_slot_products"+nr+"_endtime");
						if(!div){
							if(div=$("forestry_slot_products_name"+nr)){
								div=createElement("div",{},div);
								createElement("img",{"src":GFX+"adtime.gif","style":"width:14px;height:14px;vertical-align:text-bottom;margin-right:5px;"},div);
								div=createElement("div",{"id":"forestry_slot_products"+nr+"_endtime","style":"display:inline-block;"},div);
							}
						}
						if(div){
							var iProd = parseInt(/f_symbol(\d+)/.exec(this.getAttribute("class"))[1],10);
							var iTime=calcProductionTime("sawmill",1,iProd,1-zoneBonus["sawmill"]/100);
							div.innerHTML=getDaytimeStr(now+iTime)+"&nbsp;"+texte["uhr"];
							iProd=null;iTime=null;
						}
						nr=null;div=null;
					},false);
				}
			}
		}
		/*
		el1 = createElement("div",{"id":"forestry_sawmill_productbox_scrap"+treeId,"class":"forestry_slot_product","style":"display:block;"},treeContainer);
		el2 = createElement("img",{"class":"link","alt":"X","style":"width:20px;height:20px;","src":GFX+"stadt/anullieren.gif"},el1);
		el2.addEventListener("click",function(){
			var treeId = parseInt(this.parentNode.id.replace("forestry_sawmill_productbox_scrap",""),10);
			var msgBody = createElement("div");
			createElement("div",{},msgBody,"How many "+prodName[1][20+treeId]+" shall be scrapped?"); // TODO texte
			createElement("input",{"id":"promptInputScrapLog","class":"text","value":"1","style":"width:50px;","maxlength":3,"treeId":treeId},msgBody);
			var yesFkt = function(){
				var input = $("promptInputScrapLog");
				var treeId = parseInt(input.getAttribute("treeId"),10);
				var amount = Math.min(parseInt(input.value,10),prodStock[1][20+treeId]);
				if(amount>0){ forestryScrapTreeLog(1,treeId,amount); }
				input=null;treeId=null;amount=null;
			};
			alert2(msgBody.innerHTML,texte["yes"],texte["no"],yesFkt);
			treeId=null;msgBody=null;yesFkt=null;
		},false);
		el2.addEventListener("mouseover",function(){ $(this.parentNode.id+"_name").style.display = "block"; },false);
		el2.addEventListener("mouseout", function(){ $(this.parentNode.id+"_name").style.display = "none"; },false);
		createElement("div",{"class":"forestry_slot_product_name blackbox","id":"forestry_sawmill_productbox_scrap"+treeId+"_name","style":"display:none;"},el1,"Scrap "+prodName[1][20+treeId]); //TODO texte
		*/
	}
	// Redesign Carpentry
	for(var i=1;i<=20;i++){
		el1=$("forestry_productiondialog_content_item_amount"+i);
		if(el1){
			el1.style.width = "150px";
			container = el1.parentNode; // $("forestry_productiondialog_content_item_con"+i);
			container.style.position = "relative";
			container.style.height = "28px";
			container.style.marginBottom = "5px";
			container.className = "hoverBgLightbrown";
			container.addEventListener("mouseover",function(evt){
				try{
					var prod = parseInt(/f_symbol(\d+)/.exec($(this.id.replace("forestry_productiondialog_content_item_con","forestry_productiondialog_content_item")).getAttribute("class"))[1],10);
					var container,newTable,newTr,newTd;
					container=createElement("div");
					newTable=createElement("table",{"class":"white"},container);
					// name
					newTr=createElement("tr",{},newTable);
					newTd=createElement("th",{"colspan":"2"},newTr,prodName[1][prod]);
					if(prodTyp[1][prod]=="f5"){
						newTr=createElement("tr",{},newTable);
						newTd=createElement("td",{"colspan":"2","style":"font-weight:bold;"},newTr,unsafeWindow.forestry_production_farmhouseitem_info_head);
					}else{
						// rack amount
						newTr=createElement("tr",{},newTable);
						newTd=createElement("td",{},newTr,texte["stock"]);
						newTd=createElement("td",{},newTr,numberFormat(prodStock[1][prod]));
					}
					showToolTip(evt,container.innerHTML);
				}catch(err){ GM_log("ERROR listener carpentryItem.mouseover\nprod="+prod+"\n"+err); }
			},false);
			// createElement("div",{"id":"forestry_productiondialog_content_item_rackamount"+i,"style":"position:absolute;top:25px;left:0px;"},container,"0");
			el1=insertAfter(createElement("div",{"class":"forestry_productiondialog_content_item_main_amount","style":"width:150px;"}),el1);
			el2=createElement("div",{"style":"display:inline-block;height:15px;width:15px;margin-right:1px;"},el1);
			createElement("img",{"src":GFX+"lager/wachstum.gif","style":"width:14px;height:14px;vertical-align:text-bottom;"},el2);
			createElement("div",{"id":"forestry_productiondialog_content_item_times"+i,"style":"display:inline-block;width:58px;"},el1,"0");
			el2=createElement("div",{"style":"display:inline-block;height:15px;width:15px;margin-left:2px;margin-right:1px;"},el1);
			createElement("img",{"src":GFX+"adtime.gif","style":"width:14px;height:14px;vertical-align:text-bottom;"},el2);
			createElement("div",{"id":"forestry_productiondialog_content_item_endtimes"+i,"style":"display:inline-block;width:58px;"},el1,"0");
		}
	}
	container=null;treeContainer=null;el1=null;el2=null;
	
	unsafeWindow._showForestryProductionBox=unsafeWindow.showForestryProductionBox;
	unsafeWindow.showForestryProductionBox = function(type){
		unsafeWindow._showForestryProductionBox(type);
		if(DEVMODE){ GM_log("showForestryProductionBox type="+type); }
		if(type==1){ // sawmill
			var container,prod,classStr,flagDisplay,div;
			var zoneNrF="sawmill";
			for(var treeId=1;treeId<=5;treeId++){
				try{
					container = $("forestry_sawmill_productbox_tree"+treeId);
					classStr = container.children[0].getAttribute("class");
					prod = parseInt(/f_symbol(\d+)/.exec(classStr)[1],10);
					$(container.children[0].id+"_amount").innerHTML = numberFormat(prodStock[1][prod]);
					
					flagDisplay = "none";
					for(var i=1;i<=3;i++){
						if(container.children[i].style.display!="none"){
							flagDisplay = "block"; 
							classStr = container.children[i].getAttribute("class");
							prod = parseInt(/f_symbol(\d+)/.exec(classStr)[1],10);
							if(!classStr.match(/ link$/)){ container.children[i].setAttribute("class",classStr+" link"); }
							$(container.children[i].id+"_amount").innerHTML = numberFormat(prodStock[1][prod]);
						}
					}
					container.style.display = flagDisplay;
				}catch(err){ GM_log("ERROR showForestryProductionBox sawmill\ntreeId="+treeId+"\n"+err); }
			}
			//auto-cropping
			for(var slot=1;slot<=3;slot++){
				try{
					if((top.unsafeData.autoAction==null) && valAutoCrop["forestry"] && (div=$("forestry_slot_crop"+slot)) && (div.style.display=="block")){
						top.unsafeData.autoAction="berater: sawmill crop";
						document.addEventListener("gameOpenGlobalCommitBox",function(){
							document.removeEventListener("gameOpenGlobalCommitBox",arguments.callee,false);
							window.setTimeout(function(){ 
								click($("globalcommitboxfooter").firstElementChild); 
								top.unsafeData.autoAction=null;
							},500);
						});
						window.setTimeout(function(div){ click(div); },500,div);
					}
					div=null;
				}catch(err){ GM_log("ERROR showForestryProductionBox sawmill\nslot="+slot+"\n"+err); }
			}
			container=null;prod=null;classStr=null;flagDisplay=null;
			raiseEvent("gameOpenSawmill");
		} else if(type==2){ // carpentry
			var container,icon,prod,help;
			for(var i=1;i<=20;i++){
				try{			
				container=$("forestry_productiondialog_content_item_con"+i);
				icon=$("forestry_productiondialog_content_item"+i);
				if(container&&icon&&(container.style.display=="block")){
					prod = parseInt(/f_symbol(\d+)/.exec(icon.getAttribute("class"))[1],10);
					// show rack amount
					// $("forestry_productiondialog_content_item_rackamount"+i).innerHTML = numberFormat(prodStock[1][prod]);
					// check required products
					help=true;
					for(var j=0;j<prodRequire[1][prod].length;j++){
						if(prodStock[1][prodRequire[1][prod][j][1]]<prodRequire[1][prod][j][2]){ help=false; }
					}
					if(help){
						if(icon.childElementCount>0){ removeElement(icon.children[0]); }
					} else {
						if(icon.childElementCount==0){ createElement("img",{"alt":"X","style":"width:25px;height:25px;","src":GFX+"cursors/cursor_forbidden.gif"},icon); }
					}
					// show times
					help=calcProductionTime("carpentry",1,prod,1-zoneBonus["carpentry"]/100);
					if(icon=$("forestry_productiondialog_content_item_amount"+i)){
						icon.innerHTML = prodName[1][prod];
					}
					if(icon=$("forestry_productiondialog_content_item_times"+i)){
						icon.innerHTML = getTimeStr(help,true)+"&nbsp;"+texte["stunden"];
					}
					if(icon=$("forestry_productiondialog_content_item_endtimes"+i)){
						icon.innerHTML = getDaytimeStr(now+help,true,true)+"&nbsp;"+texte["uhr"];
					}
				}
				}catch(err){ GM_log("ERROR showForestryProductionBox carpentry\ni="+i+"\n"+err); }
			}
			//auto-cropping
			for(var slot=1;slot<=3;slot++){
				try{
					if((top.unsafeData.autoAction==null) && valAutoCrop["forestry"] && (div=$("forestry_slot_crop"+slot)) && (div.style.display=="block")){
						top.unsafeData.autoAction="berater: carpentry crop";
						document.addEventListener("gameOpenGlobalCommitBox",function(){
							document.removeEventListener("gameOpenGlobalCommitBox",arguments.callee,false);
							window.setTimeout(function(){
								click($("globalcommitboxfooter").firstElementChild);
								top.unsafeData.autoAction=null;
							},500);
						});
						window.setTimeout(function(div){ click(div); },500,div);
					}
					div=null;
				}catch(err){ GM_log("ERROR showForestryProductionBox carpentry\nslot="+slot+"\n"+err); }
			}
			container=null;icon=null;prod=null;help=null;
			raiseEvent("gameOpenCarpentry");
		}
	}	

	unsafeWindow._forestrySetSlot=unsafeWindow.forestrySetSlot;
	unsafeWindow.forestrySetSlot = function(type,slot){
		unsafeWindow._forestrySetSlot(type,slot);
		if(type==1){
			raiseEvent("gameOpenSawmillSlot")
		}else if(type==2){
			raiseEvent("gameOpenCarpentrySlot")
		}		
	}

	/*
	createElement("div",{"id":"analyzediv","style":"position: fixed; top: 0px; right: 0px; z-index: 995; display: block;","class":"blackbox"},ALL);
	$("analyzediv").addEventListener("click",function(){this.innerHTML="";},false);
	unsafeWindow._forestrySetStatus=unsafeWindow.forestrySetStatus;
	unsafeWindow.forestrySetStatus = function(position,status,product){
		unsafeWindow._forestrySetStatus(position,status,product);
		var str = 'forestry_area_run       = '+unsafeWindow.forestry_area_run      [position]+'<br>'+
                  'forestry_area_time      = '+unsafeWindow.forestry_area_time     [position]+'<br>'+
                  'forestry_area_watertime = '+unsafeWindow.forestry_area_watertime[position]+'<br>'+
                  'forestry_area_name      = '+unsafeWindow.forestry_area_name     [position]+'<br>'+
                  'forestry_area_pid       = '+unsafeWindow.forestry_area_pid      [position];
		for(var j = 0 ; j < unsafeWindow.forestry_area.length ; j++)	{
			if(unsafeWindow.forestry_area[j])	{
				if(unsafeWindow.forestry_area[j]['position'] == position){
					str ="forestry_area["+j+"]="+implode(unsafeWindow.forestry_area[j]);
				}
			}
		}
		GM_log(str);
		$("analyzediv").innerHTML=str;
	}
	*/

	function doForestry(){
	try{
		gameLocation=["forestry",null];
		unsafeData.gameLocation=gameLocation.clone();
		var nowServer=unsafeWindow.Zeit.Server;
		var zoneNrF,zoneNrS,tempZoneProductionData,tempZoneProductionDataSlot;
		// GM_log("forestry_slots:\n"+print_r(unsafeWindow.forestry_slots,"",true,"\n"));
		// Sawmill and carpentry
		var err_trace="forestry_user_buildings";
		if(unsafeWindow.forestry_user_buildings){
			var res,iProd,iTime,maxCapacity,iSlotCount;
			for(var building in unsafeWindow.forestry_user_buildings){ //forestry_user_buildings==initForestryResponce->result[2]
				if(!unsafeWindow.forestry_user_buildings.hasOwnProperty(building)){continue;}
				switch(building){
				case "1": zoneNrF="sawmill";break;
				case "2": zoneNrF="carpentry";break;
				default: continue;
				}
				// GM_log("forestry_user_buildings["+building+"]:\n"+print_r(unsafeWindow.forestry_user_buildings[building],"",true,"\n"));
				//building=getForestryUserBuilding(i);
				zoneBlock[zoneNrF]=(unsafeWindow.forestry_user_buildings[building]["locked"]?"q":"");
				if(isMultiSlotZone(zoneNrF)){
					iSlotCount=3;
					if(zoneBlock[zoneNrF]){
						for(var slot=1;slot<=3;slot++){
							zoneBlock[zoneNrF+"."+slot]=true;
						}
					}else{
						for(var slot=1;slot<=3;slot++){
							zoneBlock[zoneNrF+"."+slot]=!((slot==1)||(unsafeWindow.forestry_slots[building]&&unsafeWindow.forestry_slots[building][slot]));
						}
					}
				}else{
					iSlotCount=0;
				}
				if(!zoneBlock[zoneNrF]){
					zoneBonus[zoneNrF]=unsafeWindow.forestry_user_buildings[building]["boni"]?unsafeWindow.forestry_user_buildings[building]["boni"]:0;
					// maxCapacity=unsafeWindow.forestry_user_buildings[building]?unsafeWindow.forestry_user_buildings[building]["capacity"]:100;
					res=(unsafeWindow.forestry_user_buildings[building]&&unsafeWindow.forestry_user_buildings[building]["slots"])?unsafeWindow.forestry_user_buildings[building]["slots"]:{};
					
					tempZoneProductionData=[[{},{}],0,0,true];
					for(var slot=1;slot<=(iSlotCount==0?1:iSlotCount);slot++){
						if(DEVMODE){ GM_log("doForestry zoneNrF="+zoneNrF+" slot="+slot+" res["+slot+"]="+implode(res[slot],"res")); }
						if(iSlotCount>0){
							zoneNrS=zoneNrF+"."+slot;
						}else{
							zoneNrS=zoneNrF;
						}
						if(!zoneBlock[zoneNrS]){
							tempZoneProductionDataSlot=[[{},{}],0,0,true];
							if(res[slot]){
								iProd=(res[slot]["productid"]?parseInt(res[slot]["productid"],10):null);
								if(isNaN(iProd)){ iProd=null; }
									// &&maxCapacity<(prodStock[1][iProd]+((iStock+1)*prodYield[1][iProd]))){
									// tempZoneProductionData["block"][slot]=true;
									// if(tempZoneProductionData["block"].length()==1){
									// 	showInLogBubble("Max stock capacity reached for<br>"+prodName[1][iProd],10,"red"); // TODO texte
									// }
								if((iProd!=null)&&(res[slot]["ready"]==2)){ // production busy
									iTime=nowServer+res[slot]["remain"]; 
								}else if((iProd!=null)&&(res[slot]["ready"]==1)){ // production ready
									iTime=nowServer;
								}else{
									iTime=NEVER;
									tempZoneProductionData[1]++;
									tempZoneProductionDataSlot[1]++;
								}
								tempZoneProductionData[2]++;
								tempZoneProductionDataSlot[2]++;
								if(iProd!=null){
									if(!tempZoneProductionData[0][1][iProd]){ tempZoneProductionData[0][1][iProd]=[]; }
									tempZoneProductionData[0][1][iProd].push([1,iTime,NEVER]);
									if(!tempZoneProductionDataSlot[0][1][iProd]){ tempZoneProductionDataSlot[0][1][iProd]=[]; }
									tempZoneProductionDataSlot[0][1][iProd].push([1,iTime,NEVER]);
								}
							}
							if(iSlotCount>0){
								zoneProductionData[zoneNrS]=tempZoneProductionDataSlot.clone();
								processZoneProductionData(zoneNrS);
							}
						}
					}
					zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
					processZoneProductionData(zoneNrF);
					//auto-cropping
					if(iSlotCount=0){
						var div;
						if((top.unsafeData.autoAction==null) && valAutoCrop["forestry"] && (zoneEndTimes[zoneNrF]<=unsafeWindow.Zeit.Server) && (div=$("forestry_building_click"+building))){
							top.unsafeData.autoAction="berater: forestry building crop";
							document.addEventListener("gameOpenGlobalCommitBox",function(){
								document.removeEventListener("gameOpenGlobalCommitBox",arguments.callee,false);
								window.setTimeout(function(){ 
									click($("globalcommitboxfooter").firstElementChild);
									top.unsafeData.autoAction=null;
								},500);
							});
							window.setTimeout(function(div){ click(div); },500,div);
						}
						div=null;
					}
					makeZoneTimers(zoneNrF,"zonetimer","position:absolute;top:5px;left:50px;",$("forestry_building"+building));
				}
			}
			building=null;res=null;iProd=null;iTime=null;maxCapacity=null;zones=null;
		}
		// Forest
		zoneNrF="forest";
		err_trace="forest";
		if(unsafeWindow.forestry_unlock){
			var res,zoneNrF,iProd,iProd2,iTime,iWaterTime,building,maxCapacity,div;
			//GM_log("doForestry zoneNrF:"+zoneNrF);
			//maxCapacity=((building=getForestryUserBuilding(1))&&unsafeWindow.forestry_user_buildings[building])?unsafeWindow.forestry_user_buildings[building]['capacity']:100;
			tempZoneProductionData=[[{},{}],25,25,true];
			zoneBlock[zoneNrF]="";
			zoneBonus[zoneNrF]=((div=$("forestry_forest_button1_info_locked"))&&(div.style.display=="block")?0:5);
			if(questData["lodge"]["1"]["nr"]>75){ zoneBonus[zoneNrF]+=5; }
			for(var slot in unsafeWindow.forestry_area){ //forestry_area==initForestryResponce->result[1]
				if(!unsafeWindow.forestry_area.hasOwnProperty(slot)){continue;}
				//if(DEVMODE){ GM_log("doFestry zoneNrF:"+zoneNrF+" slot:"+slot+" res:"+implode(res,"res")); }
				res=unsafeWindow.forestry_area[slot];
				iProd=parseInt(res["productid"],10); // the saplings
				if(unsafeWindow.forestry_production_products[res["category"]]){
					iProd2=unsafeWindow.forestry_production_products[res["category"]][iProd][5]; // the tree
				}else{
					iProd2=null;
				}
				if(res["category"]==0){ // garbage
					if(!tempZoneProductionData[0][1][iProd]){ tempZoneProductionData[0][1][iProd]=0; }
					tempZoneProductionData[0][1][iProd]++;
					tempZoneProductionData[1]--;
					tempZoneProductionData[2]--;
				}else{
					// if(maxCapacity<(prodStock[1][iProd2]+((iStock+1)*prodYield[1][iProd2]))){
					// 	//TODO maybe maxCapacity needed for wood-cuttings
					// 	iTime=NEVER;
					// 	iWaterTime=NEVER;
					// 	if(tempZoneProductionData["block"].length()==1){
					// 		showInLogBubble("Max stock capacity reached for<br>"+prodName[1][iProd2],10,"red");
					// 	}
					if(res["block"]>0){ //production has animal on it
						tempZoneProductionData[1]--;
						iTime=NEVER;
						iWaterTime=NEVER;
					}else if(res["ready"]){
						tempZoneProductionData[1]--;
						if(res["ready"]==2){ //production busy, "duration" is reduced by watering
							iTime=parseInt(res["duration"],10)+parseInt(res["createdate"],10);
							if(zoneBonus["forest"]>0){
								iWaterTime=parseInt(res["waterdate"],10);
								iWaterTime=((iWaterTime==0)?parseInt(res["createdate"],10):(iWaterTime+86400<iTime?iWaterTime+86400:NEVER));
							}else{
								iWaterTime=NEVER;
							}
						}else if(res["ready"]==1){ //production ready
							iTime=parseInt(res["duration"],10)+parseInt(res["createdate"],10);
							iWaterTime=NEVER;
						}else{
							// does this case exist?
							iTime=NEVER;
							iWaterTime=NEVER;
						}
					}else{
						iTime=NEVER;
						iWaterTime=NEVER;
					}
                
					if(tempZoneProductionData[0][1][iProd]){
						var notfound=true;
						for(var i=0;i<tempZoneProductionData[0][1][iProd].length;i++){
							if(notfound&&(tempZoneProductionData[0][1][iProd][i][1]==iTime)&&(tempZoneProductionData[0][1][iProd][i][2]==iWaterTime)){
								tempZoneProductionData[0][1][iProd][i][0]++;
								notfound=false;
							}
						}
						if(notfound){ tempZoneProductionData[0][1][iProd].push([1,iTime,iWaterTime]); }
					}else{
						tempZoneProductionData[0][1][iProd]=[[1,iTime,iWaterTime]];
					}
					if(iProd2!=null){
					if(tempZoneProductionData[0][1][iProd2]){
						var notfound=true;
						for(var i=0;i<tempZoneProductionData[0][1][iProd2].length;i++){
							if(notfound&&(tempZoneProductionData[0][1][iProd2][i][1]==iTime)&&(tempZoneProductionData[0][1][iProd2][i][2]==iWaterTime)){
								tempZoneProductionData[0][1][iProd2][i][0]++;
								notfound=false;
							}
						}
						if(notfound){ tempZoneProductionData[0][1][iProd2].push([1,iTime,iWaterTime]); }
					}else{
						tempZoneProductionData[0][1][iProd2]=[[1,iTime,iWaterTime]];
					}
					}
				}
			}
			zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
			processZoneProductionData(zoneNrF);
			// auto-watering
			if((top.unsafeData.autoAction==null)&&valAutoWater["forestry"]&&(zoneWaterTimes[zoneNrF]<=unsafeWindow.Zeit.Server)&&(zoneBonus[zoneNrF]>0)&&(zoneProductionData[zoneNrF][1]==0)&&(div=$("forestry_forest_button1"))){
				top.unsafeData.autoAction="berater: forest water";
				window.setTimeout(function(div){
					click(div);
					top.unsafeData.autoAction=null;
				},500,div);
			}
			//auto-cropping
			if((top.unsafeData.autoAction==null)&&valAutoCrop["forestry"]&&(zoneEndTimes[zoneNrF]<=unsafeWindow.Zeit.Server) && (!((div=$("forestry_forest_button2_premium"))&&(div.style.display=="block")))&&(div=$("forestry_forest_button2"))){
				top.unsafeData.autoAction="berater: forest crop";
				window.setTimeout(function(div){ 
					click(div);
					top.unsafeData.autoAction=null;
				},500,div.firstElementChild);
			}
			//zonetimer
			div=$("forestry_forest");
			makeZoneTimers("forest","zonetimer","position:absolute;top:-20px;right:0;",div);
			if(zoneBonus["forest"]>0){ makeZoneTimers("forest","zoneTimerWater","position:absolute;top:-40px;right:0;",div); }
			// stock
			unsafeWindow.forestrySetStockItem(1,Math.max(1,unsafeWindow.forestry_plant),Math.max(1,unsafeWindow.forestry_plant));
			var newDiv;
			for(var v=1;v<=6;v++){
				if(div=$("f_stock_item"+v)){
					iProd=parseInt(/f_symbol(\d+)/.exec(div.firstElementChild.className)[1],10);
					if(iProd&&(div=$("f_stock_growing_"+v))){
						iTime=calcProductionTime("forest",1,iProd,1-zoneBonus[zoneNrF]/100);
						div.innerHTML=getTimeStr(iTime,true)+"&nbsp;"+texte["stunden"];
						if(!(newDiv=$("forestry_stock1_item_endtime"+v))){
							div.parentNode.parentNode.style.height="44px";
							newDiv=createElement("div",{"style":"float:left;height:15px;width:15px;margin-right:5px;"},div.parentNode);
							createElement("img",{"src":GFX+"adtime.gif","style":"width:14px;height:14px;"},newDiv);
							newDiv=createElement("div",{"id":"forestry_stock1_item_endtime"+v,"time":iTime,"class":"forestry_stockitem_time"},div.parentNode,getDaytimeStr(now+iTime)+"&nbsp;"+texte["uhr"]);
							createElement("div",{"class":"clear"},div.parentNode);
						}
					}
				}
			}
			if(div=$("forestry_stock1_object")){
				div.addEventListener("mouseover",function(){
					var div,iTime;
					if((div=$("forestry_stock1"))&&(div.getAttribute("clocksTicking")!="1")){
						div.setAttribute("clocksTicking","1");
						for(var v=1;v<=6;v++){
							if(div=$("forestry_stock1_item_endtime"+v)){
								iTime=parseInt(div.getAttribute("time"),10);
								div.innerHTML=getDaytimeStr(now+iTime)+"&nbsp;"+texte["uhr"];
							}
						}
						window.setTimeout(function(){
							var div,iTime;
							for(var v=1;v<=6;v++){
								if(div=$("forestry_stock1_item_endtime"+v)){
									iTime=parseInt(div.getAttribute("time"),10);
									div.innerHTML=getDaytimeStr(now+iTime)+"&nbsp;"+texte["uhr"];
								}
							}
							div=null;iTime=null;
							if((div=$("forestry_stock1"))&&(div.style.display=="block")){
								window.setTimeout(arguments.callee,950);
							}else{
								div.setAttribute("clocksTicking","0");
							}
						},950);
					}
					div=null;iTime=null;
				},false);
			}
			// farmies
			for(var i=0;i<unsafeWindow.forestry_farmis.length;i++){
				// GM_log("unsafeWindow.forestry_farmis["+i+"]:\n"+print_r(unsafeWindow.forestry_farmis[i],"",true,"\n"));
				iTime=[0,0];
				for(var j=0;j<unsafeWindow.forestry_farmis[i]["products"].length;j++){
					iProd = unsafeWindow.forestry_farmis[i]["products"][j]["product"];
					if(prodTyp[1][iProd]=="f3"){
						iTime[0]+=calcProductionTime("sawmill",1,iProd,1-zoneBonus["sawmill"]/100)*unsafeWindow.forestry_farmis[i]["products"][j]["amount"]/prodYield[1][iProd];
					} else if(prodTyp[1][iProd]=="f4"){
						iTime[1]+=calcProductionTime("carpentry",1,iProd,1-zoneBonus["carpentry"]/100)*unsafeWindow.forestry_farmis[i]["products"][j]["amount"]/prodYield[1][iProd];
					}
					if(typeof prodRequire[1][iProd]=="object"){
						for(var k=0;k<prodRequire[1][iProd].length;k++){
							iProd2=prodRequire[1][iProd][k];
							if(prodTyp[iProd2[0]][iProd2[1]]=="f3"){
								iTime[0]+=calcProductionTime("sawmill",iProd2[0],iProd2[1],1-zoneBonus["sawmill"]/100)*unsafeWindow.forestry_farmis[i]["products"][j]["amount"]*iProd2[2]/prodYield[iProd2[0]][iProd2[1]];
							} else if(prodTyp[iProd2[0]][iProd2[1]]=="f4"){
								iTime[1]+=calcProductionTime("carpentry",iProd2[0],iProd2[1],1-zoneBonus["carpentry"]/100)*unsafeWindow.forestry_farmis[i]["products"][j]["amount"]*iProd2[2]/prodYield[iProd2[0]][iProd2[1]];
							}
						}
					}
				}
				div=$("forestry_farmi_info"+(1+i));
				if(div&&div.parentNode){
					newDiv=$("forestry_farmi_info"+(i+1)+"_createdate");
					if(!newDiv){
						newDiv=createElement("div",{"id":"forestry_farmi_info"+(i+1)+"_createdate"});
						div.insertBefore(newDiv,div.firstElementChild);
					}
					newDiv.innerHTML=getDateStr(unsafeWindow.forestry_farmis[i]["createdate"]);
				}
				div=$("forestry_farmi_info_price"+(1+i));
				if(div&&div.parentNode){
					newDiv=$("forestry_farmi_info"+(i+1)+"_time_sawmill");
					if(!newDiv){
						newDiv=createElement("div",{"id":"forestry_farmi_info"+(i+1)+"_time_sawmill"});
						div.parentNode.parentNode.insertBefore(newDiv,div.parentNode);
					}
					newDiv.innerHTML=texte["sawmill"]+": "+getTimeStr(iTime[0],true)+"&nbsp;"+texte["stunden"];
					newDiv=$("forestry_farmi_info"+(i+1)+"_time_carpentry");
					if(!newDiv){
						newDiv=createElement("div",{"id":"forestry_farmi_info"+(i+1)+"_time_carpentry"});
						div.parentNode.parentNode.insertBefore(newDiv,div.parentNode);
					}
					newDiv.innerHTML="("+texte["carpentry"]+": "+getTimeStr(iTime[1],true)+"&nbsp;"+texte["stunden"]+")";
					newDiv=$("forestry_farmi_info_price"+(i+1)+"_norm");
					if(!newDiv){
						newDiv=createElement("span",{"id":"forestry_farmi_info_price"+(i+1)+"_norm","style":"font-size:8pt;"},div.parentNode);
					}
					newDiv.innerHTML="&nbsp;("+moneyFormatInt(unsafeWindow.forestry_farmis[i]["price"]*86400/iTime[0])+"/d)";
				}
				div=$("forestry_farmi_info_points"+(1+i));
				if(div&&div.parentNode){
					div.innerHTML=numberFormat(unsafeWindow.forestry_farmis[i]["points"]);
					newDiv=$("forestry_farmi_info_points"+(i+1)+"_norm");
					if(!newDiv){
						newDiv=createElement("span",{"id":"forestry_farmi_info_points"+(i+1)+"_norm","style":"font-size:8pt;"},div.parentNode);
					}
					newDiv.innerHTML="&nbsp;("+numberFormat(unsafeWindow.forestry_farmis[i]["points"]*86400/iTime[0])+"/d)";
				}
			}
			res=null;pos=null;iProd=null;iProd2=null;iTime=null;iWaterTime=null;iStock=null;building=null;maxCapacity=null;
		}else{
			zoneBlock[zoneNrF]="q";
			zoneBonus[zoneNrF]=0;
		}
		zoneNrF=null;tempZoneProductionData=null;tempZoneProductionDataSlot=null;

		err_trace="saving";
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBonus",implode(zoneBonus,"doForestry/zoneBonus"));
		unsafeData.zoneBonus=zoneBonus.clone();
		GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_zoneBlock",implode(zoneBlock,"doForestry/zoneBlock"));
		unsafeData.zoneBlock=zoneBlock.clone();
		publishProductData();
	}catch(err){GM_log("ERROR doForestry ("+err_trace+")\n"+err);}
	}
	
	function forestryScrapTreeLog(step,treeId,amount){
		// GM_log("forestryScrapTreeLog BEGIN step="+step+" treeId="+treeId);
		var action=null,listeningEvent=null;
		switch(step){
		case 1: // click the production icon
			if(amount>0){
				showInLogBubble("Scrapping Tree Log: tree "+treeId+", left "+amount);
				listeningEvent="gameOpenGlobalCommitBox";
				action=function(){ click($("forestry_slot_products"+(3*treeId-2))); };
			}
		break;
		case 2: // click OK. sawmill will be reopened
			listeningEvent="gameOpenSawmill";
		 	action=function(){ click($("globalcommitboxfooter").children[0]); };
		break;
		case 3: // click Abort
			listeningEvent="gameOpenGlobalCommitBox";
		 	action=function(){ click($("forestry_slot_cancel"+unsafeWindow.currentslot)); };			
		break;
		case 4: // click OK. sawmill will be reopened
			listeningEvent="gameOpenSawmill";
		 	action=function(){ click($("globalcommitboxfooter").children[0]); };
		break;
		case 5: // open production menu again
			amount--;step=0;
			listeningEvent="gameOpenSawmillSlot";
		 	action=function(){ click($("forestry_slot"+unsafeWindow.currentslot)); };
		break;
		}
		if(listeningEvent){
			document.addEventListener(listeningEvent,function(listeningEvent,step,treeId,amount){
				return function(){
					document.removeEventListener(listeningEvent,arguments.callee,false);
					window.setTimeout(function(){ forestryScrapTreeLog(step+1,treeId,amount); },300);
				};
			}(listeningEvent,step,treeId,amount),false);
		}
		if(action){ action(); }
		listeningEvent=null;action=null;
	}
	
	unsafeWindow._forestryBuySlotResponse=unsafeWindow.forestryBuySlotResponse;
	unsafeWindow.forestryBuySlotResponse = function(request){
	try{
		unsafeWindow._forestryBuySlotResponse(request);
		var result = checkRequest(request);
		if(result){
			if(DEVMODE){ GM_log("forestryBuySlotResponse result:"+implode(result)); }
			doForestry();
			calcProdMinRack();
		}
		}catch(err){GM_log("ERROR forestryBuySlotResponse \n"+err);}
	};

	unsafeWindow._initCampaignsResponse=unsafeWindow.initCampaignsResponse;
	unsafeWindow.initCampaignsResponse = function(request,update){
	try{
		unsafeWindow._initCampaignsResponse(request,update);
		var result = checkRequest(request);
		if(result&&result[0]!=0){
			if(DEVMODE){ GM_log("initCampaignsResponse"); }
			// GM_log("initCampaignsResponse result="+implode(result));
			//if(DEVMODE){ GM_log("campaign: result:"+print_r(result)); }
			for(campaign in QUESTS["lodge"]){
				if(!QUESTS["lodge"].hasOwnProperty(campaign)){continue;}
				if(result[1][campaign]){
					if(result[1][campaign]==0){
						// campaign not available
						var newlodgeQuestNr = 0;
						if(questData["lodge"][campaign]["nr"]!=newlodgeQuestNr){
							questData["lodge"][campaign]["nr"]=newlodgeQuestNr;
							if(questData["lodge"][campaign]["calcTo"]!=0){
								setCalcToQuest("lodge",campaign,0);
							}
						}
					}else{
						// quest available
/*
GM_log("initCampaignsResponse\ncampaign="+campaign+"\nresult[1][campaign]:\n"+print_r(result[1][campaign],"",true,"\n"));
[1]{1}{1}[0]{8} = 300
[1]{1}{1}[0]{6} = 2000
[1]{1}{entries}{1}[0]{productid} = 8
[1]{1}{entries}{1}[0]{sum} = 300
[1]{1}{entries}{1}[0]{type} = 1

[1]{1}{1}[0]{24} = 1800
[1]{1}{1}[1]{21} = 12
[1]{1}{1}[1]{41} = 10
[1]{1}{entries}{1}[0]{productid} = 24
[1]{1}{entries}{1}[0]{sum} = 1800
[1]{1}{entries}{1}[0]{type} = 1
[1]{1}{entries}{2}[0]{productid} = 21
[1]{1}{entries}{2}[0]{sum} = 12
[1]{1}{entries}{2}[0]{type} = 2
[1]{1}{entries}{2}[1]{productid} = 41
[1]{1}{entries}{2}[1]{sum} = 9
[1]{1}{entries}{2}[1]{type} = 2
*/
						// Time
						if(result[1][campaign]["remain"]){
							questData["lodge"][campaign]["time"] = now+result[1][campaign]["remain"];
						}else if(now<questData["lodge"][campaign]["time"]){
							questData["lodge"][campaign]["time"] = now;
						}
						// Given
						questData["lodge"][campaign]["given"] = new Object();
						if(result[1][campaign]["entries"]){
						for(var t in result[1][campaign]["entries"]){
							if(!result[1][campaign]["entries"].hasOwnProperty(t)){continue;}
							for(var i=0;i<result[1][campaign]["entries"][t].length;i++){
								var prod = result[1][campaign]["entries"][t][i]["productid"];
								var type = parseInt(t,10)-1;
								if(!questData["lodge"][campaign]["given"][type]){ questData["lodge"][campaign]["given"][type] = new Object(); }
								if(!questData["lodge"][campaign]["given"][type][prod]){ questData["lodge"][campaign]["given"][type][prod] = 0; }
								questData["lodge"][campaign]["given"][type][prod] += parseInt(result[1][campaign]["entries"][t][i]["sum"],10);
							}
						}
						}
						// Number
						var newlodgeQuestNr = parseInt(result[1][campaign]["questid"],10);
						if((questData["lodge"][campaign]["nr"]!=newlodgeQuestNr)||(typeof questData["lodge"][campaign]["nr"]!=typeof newlodgeQuestNr)){
							questData["lodge"][campaign]["nr"]=newlodgeQuestNr;
							if((0<questData["lodge"][campaign]["calcTo"])&&(questData["lodge"][campaign]["calcTo"]<questData["lodge"][1]["nr"])){
								setCalcToQuest("lodge",campaign,questData["lodge"][campaign]["nr"]);
							}
						}
						// Data
						calcQuestData("lodge",campaign);
					}
				}else{
					// all quests solved
					var newlodgeQuestNr = QUESTS["lodge"][campaign].length;
					if(questData["lodge"][campaign]["nr"]!=newlodgeQuestNr){
						questData["lodge"][campaign]["nr"]=newlodgeQuestNr;
						if(questData["lodge"][campaign]["calcTo"]!=0){
							setCalcToQuest("lodge",campaign,0);
						}
					}
				}
			}
			handleLodgeQuestLine();
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_questData",implode(questData));
			unsafeData.questData=questData.clone();
			//GM_log("onclick:"+$('forestry_quest_entry' + lodgeCampaignNr + '_' + questData["lodge"][1]["nr"] + '_1_6').onclick);

			//make prodName[1] && forestry_stock
				//GM_log("initCampaignsResponse bChanged:"+ bChanged+" prodName:"+implode(prodName));
			try{
				var store, fId, bChanged=false;
				prodStock[1]= new Object();
				for(store in result[3]){ //forestry_stock
					if (!result[3].hasOwnProperty(store)){ continue; }
					for(fId in result[3][store]){
						if (!result[3][store].hasOwnProperty(fId)){ continue; }
						// if (!prodName[1][fId]){
						// 	prodName[1][fId] = result[3][store][fId]["name"]; // set prodName[1]
						// 	//GM_log("initCampaignsResponse ADD prodName stock fId:"+fId+" name:"+prodName[1][fId]);
						// 	bChanged=true;
						// }
						if(!prodStock[1][fId]) prodStock[1][fId]=0;
						prodStock[1][fId] += parseInt(result[3][store][fId]["amount"],10);
					}
				}
				for(fId in prodName[1]){
					if (!prodName[1].hasOwnProperty(fId)){ continue; }
					if(!prodStock[1][fId]){ prodStock[1][fId]=0; }
				}
				store=null;fId=null;
				// GM_log("initCampaignsResponse bChanged:"+ bChanged+" prodName:"+implode(prodName));
				if(bChanged){
					prodName[1].sortObj();
					GM_setValueCache(LNG+"_"+SERVER+"_prodName",implode(prodName));
				}
				prodStock[1].sortObj();
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock));
			}catch(err){GM_log("ERROR initCampaignsResponse \n"+err);}
			updateProductDataForestry();
			calcProdMinRack();
			raiseEvent("gameOpenCampaign");
		}
	}catch(err){GM_log("ERROR initCampaignsResponse \n"+err);}
	};

	// newdiv = createElement("div",{"id":"lodgequestboxline"},$("garten_komplett"));
	function updateLodgeQuestLineTimer(campaign){
	try{
		if(now<questData["lodge"][campaign]["time"]){
			nodes["questline_lodge_"+campaign]["node"].children[1].innerHTML = getTimeStr(questData["lodge"][campaign]["time"]-now,false);
			window.setTimeout(updateLodgeQuestLineTimer,1000,campaign);
		}else{
			handleLodgeQuestLine();
		}
	}catch(err){GM_log("ERROR updateLodgeQuestLineTimer campaign="+campaign+"\n"+err);}
	}
	function handleLodgeQuestLine(){
	try{
		// GM_log("handleLodgeQuestLine"); //lodgequestboxline
		var newdiv;
		for(var campaign in QUESTS["lodge"]){
			if (!QUESTS["lodge"].hasOwnProperty(campaign)){ continue; }
			if(questData["lodge"][campaign]&&QUESTS["lodge"][campaign][questData["lodge"][campaign]["nr"]]){
				if(!nodes["questline_lodge_"+campaign]){ nodes["questline_lodge_"+campaign]=new Object(); }
				if(!nodes["questline_lodge_"+campaign]["node"]){
					nodes["questline_lodge_"+campaign]["node"]=createElement("div",{"id":"questboxlinecontent_lodge_"+campaign,"class":"link questboxlinecontent","style":"position:relative;padding:5px;"},$("questboxline"),title);
					nodes["questline_lodge_"+campaign]["node"].addEventListener("mouseover",function(event){
						showToolTip(event,questLineMouseOver("lodge",this.id.replace("questboxlinecontent_lodge_","")));
					},false);
					nodes["questline_lodge_"+campaign]["node"].addEventListener("click", function(){
						document.addEventListener("gameCity2",function(){
							document.removeEventListener("gameCity2",arguments.callee,false);
								click($("cityzone_2_9"));
						},false);
						click($top("speedlink_city2"));
					},false);
				}
				nodes["questline_lodge_"+campaign]["node"].innerHTML="";
				var title = "Forest-Quest "+campaign+"."+questData["lodge"][campaign]["nr"]; // TODO texte
				// $("forestry_questlist_item"+campaign+"_"+questData["lodge"][1]["nr"]).getElementsByClassName("forestry_questlist_item_title")[0].innerHTML.match(/\d+\. (.*)/i)[1];
				// if (title.length>12) title = title.substr(0,9)+"...";
				newdiv = createElement("div",{"class":"questlineicon1"},nodes["questline_lodge_"+campaign]["node"]);
				newdiv = createElement("div",{"style":"display:inline-block;margin-left:20px;"},nodes["questline_lodge_"+campaign]["node"],title);
				if(now<questData["lodge"][campaign]["time"]){
					updateLodgeQuestLineTimer(campaign);
				}
			}else{
				if(nodes["questline_lodge_"+campaign]&&nodes["questline_lodge_"+campaign]["node"]){
					removeElement(nodes["questline_lodge_"+campaign]["node"]);
				}
			}
		}
		newdiv=null;
	}catch(err){GM_log("ERROR handleLodgeQuestLine\ncampaign="+campaign+"\n"+err);}
	};
	handleLodgeQuestLine();
	//unsafeWindow.showQuests();

	// events city 1 ==============================================================================
	err_trace="events city 1";
	unsafeWindow._cityArrived=unsafeWindow.cityArrived;
	unsafeWindow.cityArrived = function(questbox){
		unsafeWindow._cityArrived(questbox);
		gameLocation=["city",unsafeWindow.city];
		unsafeData.gameLocation=gameLocation.clone();
		raiseEvent("gameCity"+unsafeWindow.city);
	};

	// Werbung
	unsafeWindow._fillAdColumn=unsafeWindow.fillAdColumn;
	unsafeWindow.fillAdColumn = function(){
		unsafeWindow._fillAdColumn();
		var images=$("adzonetooltip1").getElementsByTagName("img");

		if(LNG=="se"){
			$("adzonetooltip1").firstElementChild.innerHTML=$("adzonetooltip1").firstElementChild.innerHTML.replace(/\.(\d\d) /,",$1 ");
		}

		var preis=parseFloat(/&nbsp;(.*)/.exec($("adzonetooltip1").firstElementChild.innerHTML)[1].replace(regDelimThou,"").replace(regDelimDeci,"."),10);
		createElement("div",{},$("adzonetooltip1"),"<img width='12' height='12' src='"+images[0].getAttribute("src")+"'>/<img width='12' height='12' src='"+images[2].getAttribute("src")+"'>&nbsp;"+moneyFormatInt(preis/8));

		var preis=gut[0]*parseInt(/&nbsp;(\d*)/.exec($("adzonetooltip2").firstElementChild.innerHTML)[1],10);
		createElement("div",{},$("adzonetooltip2"),"<img width='12' height='12' src='"+images[0].getAttribute("src")+"'>/<img width='12' height='12' src='"+images[2].getAttribute("src")+"'>&nbsp;"+moneyFormatInt(preis/16));
		$("adzonetooltip2").firstElementChild.innerHTML +="&nbsp;("+moneyFormatInt(preis)+")";

		var preis=gut[0]*parseInt(/&nbsp;(\d*)/.exec($("adzonetooltip3").firstElementChild.innerHTML)[1],10);
		createElement("div",{},$("adzonetooltip3"),"<img width='12' height='12' src='"+images[0].getAttribute("src")+"'>/<img width='12' height='12' src='"+images[2].getAttribute("src")+"'>&nbsp;"+moneyFormatInt(preis/24));
		$("adzonetooltip3").firstElementChild.innerHTML +="&nbsp;("+moneyFormatInt(preis)+")";
		images=null;
	};

	// Marktschreier
	$("marktschreierinner").addEventListener ("DOMAttrModified", function(event){
		if ((this==event.target)&&(this.style.display == "block")){
			if(!$("marktschreierinnercontentBerater")){
				createElement("h1",{"id":"marktschreierinnercontentBerater","style":"display:none;"},$("marktschreierinnercontent"));
				for(var v=0;v<$("marktschreierinnercontent").childElementCount;v++){
					if($("marktschreierinnercontent").children[v].nodeName=="DIV"){
						var newdiv=$("marktschreierinnercontent").children[v].getElementsByTagName("div")[1];
						var player=(/\?to=(.*)';/).exec(newdiv.getElementsByTagName("img")[0].getAttribute("onclick"))[1];
						stats(player,newdiv);
						newdiv=null;
					}
				}
			}
		}
	},false);

	// Competition
	unsafeWindow._setCityWBWContentResponse=unsafeWindow.setCityWBWContentResponse;
	unsafeWindow.setCityWBWContentResponse = function(request){
		unsafeWindow._setCityWBWContentResponse(request);
		var result=checkRequest(request);
		if(result){
			window.setTimeout(function(){
				if(result[1]['open']==1){
					var product=parseInt(result[1]['wettbewerb_produkt'],10);
					GM_setValue(LNG+"_"+SERVER+"_competition",implode([product,result[1]['wettbewerb_ende']]));
				}else{
					var help=explode(GM_getValue(LNG+"_"+SERVER+"_competition","[]"),"setCityWBWContentResponse/competition",[]);
					if(help[1]==result[1]["wettbewerb_ende"]){
						var product=help[0];
					}else{
						var product=-1;
					}
				}
				if(product>-1){
					$('localwbwproduct').innerHTML='<div class="kp' + product + '" style="position:absolute; width:15px; height:15px;"></div>';
					$('localwbwproductname').innerHTML=prodName[0][product];
				}

				cand=document.querySelectorAll("#wbwcontent2ranking>div");
				var newdiv,c,sum=0;
				for(var v=1;v<cand.length;v++){
					newdiv=cand[v].getElementsByTagName("div");
					igm(newdiv[2].innerHTML.replace(/&nbsp;.*/,""),newdiv[2]);
					newdiv[newdiv.length-2].style.textAlign="right";
					c=parseInt(newdiv[newdiv.length-2].innerHTML,10);
					newdiv[newdiv.length-2].innerHTML=numberFormat(c);
					sum += c;
				}
				if(cand.length>1){ cand[1].style.borderBottom="1px solid black"; }
				if(cand.length>15){ cand[15].style.borderBottom="1px solid black"; }
				if(cand.length>50){ cand[50].style.borderBottom="1px solid black"; }
				newdiv=null;
				$("localwbwproductname").innerHTML += "&nbsp;("+sign_sum+"&nbsp;"+numberFormat(sum)+")";
				if(result[1]['open']!=1){
					nextproduct=parseInt(result[1]['wettbewerb_produkt'],10);
					if(nextproduct>0){
						$("localwbwproductname").innerHTML += "&nbsp;(&rarr;"+prodName[0][nextproduct]+"?)";
					}
				}
			},0);
		}
	};

	// events city 2 ==============================================================================
	err_trace="events city 2";
	if(unsafeWindow.cities&&(unsafeWindow.cities>1)){
		function doWindmill(){
			try{
				var zoneNrF="windmill";
				zoneTyp[zoneNrF]=zoneNrF;
				zoneBlock[zoneNrF]=false;
				//GM_log("doWindmill:city "+unsafeWindow.city+":"+unsafeWindow.cityzones[3]+":recipeName "+unsafeWindow.cityzones[4]+":"+unsafeWindow.windmilltime+":"+unsafeWindow.windmillrun);
				if(unsafeWindow.windmilltime>0){ // baking
					var tempZoneProductionData=[[],0,1,true];
					var iPrTyp=3;
					var iProd=prodId[iPrTyp][unsafeWindow.cityzones[4]];
					var iTime=unsafeWindow.windmilltime+now-unsafeWindow.Zeit.Verschiebung;
					tempZoneProductionData[0][iPrTyp]={};
					tempZoneProductionData[0][iPrTyp][iProd]=[[1,iTime,NEVER]];
					zoneProductionData[zoneNrF]=tempZoneProductionData.clone();
					processZoneProductionData(zoneNrF);
					var tempZoneProductionData=null;
				// else if(unsafeWindow.cityzones[3]==0)
				}else if(($("windmill_readyani"))&&($("windmill_readyani").style.display!="block")){ // empty
					zoneProductionData[zoneNrF]=[[],1,1,true];
					processZoneProductionData(zoneNrF);
					// TODO better conditions
				}else if(unsafeWindow.cityzones[4]!=""){ // baking done
					// if((zoneEndTimes[zoneNrF]==0)||(zoneEndTimes[zoneNrF]==NEVER)){ zoneEndTimes[zoneNrF]=now; }
					// zoneEndProducts[zoneNrF]=prodId[2][unsafeWindow.cityzones[4]];
				}
			}catch(err){ GM_log("ERROR doWindmill\n"+err); }
		}

		// arrival in city2
		document.addEventListener("gameCity2",function(){
			try{
			doWindmill();
/*
			//QUESTS["lodge"]["campaign"]["nr"][[type,id,amount],waittime,points,more|undefined]
			//more:
			//0,id of type 1 product
			//1,id of type 2 product
			//2,special name
			// Generate QUESTS["lodge"]
				var cand,camp,qnr,inf,maxi,help,help2, forest_quest=new Array(),foresty_prods_after_quest=new Object();
				var cells = $("forestry_questlist_container").querySelectorAll("div[id^=\"forestry_questlist_item\"]");
				for(var i=0;i<cells.length;i++){
					inf = cells[i].id.replace("forestry_questlist_item","").split("_");
					camp = inf[0];
					qnr = inf[1];
					if (!forest_quest[camp]) forest_quest[camp]= new Array();
					if (!forest_quest[camp][qnr]) forest_quest[camp][qnr]= [[],,0,[]];
					cand = $("forestry_quest_require"+camp+"_"+qnr);
					for(var k=0;k<cand.childElementCount;k=k+2){
						inf = cand.children[k].id.replace("forestry_quest_entry","").split("_");
						maxi = $("forestry_quest_amount_max"+camp+"_"+qnr+"_"+inf[2]+"_"+inf[3]).innerHTML;
						forest_quest[camp][qnr][0].push([parseInt(inf[2],10)-1,parseInt(inf[3],10),parseInt(maxi,10)]);
						//$("forestry_tt_"+camp+"_"+qnr+"_"+inf[2]+"_"+inf[3])
					}
					cand = $("forestry_quest_reward"+camp+"_"+qnr);
					for(var k=1;k<cand.childElementCount;k++){
						cand2 = cand.children[k];
						if(cand2.childElementCount==1){
							forest_quest[camp][qnr][3].push([2,cand2.children[0].innerHTML]);
						}else if(cand2.childElementCount==3){
							if(help = cand2.children[0].className.match(/kp(\d+)/i)){//Not used yet
								maxi = cand2.children[1].innerHTML.match(/&nbsp;(\d+)x ([A-z]*)/i);
								forest_quest[camp][qnr][3].push([0,parseInt(help[1],10),parseInt((maxi&&maxi[1]?maxi[1]:1),10)]);
							}else if(help = cand2.children[0].className.match(/f_m_symbol(\d+)/i)){
								maxi = cand2.children[1].innerHTML.match(/&nbsp;(\d+)x ([A-z]*)/i);
								forest_quest[camp][qnr][3].push([1,parseInt(help[1],10),parseInt((maxi&&maxi[1]?maxi[1]:1),10)]);
								foresty_prods_after_quest[parseInt(help[1],10)]= qnr;
							}else if(help=cand2.children[1].innerHTML.match(/\&nbsp;(\d+)\&nbsp;punten/i)){
								forest_quest[camp][qnr][2]=parseInt(help[1],10);
							}else{
								forest_quest[camp][qnr][3].push([2,cand2.children[1].innerHTML]);
							}
						}
					}
				}
				cells=null;cand=null;inf=null;help=null;cand2=null;
				GM_log("forest_quest"+implode(forest_quest));
				GM_log("foresty_prods_after_quest"+implode(foresty_prods_after_quest));
*/

			//make forestry naming
			/*
				var cand,camp,qnr,inf,maxi,help,help2,bChanged=false;
				var cells = $("forestry_questlist_container").querySelectorAll("div[id^=\"forestry_questlist_item\"]");
				for(var i=0;i<cells.length;i++){
					inf = cells[i].id.replace("forestry_questlist_item","").split("_");
					camp = inf[0];
					qnr = inf[1];
					cand = $("forestry_quest_require"+camp+"_"+qnr);
					for(var k=0;k<cand.childElementCount;k=k+2){
						inf = cand.children[k].id.replace("forestry_quest_entry","").split("_");
						if(inf[2]==2){
							prodName[1][inf[3]] = $("forestry_tt_"+camp+"_"+qnr+"_"+inf[2]+"_"+inf[3]).innerHTML; // set prodName[1]
							//GM_log("gameCity2 ADD prodName quest1 fId:"+inf[3]+" name:"+prodName[1][inf[3]]);
							bChanged=true;
						}
					}
					cand = $("forestry_quest_reward"+camp+"_"+qnr);
					for(var k=0;k<cand.childElementCount;k=k+2){
						inf = cand.children[k].id.replace("forestry_quest_entry","").split("_");
						if(inf[2]==2){
							prodName[1][inf[3]] = $("forestry_tt_"+camp+"_"+qnr+"_"+inf[2]+"_"+inf[3]).innerHTML; // set prodName[1]
							//GM_log("gameCity2 ADD prodName quest2 fId:"+inf[3]+" name:"+prodName[1][inf[3]]);
							bChanged=true;
						}
					}
					cand = $("forestry_quest_reward"+camp+"_"+qnr);
					for(var k=1;k<cand.childElementCount;k++){
						cand2 = cand.children[k];
						if(cand2.childElementCount==3){
							if(help = cand2.children[0].className.match(/f_m_symbol(\d+)/i)){
								maxi = cand2.children[1].innerHTML.match(/&nbsp;((\d+)?x?\s?)?(.*)/i); //OLD &nbsp;((\d+)x\s)?([A-z\s]*)/i);
								if(maxi[3]){
									prodName[1][help[1]] = maxi[3]; // set prodName[1]
									//GM_log("gameCity2 ADD prodName quest3 fId:"+help[1]+" name:"+prodName[1][help[1]]+" maix:"+implode(maxi));
									bChanged=true;
								}
							}
						}
					}
				}

				cells=null;cand=null;inf=null;help=null;
				//GM_log("gameCity2 bChanged:"+ bChanged+" prodName:"+implode(prodName));
				if(bChanged){
					prodName[1].sortObj();
					GM_setValueCache(LNG+"_"+SERVER+"_prodName",implode(prodName));
				}
				*/
			}catch(err){GM_log("ERROR city2 \n"+err+"\n"+cand.innerHTML);}
		},false);
		// open windmill
		unsafeWindow._initWindmillResponse=unsafeWindow.initWindmillResponse;
		unsafeWindow.initWindmillResponse = function(request){
			unsafeWindow._initWindmillResponse(request);
			var result=checkRequest(request);

			if(result){
				doWindmill();
				if(result[0]!=0&&result[1]){
					for(var i=0;i<prodStock[2].length;i++){
						prodStock[2][i]=0;
					}				
					for(var i in result[1]){
						if(!result[1].hasOwnProperty(i)){continue;}
						prodStock[2][parseInt(i,10)]=parseInt(result[1][i]["amount"],10);
					}
				}
				//updateProductDataWindmill();
				unsafeData.prodStock = prodStock.clone();
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock,"initWindmillResponse\prodStock"));
				raiseEvent("gameOpenWindmill");
			}
		};
		// start baking
		unsafeWindow._startWindmillProductionResponse=unsafeWindow.startWindmillProductionResponse;
		unsafeWindow.startWindmillProductionResponse = function(request){
			unsafeWindow._startWindmillProductionResponse(request);
			if(checkRequest(request)){
				doWindmill();
			}
		};
		// cancel baking
		unsafeWindow._cancelWindmillProductionResponse=unsafeWindow.cancelWindmillProductionResponse;
		unsafeWindow.cancelWindmillProductionResponse = function(request){
			unsafeWindow._cancelWindmillProductionResponse(request);
			if(checkRequest(request)){
				doWindmill();
			}
		};

		// Recipedealer
		document.addEventListener("gameUpdateFormuladealerOffers", function(event){
			var newdiv,newtable,newtr,newtd;
			for(var v=1;v<4;v++){
				newdiv=$("formuladealerproduct"+v);
				newdiv.setAttribute("class","");

				newdiv=newdiv.getElementsByTagName("div")[0];
				var str=newdiv.getAttribute("class");
				newdiv.setAttribute("class","link "+str);
				var formula=parseInt(str.replace("fm",""),10);

				newdiv=$("formuladealerproduct"+v+"berater");
				if(newdiv){
					newdiv.innerHTML="";
				}else{
					newdiv=createElement("div",{"id":"formuladealerproduct"+v+"berater","class":"blackbox","style":"position:absolute;top:70px;"},$("formuladealerproduct"+v));
				}
				var sum=0;

				newtable=createElement("table",{"cellspacing":"0","style":"text-align:right;"},newdiv);
				newtr=createElement("tr",{"class":"hoverBgCc9"},newtable);
				newtr.addEventListener("mouseover",function(event){ showToolTip(event,texte["preis"]); },false);
				createElement("td",{},newtr,"-");
				newtd=createElement("td",{},newtr);
				if(unsafeWindow.formulas[0][formula][6]>0){
					newtd.innerHTML=numberFormat(unsafeWindow.formulas[0][formula][6]);
					sum -= unsafeWindow.formulas[0][formula][6];
				}else if(unsafeWindow.formulas[0][formula][7]>0){
					newtd.innerHTML=numberFormat(unsafeWindow.formulas[0][formula][7]*gut[0]);
					sum -= unsafeWindow.formulas[0][formula][7]*gut[0];
				}
				var sum1=0;
				str='<table class="white">';
				str += '<tr><th colspan="4" style="border-bottom:1px solid white">'+texte["ingredients"]+'</th></tr>';
				for(var w=0;w<unsafeWindow.formulas[0][formula][3].length;w++){
					sum1 += unsafeWindow.formulas[0][formula][3][w][1]*gut[unsafeWindow.formulas[0][formula][3][w][0]];
					str += '<tr><td>'+produktPic(0,unsafeWindow.formulas[0][formula][3][w][0],createElement("div")).parentNode.innerHTML+'</td>';
					str += '<td style="text-align:right;">'+numberFormat(unsafeWindow.formulas[0][formula][3][w][1])+'&nbsp;'+sign_mult+'</td>';
					str += '<td style="text-align:right;">'+moneyFormat(gut[unsafeWindow.formulas[0][formula][3][w][0]])+'&nbsp;=</td>';
					str += '<td style="text-align:right;">'+moneyFormatInt(unsafeWindow.formulas[0][formula][3][w][1]*gut[unsafeWindow.formulas[0][formula][3][w][0]])+'</td></tr>';
				}
				str += '</table>';

				newtr=createElement("tr",{"class":"hoverBgCc9","mouseOverText":str},newtable);
				newtr.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseOverText")); },false);
				createElement("td",{},newtr,"-");
				createElement("td",{},newtr,numberFormat(sum1));
				sum -= sum1;

				if(unsafeWindow.formulas[0][formula][5][0]!=0){
					sum1=unsafeWindow.formulas[0][formula][5][0][1]*gut[unsafeWindow.formulas[0][formula][5][0][0]];
					sum += sum1;
					str='<table class="white">';
					str += '<tr><th colspan="3" style="border-bottom:1px solid white">'+texte["gain"]+'</th></tr>';
					str += '<tr><td>'+produktPic(0,unsafeWindow.formulas[0][formula][5][0][0],createElement("div")).parentNode.innerHTML+'</td>';
					str += '<td style="text-align:right;">'+numberFormat(unsafeWindow.formulas[0][formula][5][0][1])+'&nbsp;'+sign_mult+'</td>';
					str += '<td style="text-align:right;">'+moneyFormat(gut[unsafeWindow.formulas[0][formula][5][0][0]])+'</td>';
					str += '</table>';
					newtr=createElement("tr",{"class":"hoverBgCc9","mouseOverText":str},newtable);
					newtr.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseOverText")); },false);
					createElement("td",{},newtr,"+");
					createElement("td",{},newtr,numberFormat(sum1));
				}
				if(unsafeWindow.formulas[0][formula][5][1]!=0){
					var c=0;
					for(var i=1;i<ALL_ZONES["farm"].length;i++){
						var zoneNr=ALL_ZONES["farm"][i];
						if((!zoneBlock[zoneNr])&&(zoneTyp[zoneNr]==1)){
							c += Math.ceil(calcGrowTimes(60*prodGrowTime[0][unsafeWindow.formulas[0][formula][5][1][0]],unsafeWindow.formulas[0][formula][5][1][2],1-(zoneBonus[zoneNr]/100)))*120/prodPlantSize[0][unsafeWindow.formulas[0][formula][5][1][0]];
						}
					}
					sum1=c*unsafeWindow.formulas[0][formula][5][1][1]*gut[unsafeWindow.formulas[0][formula][5][1][0]];
					sum += sum1;
					str='<table class="white">';
					str += '<tr><th colspan="4" style="border-bottom:1px solid white">'+texte["gain"]+'</th></tr>';
					str += '<tr><td>'+produktPic(0,unsafeWindow.formulas[0][formula][5][1][0],createElement("div")).parentNode.innerHTML+'</td>';
					str += '<td style="text-align:right;">'+numberFormat(c)+'&nbsp;'+sign_mult+'</td>';
					str += '<td style="text-align:right;">'+numberFormat(unsafeWindow.formulas[0][formula][5][1][1])+'&nbsp;'+sign_mult+'</td>';
					str += '<td style="text-align:right;">'+moneyFormat(gut[unsafeWindow.formulas[0][formula][5][1][0]])+'</td>';
					str += '</table>';
					newtr=createElement("tr",{"class":"hoverBgCc9","mouseOverText":str},newtable);
					newtr.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseOverText")); },false);
					createElement("td",{},newtr,"+");
					createElement("td",{},newtr,numberFormat(sum1));
				}

				newtr=createElement("tr",{},newtable);
				createElement("td",{"colspan":"2","style":"border-top:1px solid black;"},newtr,numberFormat(sum));
				if(unsafeWindow.formulas[0][formula][5][2]!=0){
					var c=0;
					for(var i=1;i<ALL_ZONES["farm"].length;i++){
						var zoneNr=ALL_ZONES["farm"][i];
						if((!zoneBlock[zoneNr])&&(zoneTyp[zoneNr]==1)){
						c += Math.ceil(calcGrowTimes(60*prodGrowTime[0][unsafeWindow.formulas[0][formula][5][2][0]],unsafeWindow.formulas[0][formula][5][2][2],1-(zoneBonus[zoneNr]/100)))*120/prodPlantSize[0][unsafeWindow.formulas[0][formula][5][2][0]];
						}
					}
					sum1=c*unsafeWindow.formulas[0][formula][5][2][1];
					str='<table class="white">';
					str += '<tr><th colspan="2" style="border-bottom:1px solid white">'+texte["punkte"]+'</th></tr>';
					str += '<tr><td style="text-align:right;">'+numberFormat(c)+'&nbsp;'+sign_mult+'</td>';
					str += '<td style="text-align:right;">'+pointsFormat(unsafeWindow.formulas[0][formula][5][2][1],"span",createElement("div")).parentNode.innerHTML+'</td>';
					str += '</table>';
					newtr=createElement("tr",{"class":"hoverBgCc9","mouseOverText":str},newtable);
					newtr.addEventListener("mouseover",function(event){ showToolTip(event,this.getAttribute("mouseOverText")); },false);
					newtd=createElement("td",{"colspan":"2"},newtr);
					pointsFormat(sum1,"div",newtd);
				}

				newtr=createElement("tr",{"class":"hoverBgCc9"},newtable);
				newtd=createElement("td",{"colspan":"2"},newtr);
				pointsFormat(unsafeWindow.formulas[0][formula][8],"div",newtd);
			}

			// Powerups
			if(unsafeWindow.powerupcontent){
				newdiv=$("powerups");
				if(newdiv){
					newdiv.innerHTML="";
				}else{
					createElement("div",{id:"powerupsbackground",style:"background-color:black;width:560px;right:0;opacity:0.5;position:absolute;bottom:0;height:80px;"},$("formuladealer"));
					newdiv=createElement("div",{id:"powerups",style:"height:80px;bottom:0;right:0;position:absolute;vertical-align:top;"},$("formuladealer"));
				}
				var newRID;
				for(var v=0;v<unsafeWindow.powerupcontent.length;v++){
					aMount=parseInt(unsafeWindow.powerupcontent[v]["rack"],10);
					rId=parseInt(unsafeWindow.powerupcontent[v][0],10);
					newRID=createElement("div",{onmouseout:"$('formuladealerproductinfo').innerHTML=''; hideDiv('formuladealerproductinfo');",onmouseover:"$('formuladealerproductinfo').innerHTML=showFormulaInfos("+rId+"); showDiv('formuladealerproductinfo');",style:"height: 25px; width: 25px; position: relative; margin-top: 7px; float: right; margin-right: 10px;"});
					newdiv.insertBefore(newRID, newdiv.firstElementChild);
					createElement("div", {"class":"fmm"+rId},newRID);
					createElement("div", {style:"position:absolute;bottom:-2px;right:-2px;font-weight:normal;color:white;"},newRID,aMount);
				}
				newRID=null;
			}
			newdiv=null;newtable=null;newtr=null;newtd=null;
		},false);
		unsafeWindow._setFormulaDealerFormulas=unsafeWindow.setFormulaDealerFormulas;
		unsafeWindow.setFormulaDealerFormulas = function(){
			unsafeWindow._setFormulaDealerFormulas();
			raiseEvent("gameUpdateFormuladealerOffers");
		};
		unsafeWindow._setFormulaDealerRack=unsafeWindow.setFormulaDealerRack;
		unsafeWindow.setFormulaDealerRack = function(rack){
			unsafeWindow._setFormulaDealerRack(rack);
			for(var i=0;i<prodStock[2].length;i++){
				prodStock[2][i]=0;
			}
			for(var i=0;i<rack.length;i++){
				prodStock[2][parseInt(rack[i]["fid"],10)]=parseInt(rack[i]["amount"],10);
			}
			unsafeData.prodStock = prodStock.clone();
			GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_prodStock",implode(prodStock,"setFormulaDealerRack\prodStock"));
			raiseEvent("gameUpdateFormuladealerRack");
		};

		// Windmill Recipe Submit
		$("windmillpaper").addEventListener("DOMAttrModified",function(event){
			if($("windmillpaper").style.display=="block"){
				if(!$("windmillpaperBerater")){
					createElement("h1",{"id":"windmillpaperBerater","style":"display:none;"},$("windmillpaperheadline"));
					var low=false,currAmount,currProd;
					var cand;
					for(var v=0;v<3;v++){
						cand=$("windmillproduct"+v);
						currProd=/l(\d+)/.exec(cand.getAttribute("class"))[1];
						currAmount=parseInt(cand.getElementsByTagName("div")[0].innerHTML,10);
						if(prodStock[0][currProd]-currAmount<prodMinRack[0][currProd]){ low=true;break; }
					}
					cand=null;
					if(low){
						createElement("div",{"class":"blackbox alertbox","style":"position:absolute;left:20px;top:20px;"},$("windmillproduction"),texte["alertWillLowRack"]);
					}
				}
			}
		},false);

		// Lottery
		// lotteryLog[day]=[id of daily lot,exchanged products|null|undefined,id's of bought lots|undefined]
		if($top("lotterycontainer")){
			function blinkGoToLottery(){
				if(nodes["goToLottery"]&&nodes["goToLottery"]["node"]){
					nodes["goToLottery"]["node"].style.opacity=(nodes["goToLottery"]["node"].style.opacity=="1"?"0.3":"1");
					window.setTimeout(function(){ blinkGoToLottery(); },500);
				}
			}
			function showGoToLottery(){
				nodes["goToLottery"]=new Object();
				nodes["goToLottery"]["node"]=createElement("div",{"id":"divGoToLottery","class":"link","style":"height:70px;width:70px;background:url('"+GFX+"city/city2_back2.jpg') 440px 430px;border:2px solid black;border-radius:35px;margin-bottom:5px;opacity:1;","mouseOverText":texte["goToLottery"]},$("fixedDivRight"));
				nodes["goToLottery"]["node"].addEventListener("mouseover",function(event){ showToolTip(event,texte["goToLottery"]); },false);
				nodes["goToLottery"]["node"].addEventListener("click",function(event){ showLottery(); },false);
				blinkGoToLottery(1);
				raiseEvent("gameLotteryDailyLotAvailable");
			}
			if(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLastLot")!=todayStr){ showGoToLottery(); }

			function hideGoToLottery(){
				GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLastLot",todayStr);
				if(nodes["goToLottery"]){
					if(nodes["goToLottery"]["node"]){ removeElement(nodes["goToLottery"]["node"]); }
					delete nodes["goToLottery"];
				}
			}

			unsafeWindow._updateLotRack=unsafeWindow.updateLotRack;
			unsafeWindow.updateLotRack = function(){
				unsafeWindow._updateLotRack();
				window.setTimeout(function(){
					try{
					if(unsafeData.lotteryCollectForPrize){
						var lotteryCollectForPrize=unsafeData.lotteryCollectForPrize.clone();
					}else{
						var lotteryCollectForPrize=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryCollectForPrize", "{}"),"updateLotRack/lotteryCollectForPrize",{});
					}
					if (!lotteryCollectForPrize["total"]){ lotteryCollectForPrize["total"]=new Array(); }
					var newdiv;
					var lrack=$("lotsrack");
					for(var v=0;v<lrack.childElementCount;v++){
						var lotid=lrack.children[v].style.backgroundImage.match(/lot_(\d+).png/i)[1];
						if (!lotteryCollectForPrize["total"][lotid]){ lotteryCollectForPrize["total"][lotid]=0; }
						//if (!$("lotlack"+lotid)){
						newdiv=createElement("div",{"id":"lotlack"+lotid,"style":"position:absolute;right:8px;top:5px;font-size:14px;font-weight:bold;color:#fff;padding:2px;"},lrack.children[v]);
						var help=(unsafeWindow.lotrack[lotid]?unsafeWindow.lotrack[lotid]:0)-lotteryCollectForPrize["total"][lotid];
						if(help<=0){
							newdiv.innerHTML=help;
							newdiv.style.backgroundColor="#AA0000";
						}else{
							newdiv.innerHTML="+"+help;
							newdiv.style.backgroundColor="green";
						}
					}
					lrack=null;
					newdiv=null;

					}catch(err){GM_log("updateLotRack error:"+err);}
				},0);
			};
			unsafeWindow._updateLotteryPrizes=unsafeWindow.updateLotteryPrizes;
			unsafeWindow.updateLotteryPrizes = function(item){
				unsafeWindow._updateLotteryPrizes(item);
				window.setTimeout(function(){
					if(unsafeData.lotteryCollectForPrize){
						var lotteryCollectForPrize=unsafeData.lotteryCollectForPrize.clone();
					}else{
						var lotteryCollectForPrize=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryCollectForPrize", "{}"),"updateLotteryPrizes/lotteryCollectForPrize",{});
					}
					// delete collecting of missing prizes
					for(var v in lotteryCollectForPrize){
						if(!lotteryCollectForPrize.hasOwnProperty(v)){ continue; }
						if(isNaN(v)){ continue; }
						if(!unsafeWindow.lotteryprizes[v]){
							lotteryCollectForPrize[v]=false;
							//Calc new totals
							lotteryCollectForPrize["total"]=new Array();
							for(var prizeId in unsafeWindow.lotteryprizes){
								if(!unsafeWindow.lotteryprizes.hasOwnProperty(prizeId)){ continue; }
								if (lotteryCollectForPrize[prizeId]){
									for(var v in unsafeWindow.lotteryprizes[prizeId][1]){
										if(!unsafeWindow.lotteryprizes[prizeId][1].hasOwnProperty(v)){ continue; }
										var flid=unsafeWindow.lotteryprizes[prizeId][1][v][0];
										if (!lotteryCollectForPrize["total"][flid]) lotteryCollectForPrize["total"][flid]=0;
										lotteryCollectForPrize["total"][flid] += unsafeWindow.lotteryprizes[prizeId][1][v][1];
										flid=null;
									}
									v=null;
								}
							}
						}
					}

					var divLotteryprizes=$("lotteryprizes");
					var cell;
					for(var v=0;v<divLotteryprizes.childElementCount;v++){
						if(!divLotteryprizes.children[v].id.match(/lotteryprize\d+/)){ continue; }
						var prizeId=parseInt(divLotteryprizes.children[v].id.replace("lotteryprize",""),10);
						if (lotteryCollectForPrize[prizeId]==undefined){ lotteryCollectForPrize[prizeId]=false; }
						cell=createElement("input",{"id":"inputLotteryCollectForPrize"+prizeId,"class":"link","type":"checkbox","checked":lotteryCollectForPrize[prizeId],"style":"position:absolute;top:35px;left:10px;"},divLotteryprizes.children[v].firstElementChild);
						cell.addEventListener("click",function(){
							var prizeId=parseInt(this.id.replace("inputLotteryCollectForPrize",""),10);
							var lotteryCollectForPrize=unsafeData.lotteryCollectForPrize.clone();
							lotteryCollectForPrize[prizeId]=this.checked;

							//Calc new totals
							lotteryCollectForPrize["total"]=new Array();
							for(var prizeId in unsafeWindow.lotteryprizes){
								if(!unsafeWindow.lotteryprizes.hasOwnProperty(prizeId)){ continue; }
								if (lotteryCollectForPrize[prizeId]){
									for(var v in unsafeWindow.lotteryprizes[prizeId][1]){
										if(!unsafeWindow.lotteryprizes[prizeId][1].hasOwnProperty(v)){ continue; }
										var flid=unsafeWindow.lotteryprizes[prizeId][1][v][0];
										if (!lotteryCollectForPrize["total"][flid]) lotteryCollectForPrize["total"][flid]=0;
										lotteryCollectForPrize["total"][flid] += unsafeWindow.lotteryprizes[prizeId][1][v][1];
										flid=null;
									}
									v=null;
								}
							}
							prizeId=null;
							lotteryCollectForPrize.sortObj();
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryCollectForPrize", implode(lotteryCollectForPrize));
							unsafeData.lotteryCollectForPrize=lotteryCollectForPrize.clone();
							unsafeWindow.updateLotRack();
						},false);
						// position:absolute; top:0px; left:0px; width:40px; height:40px;
						// mouseover-div
						cell=divLotteryprizes.children[v].children[1].firstElementChild;
						for(var w=0;w<unsafeWindow.lotteryprizes[prizeId][1].length;w++){
							var help=(unsafeWindow.lotrack[unsafeWindow.lotteryprizes[prizeId][1][w][0]]?unsafeWindow.lotrack[unsafeWindow.lotteryprizes[prizeId][1][w][0]]:0);
							// cell.children[w].children[1].innerHTML += "<br>"+help;
							help=Math.min(100,Math.round(100*help/unsafeWindow.lotteryprizes[prizeId][1][w][1]));
							createElement("div",{"style":"position:absolute;top:0;left:0;height:5px;width:"+help+"%;background:green;"},cell.children[w]);
							createElement("div",{"style":"position:absolute;top:0;right:0;height:5px;width:"+(100-help)+"%;background:#c00;"},cell.children[w]);
						}
					}
					divLotteryprizes=null;
					cell=null;
					unsafeData.lotteryCollectForPrize=lotteryCollectForPrize.clone();
				},0);
			};
			unsafeWindow._initLotteryResponse=unsafeWindow.initLotteryResponse;
			unsafeWindow.initLotteryResponse = function(request){
				unsafeWindow._initLotteryResponse(request);
				var result=checkRequest(request);
				if(result){
					window.setTimeout(function(){
						try{
							// [1(isOk), [...](lotrack), 1(dailyLotTaken), 0(id), {...}(lotteryprizes), 0(won products)]
							if(result[2]!=0){
								hideGoToLottery();
							}
							// Log-Button
							var button=createElement("button",{"class":"link","style":"position:absolute;bottom:120px;right:30px;"},$("lotterycontainer"),texte["lotteryLog"]);
							button.addEventListener("click",function(){ buildInfoPanel("lotteryLog"); },false);
							button=null;
							//unsafeWindow.updateLotRack();
						}catch(err){GM_log("initLotteryResponse error:"+err);}
						raiseEvent("gameLotteryOpen");
					},0);
				}
			};
			unsafeWindow._dailyLotResponse=unsafeWindow.dailyLotResponse;
			unsafeWindow.dailyLotResponse = function(request){
				unsafeWindow._dailyLotResponse(request);
				var result=checkRequest(request);
				if(result){
					//GM_log("dailyLotResponse: "+implode(result));
					hideGoToLottery();
					window.setTimeout(function(){
						var lotteryLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog","{}"),"dailyLotResponse/lotteryLog",{});
						if(lotteryLog[todayStr]==undefined){ lotteryLog[todayStr]=[null]; }
						lotteryLog[todayStr][0]=result[3];
						GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog",implode(lotteryLog));
						raiseEvent("gameLotteryGotDailyLot");
					},0);
				}
			};
			unsafeWindow._showLotDecision=unsafeWindow.showLotDecision;
			unsafeWindow.showLotDecision = function(lotid){
				//GM_log("showLotDecision: "+lotid);
				unsafeWindow._showLotDecision(lotid);
				window.setTimeout(function(){
					if(unsafeData.lotteryCollectForPrize){
						var lotteryCollectForPrize=unsafeData.lotteryCollectForPrize.clone();
					}else{
						var lotteryCollectForPrize=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryCollectForPrize", "{}"),"showLotDecision/lotteryCollectForPrize",{});
					}
					if(!lotteryCollectForPrize["total"]){ lotteryCollectForPrize["total"]=new Array(); }
					if(!lotteryCollectForPrize["total"][lotid]){ lotteryCollectForPrize["total"][lotid]=0; }
					var newdiv=createElement("div",{"id":"currentlotAdvise","style":"position:absolute;right:8px;top:5px;font-size:14px;font-weight:bold;color:#fff;padding:2px;"},$("currentlot"));
					var help=(unsafeWindow.lotrack[lotid]?unsafeWindow.lotrack[lotid]:0)-lotteryCollectForPrize["total"][lotid];
					if(help<=0){
						newdiv.innerHTML=help;
						newdiv.style.backgroundColor="#AA0000";
					}else{
						newdiv.innerHTML="+"+help;
						newdiv.style.backgroundColor="green";
					}
					newdiv=null;

					raiseEvent("gameLotteryGotLot");
				},0);
			};
			unsafeWindow._lotGetPrizeResponse=unsafeWindow.lotGetPrizeResponse;
			unsafeWindow.lotGetPrizeResponse = function(request){
				unsafeWindow._lotGetPrizeResponse(request);
				var result=checkRequest(request);
				if(result){
					//GM_log("lotGetPrizeResponse: "+implode(result));
					if(result[5]){
						window.setTimeout(function(){
							var lotteryLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog","{}"),"lotGetPrizeResponse/lotteryLog",{});
							if(lotteryLog[todayStr]==undefined){ lotteryLog[todayStr]=[null,null]; }
							lotteryLog[todayStr][1]=result[5];
							lotteryLog[todayStr][1].sortObj(sortObjFunctions["productId"]);
							raiseEvent("gameLotteryGotPrize");
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog",implode(lotteryLog));
						},0);
					}
				}
			};
			unsafeWindow._buyNewLotResponse=unsafeWindow.buyNewLotResponse;
			unsafeWindow.buyNewLotResponse = function(request){
				unsafeWindow._buyNewLotResponse(request);
				var result=checkRequest(request);
				if(result){
					//GM_log("buyNewLotResponse: "+implode(result));
					if(result[5]){
						window.setTimeout(function(){
							var lotteryLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog","{}"),"buyNewLotResponse/lotteryLog",{});
							if(lotteryLog[todayStr]==undefined){ lotteryLog[todayStr]=[null,null,null]; }
							if(!lotteryLog[todayStr][2]){ lotteryLog[todayStr][2]=[]; }
							lotteryLog[todayStr][2].push(result[3]);
							raiseEvent("gameLotteryGotPrize");
							GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lotteryLog",implode(lotteryLog));
						},0);
					}
				}
			};
		}
	}

	// on load execute ============================================================================
	err_trace="on load execute";
	newdiv1=$("buildingmain");
	var newdiv2;
	for(var zoneNr=1;zoneNr<=6;zoneNr++){
		newdiv=$("zone"+zoneNr);
		newdiv.addEventListener("mouseout",function(){
			hideBlase();
			$("lager_zeit_ziel").parentNode.style.display="none";
			if((prodTyp[0][unsafeWindow.selected]=="v")&&(unsafeWindow.mode==0)&&(unsafeWindow.rackElement[unsafeWindow.selected])){
				$("lager_zeit").innerHTML=getTimeStr(60*prodGrowTime[0][unsafeWindow.selected])+"&nbsp;"+texte["stunden"];
			}
		},false);
		newdiv.addEventListener("mouseover",function(){
			showBlase(parseInt(this.id.replace("zone",""),10)+(6*gameLocation[1]));
		},true);

		makeZoneTimers(zoneNr,"zonetimer","position:absolute;top:"+(newdiv.offsetTop-16)+"px;left:"+newdiv.offsetLeft+"px;",newdiv1);
		makeZoneTimers(zoneNr,"zoneTimerWater","position:absolute;top:"+(newdiv.offsetTop-16)+"px;right:"+(newdiv1.offsetWidth-newdiv.offsetLeft-newdiv.offsetWidth-15)+"px;",newdiv1);
	}

	doGameFarmSwitch();
	calcFarmiCost();
	calcTotalFarmis();
	calcProdMinRackInit(); // this calls finally doBuyNotepad, doFarmis
	//doFarmis();
	saveProductData();
	if(unsafeWindow.showQuests){ //FastFix2012/01/18
		unsafeWindow.showQuests(); //TODO review
	}

	for(var zoneNr=1;zoneNr<7;zoneNr++){
		if($("zone"+zoneNr).childElementCount>0){ doZone(zoneNr); } // zone is already filled
	}

	if(LNG=="se"){ $("bar").innerHTML=$("bar").innerHTML.replace(/\.(\d\d) /,",$1 "); }
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_bargeld",$("bar").innerHTML.replace(" "+texte["waehrung"],"").replace(regDelimThou,"").replace(regDelimDeci,"."));

	// windmill timer
	if(unsafeWindow.cities&&(unsafeWindow.cities>1)){
		makeZoneTimers("globalWindmill","zonetimer","position:relative;",$("timeHolder"));
	}
	if(unsafeWindow.forestry_unlock!=undefined){
		makeZoneTimers("globalForest","zonetimer","position:relative;",$("timeHolder"));
		if(zoneBonus["forest"]>0){ makeZoneTimers("globalForest","zoneTimerWater","position:relative;",$("timeHolder")); }
		makeZoneTimers("globalSawmill","zonetimer","position:relative;",$("timeHolder"));
		makeZoneTimers("globalCarpentry","zonetimer","position:relative;",$("timeHolder"));
	}
	makeZoneTimers("globalFoodworld-1","zonetimer","position:relative;",$("timeHolder"));
	makeZoneTimers("globalFoodworld-2","zonetimer","position:relative;",$("timeHolder"));

	// looping ====================================================================================
	err_trace="looping";
	function loop1(){
		try{
		//timeMeasureStart("loop1");	
		// test session
		if (unsafeWindow.rid!=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_session","")){ unsafeWindow.initZones(1); }
		else{ GM_setValue2(LNG+"_"+SERVER+"_sessionlost",false,74); }

		now=Math.floor((new Date()).getTime()/1000);
		todayStr=getDateStr(now,2,false);
		nowServerOff=unsafeWindow.Zeit.Server+valServerTimeOffset;
		var help=getDateStr(nowServerOff,2,false);
		if(help!=todayServerStr){
			todayServerStr=help;
			getDailyRanking();
			showGoToLottery();
			raiseEvent("gameNewDay");
		}

		// clock
		nodes["serverTime"]["node"].innerHTML=todayServerStr+"&nbsp;"+getDaytimeStr(nowServerOff);
		if(valSessionEndtime){ nodes["sessionTimeLeft"]["node"].innerHTML="("+getTimeStr(valSessionEndtime-now)+")"; }
		if(DEVMODE){ nodes["sessionTimeNow"]["node"].innerHTML="("+getDaytimeStr(now)+")"; }

		// powerupsymbols
		for(var v=nodes["containerPowerupSymbols"]["node"].childElementCount-1;v>=0;v--){
			help=parseInt(nodes["containerPowerupSymbols"]["node"].children[v].getAttribute("end"),10)-unsafeWindow.Zeit.Server;
			if(help>0){ nodes["containerPowerupSymbols"]["node"].children[v].lastElementChild.innerHTML=getTimeStr(help); }
			else{ removeElement(nodes["containerPowerupSymbols"]["node"].children[v]); }
		}
		// global timers
		if(!zoneBlock["windmill"]){ updateZoneTimer("globalWindmill","windmill"); }
		if(!zoneBlock["forest"]){ updateZoneTimer("globalForest","forest"); }
		if(!zoneBlock["sawmill"]){ updateZoneTimer("globalSawmill","sawmill"); }
		if(!zoneBlock["carpentry"]){ updateZoneTimer("globalCarpentry","carpentry"); }
		if(!zoneBlock["foodworld-1"]){ updateZoneTimer("globalFoodworld-1","foodworld-1"); }
		if(!zoneBlock["foodworld-2"]){ updateZoneTimer("globalFoodworld-2","foodworld-2"); }
		// visible timers
		switch(gameLocation[0]){
		case "farm":
			for(var zoneNr=1;zoneNr<=6;zoneNr++){
				if(DATA_zones[zoneNr+6*gameLocation[1]]&&(!zoneBlock[zoneNr+6*gameLocation[1]])){
					updateZoneTimer(zoneNr,zoneNr+6*gameLocation[1]);
				}else{
					hideZoneTimer(zoneNr,"zonetimer");
					hideZoneTimer(zoneNr,"zoneTimerWater");
				}
			}
		break;
		case "forestry":
			updateZoneTimer("forest","forest");
			if(!zoneBlock["sawmill"]){ updateZoneTimer("sawmill","sawmill"); }
			if(!zoneBlock["carpentry"]){ updateZoneTimer("carpentry","carpentry"); }
		break;
		case "foodworld":
			for(var v=1;v<=4;v++){
				if(!zoneBlock["foodworld-"+v]){ updateZoneTimer("foodworld-"+v,"foodworld-"+v); }
			}
		break;
		}
		// slots
		var readyZoneAdded=0;
		for(var i in ALL_SLOTS){
			if(!ALL_SLOTS.hasOwnProperty(i)){ continue; }
			if(!zoneBlock[i]){ 
				readyZoneAdded+=checkReadyZone(i);
			}
		}
		if(readyZoneAdded>0){
			raiseEvent("gameZoneReady");
			// GM_log("unsafeData.readyZone:\n"+print_r(unsafeData.readyZone,"",true,"\n"));					
			if(DEVMODE){ GM_log("readyZone="+implode(unsafeData.readyZone)); }
		}
		if (zoneEndTimes[0]==-1){
			help=texte["cropped"].toUpperCase();
		}else if(zoneEndTimes[0]+unsafeWindow.Zeit.Verschiebung<=now){
			help=texte["fertig"].toUpperCase();
		}else{
			help=getTimeStr(zoneEndTimes[0]+unsafeWindow.Zeit.Verschiebung-now);
		}
		var cell;
		if((cell=$("mainmenue2_incoming"))&&(cell.style.display=="block")){
			help+=" - !";
		}else if((cell=$("mainmenue3_incoming"))&&(cell.style.display=="block")){
			help+=" - !";
		}
		cell=null;
		document.title=help+DOCTITLE;

		//raising events of other pages
		var raisedEvents=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_raisedEvents","{}"),"loop1/raisedEvents",{});
		for(var v in raisedEvents){
			if(!raisedEvents.hasOwnProperty(v)){ continue; }
			raiseEvent(v);
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_raisedEvents","{}");
		}
		// timeMeasureStop("loop1"); // 4ms
		}catch(err){ GM_log("ERROR loop1\n"+err); }
	}

	function loop60(){
		unsafeWindow.updateRack(unsafeWindow._currRack,0); //TODO Why is this done here? this generates a lot of functions to be call every time.
		unsafeWindow.updateMenu();
		plotLevelProgressBar();
	}

	window.setInterval(loop1,1000);
	window.setInterval(loop60,60000);

	// First run
	if (GM_getValue("tutorial",0)==0){
		click($("mainmenue5")); // Fix Seberoth
	}
	newinput=null;newdiv=null;newdiv1=null;newbutton=null;newimg=null;
}catch(err){ GM_log("ERROR do_main ("+err_trace+")\n"+err); }
}

//***********************************************************************************************************

function do_nachrichten_read(){
	//GM_log("do_nachrichten_read "+implode(pageZusatz)+" readstate:"+GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0));
	var candtable=document.getElementsByTagName("table");
	if (!candtable[0]){
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0);
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread","[]");
		location.href="http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/system.php?page=1";
	}
	var currMsgId=pageZusatz["msg"];
	var msgIdRead=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread","[]"),"do_nachrichten_read/msgIdRead",[]);
	for(var v=msgIdRead.length-1;v>-1;v--){if((msgIdRead[v]=="")||(msgIdRead[v]==currMsgId)){ msgIdRead.splice(v,1); break;}}
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread",implode(msgIdRead));
	var candtr=candtable[2].getElementsByTagName("tr");
	var absender=null;
	var betreff="";
	var currPage=pageZusatz["page"]?pageZusatz["page"]:1;
	var msgBox=candtr[3].getElementsByTagName("div")[0];
	var newdiv,newinput;

	switch(pageZusatz["from"]){
	case "inbox":{
		$("btn_inbox").bgColor="#cc9";
		absender=candtr[0].getElementsByTagName("td")[1].firstElementChild.innerHTML;
		//candtd.children[1].setAttribute("style","float:left");
		var sendTime=candtr[1].getElementsByTagName("td")[1].innerHTML;
		betreff="Re: "+candtr[2].getElementsByTagName("td")[1].firstElementChild.innerHTML;

		var valPrivNachr=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valPrivNachr",100);
		var nachrichten=new Array();
		removeElement(msgBox.getElementsByTagName("hr")[0]);
		removeElement(msgBox.getElementsByTagName("span")[0]);
		var currMsg=" "+msgBox.innerHTML;
		while(currMsg.search(/\s\d{4,}/)!=-1){currMsg=currMsg.replace(/(\s\d+)(\d{3})/g,"$1"+delimThou+"$2");}
		currMsg=currMsg.slice(1,currMsg.length);
		msgBox.innerHTML=currMsg;
		nachrichten[0]=new Array();
		nachrichten[0][0]=currMsgId;
		nachrichten[0][1]=absender;
		nachrichten[0][2]="<u>->>&nbsp;"+sendTime+"</u><br>"+currMsg;

		try{ var save=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten").split("&nbsp;|");
			for(var v=0;v<save.length;v++){
				nachrichten[v+1]=save[v].split("&nbsp;~");
				if ((nachrichten[v+1][1]==absender) && (nachrichten[v+1][0]!=currMsgId)){
					createElement("hr",{"style":"height:1px;width:96%;border-right:0px none;border-width:1px 0px 0px;border-style:solid none none;border-color:#aaa -moz-use-text-color -moz-use-text-color;"},msgBox);
					createElement("span",{},msgBox,nachrichten[v+1][2]);
				}
				if (v>valPrivNachr) break;
			}
		} catch(err){}

		nachrichten.sort(function (a,b){return parseInt(b[0],10) - parseInt(a[0],10);});
		if (nachrichten.length>1){
			for(var v=nachrichten.length-2;v>=0;v--){ if (nachrichten[v][0]==nachrichten[v+1][0]){ nachrichten.splice(v+1,1);}}
		}

		var save="";
		for(var v=0;v<nachrichten.length;v++){ save+=nachrichten[v].join("&nbsp;~")+"&nbsp;|";}
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten",save.slice(0,save.length-7));
	break;}
	case "outbox":{
		$("btn_inbox").parentNode.children[2].bgColor="#cc9";
		absender=candtr[0].getElementsByTagName("td")[1].firstElementChild.innerHTML;
		//candtr[0].getElementsByTagName("td")[1].childNodes[3].setAttribute("style","float:left");
		betreff="Re: "+candtr[2].getElementsByTagName("td")[1].firstElementChild.innerHTML;

		var nachrichten=new Array();
		try{ save=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten").split("&nbsp;|");
			for(var v=0;v<save.length;v++){
				nachrichten[v+1]=save[v].split("&nbsp;~");
				if ((nachrichten[v+1][1]==absender) && (nachrichten[v+1][0]!=currMsgId)){
					createElement("hr",{"style":"height:1px;width:96%;border-right:0px none;border-width:1px 0px 0px;border-style:solid none none;border-color:#aaa -moz-use-text-color -moz-use-text-color;"},msgBox);
					createElement("span",{},msgBox,nachrichten[v+1][2]);
				}
			}
		} catch(err){}
	break;}
	case "system":{
		loadProductData();
		$("btn_sysinbox").bgColor="#cc9";
		if(help=new RegExp(texte["msgFriend"]).exec(candtr[2].getElementsByTagName("div")[0].innerHTML)){
			//Friendship message
			absender=help[1];
		}else{
			var kauf = explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_kauf","{}"),"do_nachrichten_read/system/kauf",{});

			var valNachr=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valNachr",100);
			var c=0;
			for(var v in kauf){
				if(!kauf.hasOwnProperty(v)){ continue; }
				if(c>valNachr){ delete kauf[v]; }
				else{ c++; }
			}

			var currMsg=msgBox.innerHTML.replace("&amp;uuml;",u_dots);
			var help=currMsg.replace(/\s+/,"");
			// Market sale
			var help2=new RegExp(texte["msgMarketsaleContent"]).exec(help);
			//GM_log(help);
			if (help2){
				if (LNG=="tr"){ help2.push(help2.splice(2,1).toString());}
				if(LNG=="se"){
					help2[4]=help2[4].replace(/\.(\d\d) /,",$1 ");
					help2[4]=help2[4].replace(/\.(\d\d)$/,",$1");
				}

				var prod=prodId[0][help2[3]];
				var amount=parseInt(help2[2],10);
				var money=parseFloat(help2[4].replace(regDelimThou,"").replace(regDelimDeci,"."),10);

				if(!kauf[currMsgId]){
					var day=parseInt((new RegExp(dateFormatDMY.replace("day","(\\d+)").replace("month","\\d+").replace("year","\\d+").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					var month=parseInt((new RegExp(dateFormatDMY.replace("day","\\d+").replace("month","(\\d+)").replace("year","\\d+").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					var year=parseInt((new RegExp(dateFormatDMY.replace("day","\\d+").replace("month","\\d+").replace("year","(\\d+)").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					if(year<100){ year+=2000; }
					var dayStr=day+"."+month+"."+year;
					var levelLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog","{}"),"do_nachrichten_read/system/market/levelLog",{});
					if(levelLog[dayStr]==undefined){ levelLog[dayStr]=[0,null,0,0,0]; }
					levelLog[dayStr][2] += money;
					levelLog[dayStr][2]=Math.round(100*levelLog[dayStr][2])/100;
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog));
					raiseEventTop("gameChangedLevelLog");

					var price=Math.round(100*money/amount)/100;
					var ownMarketOffers=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_ownMarketOffers","{}"),"do_nachrichten_read/system/market/ownMarketOffers",{});
					if(ownMarketOffers[prod]&&ownMarketOffers[prod][price]){
						ownMarketOffers[prod][price] -= amount;
						if(ownMarketOffers[prod][price]<1){ delete ownMarketOffers[prod][price]; }
					}
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_ownMarketOffers",implode(ownMarketOffers));
					raiseEventTop("gameChangedOwnMarketOffers");
					ownMarketOffers=null;
				}

				kauf[currMsgId]=new Array();
				kauf[currMsgId][0]=help2[1];
				absender=help2[1];
				kauf[currMsgId][1]=[prod,amount];
				betreff=help2[3];
				kauf[currMsgId][2]=money;
			}
			// Contract sale
			help2=new RegExp(texte["msgContractsaleContent"]).exec(help);
			//GM_log(help);
			if (help2){
				if(LNG=="se"){
					help2[3]=help2[3].replace(/\.(\d\d) /,",$1 ");
					help2[3]=help2[3].replace(/\.(\d\d)$/,",$1");
				}
				var money=parseFloat(help2[3].replace(regDelimThou,"").replace(regDelimDeci,"."),10);
				if(!kauf[currMsgId]){
					var day=parseInt((new RegExp(dateFormatDMY.replace("day","(\\d+)").replace("month","\\d+").replace("year","\\d+").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					var month=parseInt((new RegExp(dateFormatDMY.replace("day","\\d+").replace("month","(\\d+)").replace("year","\\d+").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					var year=parseInt((new RegExp(dateFormatDMY.replace("day","\\d+").replace("month","\\d+").replace("year","(\\d+)").replace(".","\\."))).exec(candtr[1].children[1].innerHTML)[1],10);
					if(year<100){ year+=2000; }
					var dayStr=day+"."+month+"."+year;
					var levelLog=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog","{}"),"do_nachrichten_read/system/contract/levelLog",{});
					if(levelLog[dayStr]==undefined){ levelLog[dayStr]=[0,null,0,0,0]; }
					levelLog[dayStr][3] += money;
					levelLog[dayStr][3]=Math.round(100*levelLog[dayStr][3])/100;
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_levelLog",implode(levelLog));
					raiseEventTop("gameChangedLevelLog");
				}
				kauf[currMsgId]=new Array();
				kauf[currMsgId][0]=help2[1];
				kauf[currMsgId][1]=new Array();
				absender=help2[1];
				var help3;
				var help4=new Array();
				while(help3=new RegExp(texte["msgContractsaleList"]).exec(help2[2])){
					help2[2]=help2[2].replace(help3[0],"");
					kauf[currMsgId][1].push([prodId[0][help3[2]],parseInt(help3[1],10)]);
				}
				if(kauf[currMsgId][1].length==1){ betreff=prodName[0][kauf[currMsgId][1][0][0]]; }
				kauf[currMsgId][2]=money;
			}

			while(currMsg.search(/\s\d{4}/)!=-1){currMsg=currMsg.replace(/(\s\d+)(\d{3})/g,"$1"+delimThou+"$2");}
			if(betreff){msgBox.innerHTML=currMsg+"<br><br>"+texte["stueckpreis"]+": "+moneyFormat(kauf[currMsgId][2]/(typeof kauf[currMsgId][1][0]=="object"?kauf[currMsgId][1][0][1]:kauf[currMsgId][1][1]));}

			kauf.sortObj(sortObjFunctions["int"],true);
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_kauf",implode(kauf));

			var msgId=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_system","[]"),"do_nachrichten_read/system/nachrichten_system",[]);
			if (msgId.length>1){
				for(var d=0;d<msgId.length;d++){if(msgId[d]==currMsgId){ break;}}
			}else{
				var d=0;
			}
			newdiv=candtable[1].getElementsByTagName("tr")[5].getElementsByTagName("td")[0];
			newdiv.getElementsByTagName("input")[0].addEventListener("click",function(){GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",1);},false);
			newinput=createElement("input",{"type":"button","value":texte["vorigeNachricht"],"class":"link msg_input","href":"read.php?from=system&page="+currPage+"&msg="+msgId[d-1]+"&mass=0"},newdiv);
			newinput.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
			if(d==0){
				newinput.disabled=true;
				newinput.style.color="transparent";
			}else{
				newinput.setAttribute("class","link2 msg_input");
			}
			newinput=createElement("input",{"type":"button","value":texte["naechsteNachricht"],"class":"link msg_input","href":"read.php?from=system&page="+currPage+"&msg="+msgId[d+1]+"&mass=0"},newdiv);
			newinput.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
			if (d==msgId.length-1){newinput.disabled=true;newinput.style.color="transparent";}else{newinput.setAttribute("class","link2 msg_input");}

			// alle lesen
			if (GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0)==2){
				if (msgIdRead.length>0){
					newdiv=createElement("div",{"style":"position:absolute;z-index:200;right:0px;top:50px;width:100px;height:40px;background-color:yellow;border:3px solid black;border-radius:10px;text-align:center;color:black;font-weight:bold;"},ALL);
					createElement("p",{"style":"vertical-align:middle;"},newdiv,implode(msgIdRead.length));
					location.href="read.php?from=system&page="+currPage+"&msg="+msgIdRead[msgIdRead.length-1]+"&mass=0";
				}else{
					GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0);
					location.href="http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/system.php?page="+currPage;
				}
			}
		}
	break;}
	}

	if(absender){
		absender=absender.replace(/^\s+/,"");
		newdiv=candtr[0].getElementsByTagName("td")[1];
		newdiv.innerHTML="";
		igm(absender,newdiv,betreff.replace(/&nbsp;/g," "));
		stats(absender,newdiv);
		vertrag(absender,newdiv);
		createElement("a",{"href":"javascript:addContact('"+absender+"')","class":"link"},newdiv,absender);
	}

	//show last message
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_letzte","<u>"+betreff+"</u><br>"+msgBox.innerHTML);
	if (msgIdRead.length>0){
		newdiv=createElement("div",{"class":"link","href":"read.php?from=system&page="+currPage+"&msg="+msgIdRead[msgIdRead.length-1]+"&mass=0","style":"position:absolute;bottom:0;right:0;height:26px;width:35px;background:url('"+GFX+"regal2.jpg');background-position:35px 0px;border-radius:15px;"},ALL);
		newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["naechsteNachricht"]); },false);
		newdiv.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
	}
	candtable=null;candtr=null;msgBox=null;newdiv=null;newinput=null;
}

function do_nachrichten_new(){
	var pagedata=explode(GM_getValue(LNG+"_"+SERVER+"_pagedataNachrichtenNew","{}"),"do_nachrichten_new/pagedataNachrichtenNew",{});
	GM_setValue(LNG+"_"+SERVER+"_pagedataNachrichtenNew","{}");
	$("btn_inbox").parentNode.children[0].bgColor="#cc9";

	var newdiv=$("msg_subject");
	if(pagedata["subject"]){ newdiv.value=pagedata["subject"]; }
	if(newdiv && GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMessageRe",true)){
		var help=newdiv.value;
		while(help.match(/Re:\s*Re:/)){
			help=help.replace(/Re:\s*Re:/g,"Re:");
		}
		newdiv.value=help;
	}

	newdiv=$("msg_to");
	if(pagedata["to"]){ newdiv.value=pagedata["to"]; }
	if (newdiv && newdiv.value!=""){
		newdiv.style.width="350px";
		stats(newdiv.value,newdiv.parentNode);
	}

	newdiv=$("msg_body");
	if (newdiv){
		var formatMsgNumbers = function (){
			var msgBody=$("msg_body");
			var posStart=msgBody.selectionStart;
			var posEnd=msgBody.selectionEnd;
			if (posStart==posEnd){
				var help=msgBody.value+" ";
				var c;
				while((c=help.search(/\d{4}\D/))!=-1){
					help=help.replace(/(\d)(\d{3}\D)/,"$1"+delimThou+"$2"); //missing sep
					if(c+1<posStart) posStart++;
				}
				while((c=help.search(new RegExp(regDelimThou2)))!=-1){
					help=help.replace(new RegExp(regDelimThou2),"$1"+delimThou+"$2$3"); //shift sep
				}
				while((c=help.search(new RegExp(regDelimThou3)))!=-1){
					help=help.replace(new RegExp(regDelimThou3),"$1$2$3"); //delete sep
					if(c+1<posStart) posStart--;
				}

				msgBody.value=help.slice(0,help.length-1);
				setSelRange(msgBody,posStart,posStart);
				msgBody=null;
			}
		};
		newdiv.value=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichtvorlage","");
		var newa=createElement("a",{"class":"link"},newdiv.parentNode,texte["vorlage"]);
		newa.addEventListener("click",function(){
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichtvorlage",$("msg_body").value);
		},false);

		var valMsgFormat=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMsgFormat",true);
		var newspan=createElement("span",{"style":"line-height:18px;"},newdiv.parentNode.previousSibling.previousSibling,texte["formatiereZahlen"]);
		var newinput=createElement("input",{"type":"checkbox","class":"link","checked":valMsgFormat,"style":"float:left;"},newspan);
		newinput.addEventListener("click",function(){
			if (this.checked){ $("msg_body").addEventListener("keyup",formatMsgNumbers,false); }
			else{ try{$("msg_body").removeEventListener("keyup",formatMsgNumbers,false);}catch(err){} }
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_valMsgFormat",this.checked);
		},false);

		if (valMsgFormat){ newdiv.addEventListener("keyup",formatMsgNumbers,false);	}

		ALL.getElementsByTagName("input")[4].tabIndex="4";
		ALL.getElementsByTagName("input")[4].addEventListener("click",function(){
			now=Math.floor((new Date()).getTime()/1000);
			var save=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten","");
			if (save){
				save=(parseInt(save,10)+1)+"&nbsp;~"+$("msg_to").value+"&nbsp;~<u><<-&nbsp;"+getFormattedDateStr(now,2,false)+",&nbsp;"+getDaytimeStr(now,1)+"&nbsp;"+texte["uhr"]+"</u><br>"+$("msg_body").value+"<br>&nbsp;|"+save;
			}else{
				save="1&nbsp;~"+$("msg_to").value+"&nbsp;~<u><<-&nbsp;"+getFormattedDateStr(now,2,false)+",&nbsp;"+getDaytimeStr(now,1)+"&nbsp;"+texte["uhr"]+"</u><br>"+$("msg_body").value+"<br>";
			}
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten",save);
		},false);
		newa=null;newspan=null;newinput=null;
	}else{
		var msgIdRead=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread","[]"),"do_nachrichten_new/nachrichten_doread",[]);
		if (msgIdRead[0]!=""){
			newdiv=createElement("div",{"class":"link","href":"read.php?from=system&page=1&msg="+msgIdRead[msgIdRead.length-1]+"&mass=0","style":"position:absolute;bottom:0;right:0;height:26px;width:35px;background:url('"+GFX+"regal2.jpg');background-position:35px 0px;border-radius:15px;"},ALL);
			newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["naechsteNachricht"]); },false);
			newdiv.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
		}
	}

	newdiv=createElement("div",{"id":"lastMessage","style":"position:absolute;top:110px;right:-403px;width:413px;height:134px;padding:5px;background-color:#b8a789;border:2px solid black;border-radius:10px 0px 0px 10px;z-index:101;z-index:15;color:black;overflow:auto;"},ALL,GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_letzte",""));
	newdiv.addEventListener("mouseover",function(){this.style.right="0";},false);
	newdiv.addEventListener("mouseout",function(){this.style.right="-403px";},false);
	newdiv=null;
}

function do_nachrichten_inbox(){
	if($("btn_inbox").getAttribute("class").search("green")==-1){
		$("btn_inbox").bgColor="#cc9";
		if ($("btn_sysinbox").getAttribute("class").search("green")!=-1){
			window.location.href="http://s"+SERVER+"."+GAMEPAGES[LNG]+"/nachrichten/system.php";
		}
	}
	valServerTimeOffset=GM_getValue(LNG+"_valServerTimeOffset",0);

	var candtable=document.getElementsByTagName("table");
	if(candtable[2]){
		var candtr=candtable[2].getElementsByTagName("tr");
		var cand;
		for(var v=1;v<candtr.length;v++){
			cand=candtr[v].getElementsByTagName("td");
			if(valServerTimeOffset!=0){
				candtr[v].addEventListener("mouseover",function(event){
					var time=getFormattedTime(this.children[1].innerHTML)-valServerTimeOffset;
					showToolTip(event,getFormattedDateStr(time,1)+",&nbsp;"+getDaytimeStr(time,1)+"&nbsp;"+texte["uhr"]);
				},false);
			}
			cand[2].firstElementChild.style.width="230px";
		}
		if(candtable[3]){
			cand=candtable[3].getElementsByTagName("span");
			cand[0].id="prevPage";
			cand[1].id="nextPage";
		}
		cand=null;candtr=null;
	}
	candtable=null;
}

function do_nachrichten_outbox(){
	$("btn_inbox").nextElementSibling.bgColor="#cc9";
	valServerTimeOffset=GM_getValue(LNG+"_valServerTimeOffset",0);
	var candtable=document.getElementsByTagName("table");
	if(candtable[2]){
		var cand,candtr;
		if(valServerTimeOffset!=0){
			candtr=candtable[2].getElementsByTagName("tr");
			for(var v=1;v<candtr.length;v++){
				cand=candtr[v].getElementsByTagName("td");
				candtr[v].addEventListener("mouseover",function(event){
					var time=getFormattedTime(this.firstElementChild.innerHTML)-valServerTimeOffset;
					showToolTip(event,getFormattedDateStr(time,1)+",&nbsp;"+getDaytimeStr(time,1)+"&nbsp;"+texte["uhr"]);
				},false);
			}
		}
		if(candtable[3]){
			cand=candtable[3].getElementsByTagName("span");
			cand[0].id="prevPage";
			cand[1].id="nextPage";
		}
		cand=null;candtr=null;
	}
	candtable=null;
}

function do_nachrichten_contact(){
	$("btn_inbox").nextElementSibling.nextElementSibling.bgColor="#cc9";
}

function do_nachrichten_system(){
	//GM_log("do_nachrichten_system "+implode(pageZusatz));
	loadProductData();
	GM_addStyle(
		 ".systemMsg_marketsale{"+css_styles["systemMsg_marketsale"][1]+"}\n"
		+".systemMsg_contractsale{"+css_styles["systemMsg_contractsale"][1]+"}"
	);
	valServerTimeOffset=GM_getValue(LNG+"_valServerTimeOffset",0);
	var kauf=new Object();
	// market: "id":[name,[prod,amount],money]
	// contract: "id":[name,[[prod,amount],...],money]
	var msgId=new Array();
	var msgIdUnknown=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread","[]"),"do_nachrichten_system/nachrichten_doread",[]);
	var pageIsKnown=false;
	var candtable=document.getElementsByTagName("table");
	if(candtable[3]){
		var candspan=candtable[3].getElementsByTagName("span");
		candspan[0].id="prevPage";
		candspan[1].id="nextPage";
		candspan=null;
	}

	if($("btn_sysinbox").getAttribute("class").search("green")==-1){
		$("btn_sysinbox").bgColor="#cc9";
	}

	kauf=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_kauf","{}"),"do_nachrichten_system/kauf",{});

	candtable[2].parentNode.id="container_system_messages";
	candtable[2].parentNode.style.overflow="hidden";
	if(candtable[3]){
		var candtr=candtable[2].getElementsByTagName("tr");
		candtr[0].getElementsByTagName("td")[0].innerHTML=""; // the "New" in headline
		var colgroup=candtable[2].getElementsByTagName("col");
		//colgroup[0].width="20px";
		//colgroup[1].width="150px";
		//colgroup[2].width="360px";
		colgroup[3].width="20px";
		colgroup=null;

		candtable[2].addEventListener("mouseover",function(event){
			var node=event.target;
			var mouseOverText=node.getAttribute("mouseOverText");
			while((node!=this)&&(!mouseOverText)){
				node=node.parentNode;
				mouseOverText=node.getAttribute("mouseOverText");
			}
			if(mouseOverText){ showToolTip(event,mouseOverText); }
			node=null;mouseOverText=null;
		},false);

		var canda,cell,pic;
		for(var v=0;v<candtr.length-1;v++){
			var time="";
			if(valServerTimeOffset){
				cell=candtr[v+1].getElementsByTagName("td")[1];
				time=getFormattedTime(cell.innerHTML)-valServerTimeOffset;
				time=getFormattedDateStr(time,1)+",&nbsp;"+getDaytimeStr(time,1)+"&nbsp;"+texte["uhr"]+"<br>";
			}
			canda=candtr[v+1].getElementsByTagName("a");
			var help=/javascript:showMessage\('(\d+)',(\d+)\)/.exec(canda[0].href);
			if (help[2]=="0"){
				msgId[v]=help[1];
				if (kauf[msgId[v]]){
					// known sell message
					pageIsKnown=true;
					canda[0].parentNode.style.width="360px"; //130+150+80 (old 380)
					canda[0].innerHTML="";
					canda[0].setAttribute("style","text-decoration:none");
					if (typeof(kauf[msgId[v]][1][0])!="object"){ igm(kauf[msgId[v]][0],canda[0].parentNode,prodName[0][kauf[msgId[v]][1][0]].replace(/&nbsp;/g," ")); }
					else if(kauf[msgId[v]][1].length==1){ igm(kauf[msgId[v]][0],canda[0].parentNode,prodName[0][kauf[msgId[v]][1][0][0]].replace(/&nbsp;/g," ")); }
					else{ igm(kauf[msgId[v]][0],canda[0].parentNode); }
					createElement("span",{"style":"position:absolute;width:130px;"},canda[0],kauf[msgId[v]][0]);
					if(typeof(kauf[msgId[v]][1][0])=="object") canda[0].parentNode.setAttribute("class","systemMsg_contractsale");
					else canda[0].parentNode.setAttribute("class","systemMsg_marketsale");
					cell=createElement("span",{"style":"position:absolute;left:130px;width:150px;text-align:right;"},canda[0]);
					if(typeof(kauf[msgId[v]][1][0])!="object"){
						candtr[v+1].setAttribute("mouseOverText",time+canda[0].parentNode.getAttribute("title")+"<br>"+texte["stueckpreis"]+": "+moneyFormat(kauf[msgId[v]][2]/kauf[msgId[v]][1][1]));
						cell.innerHTML=numberFormat(kauf[msgId[v]][1][1])+"&nbsp;"+prodName[0][kauf[msgId[v]][1][0]]+"&nbsp;";
						produktPic(0,kauf[msgId[v]][1][0],cell);
					}else if(kauf[msgId[v]][1].length==1){
						candtr[v+1].setAttribute("mouseOverText",time+canda[0].parentNode.getAttribute("title")+"<br>"+texte["stueckpreis"]+": "+moneyFormat(kauf[msgId[v]][2]/kauf[msgId[v]][1][0][1]));
						cell.innerHTML=numberFormat(kauf[msgId[v]][1][0][1])+"&nbsp;"+prodName[0][kauf[msgId[v]][1][0][0]]+"&nbsp;";
						produktPic(0,kauf[msgId[v]][1][0][0],cell);
					}else{
						cell.innerHTML="...";
						var str=canda[0].parentNode.getAttribute("title");
						for(var i=0;i<kauf[msgId[v]][1].length;i++){
							str += "<br>"+kauf[msgId[v]][1][i][1]+"&nbsp;"+prodName[0][kauf[msgId[v]][1][i][0]];
						}
						candtr[v+1].setAttribute("mouseOverText",time+str);
					}
					canda[0].parentNode.setAttribute("title","");

					createElement("span",{"style":"position:absolute;left:280px;width:80px;text-align:right;"},canda[0],moneyFormat(kauf[msgId[v]][2]));
				}else{
					var help2=canda[0].innerHTML.replace("<b>","").replace("</b>","");
					if (help2.match(new RegExp(texte["msgMarketsale"]))){
						msgIdUnknown.push(msgId[v]);
						candtr[v+1].setAttribute("mouseOverText",time+canda[0].parentNode.getAttribute("title"));
					}else if(help2==texte["msgContractsale"]){
						msgIdUnknown.push(msgId[v]);
						candtr[v+1].setAttribute("mouseOverText",time+canda[0].parentNode.getAttribute("title"));
					}else if(time!=""){
						candtr[v+1].setAttribute("mouseOverText",time);
					}
				}
			}else{
				canda[0].innerHTML=canda[0].innerHTML.replace(/<b>/g,"");
			}
		}
	}else{
		msgIdUnknown=new Array();
	}

	msgIdAll = msgId.concat(explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_system","[]"),"do_nachrichten_system/nachrichten_system",[]));
	
	function NumsortDesc (a, b){return parseInt(b,10) - parseInt(a,10);}
	msgIdAll.sort(NumsortDesc);
	if (msgIdAll.length>1){
		for(var v=msgIdAll.length-2;v>-1;v--){
			if (msgIdAll[v]==msgIdAll[v+1]) msgIdAll.splice(v+1,1);
		}
	}

	msgIdUnknown.sort(NumsortDesc);
	for(var v=msgIdUnknown.length-1;v>-1;v--){
		if (msgIdUnknown[v]==msgIdUnknown[v+1]) msgIdUnknown.splice(v+1,1);
		if (kauf[msgIdUnknown[v]] || isNaN(msgIdUnknown[v]) ) msgIdUnknown.splice(v,1);
	}

	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_system",implode(msgIdAll));
	GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doread",implode(msgIdUnknown));

	if(!candtable[3]){
		cell=createElement("div",{"style":"width:550px;position:absolute;left:25px;top:320px;"},candtable[1].getElementsByTagName("td")[0]);
		cell=createElement("table",{"cellspacing":"0","cellpadding":"0","style":"width:550px;"},cell);
		createElement("td",{},createElement("tr",{},cell));
		createElement("td",{},createElement("tr",{},cell));
	}
	cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["zeigeLog"]},candtable[3].getElementsByTagName("td")[1]);
	cell.addEventListener("click",init_log,false);

	if (msgIdUnknown.length>0){
		switch(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0)){
		case 3:{
			if (!pageIsKnown && (candtable[3].getElementsByTagName("span")[1].getAttribute("onclick"))){
				click(candtable[3].getElementsByTagName("span")[1]);
			}else{
				GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",2); //alle lesen
				unsafeWindow.showMessage(msgIdUnknown[msgIdUnknown.length-1],0);
			}
		break;}
		case 1:{
			GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0); // eine lesen
			unsafeWindow.showMessage(msgIdUnknown[msgIdUnknown.length-1],0);
		break;}
		default:{
			cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["alleLesen"]},candtable[3].getElementsByTagName("td")[1]);
			cell.addEventListener("click",function(){
				GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",3); //alle lesen vorbereiten
				do_nachrichten_system();
				//TODO add here if(unsafeWindowfarm==1){doFarmis()} // NOTE call is in IFRAME
				top.window.wrappedJSObject.updateRack(top.window.wrappedJSObject._currRack,0);//CHECK top.window.wrappedJSObject.
			},false);
		}
		}
	}else{
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_doreadState",0);
	}
	candtable=null;candtr=null;canda=null;cell=null;pic=null;
	//*********************
	function init_log(){
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_system","[]");
		for(var v in kauf){
			if(!kauf.hasOwnProperty(v)){ continue; }
			kauf[v][3]=new Object;
			if(typeof kauf[v][1][0]!="object"){
				kauf[v][3][kauf[v][1][0]]=[kauf[v][1][1],kauf[v][2],Math.round(100*kauf[v][2]/kauf[v][1][1])/100];
			}else{
				var sum=0;
				for(var i=0;i<kauf[v][1].length;i++){
					kauf[v][3][kauf[v][1][i][0]]=[kauf[v][1][i][1],kauf[v][1][i][1]*gut[kauf[v][1][i][0]]];
					sum += kauf[v][1][i][1]*gut[kauf[v][1][i][0]];
				}
				sum /= kauf[v][2];
				for(var i in kauf[v][3]){
					if(!kauf[v][3].hasOwnProperty(i)){ continue; }
					kauf[v][3][i][1] /= sum;
					kauf[v][3][i][2]=Math.round(100*kauf[v][3][i][1]/kauf[v][3][i][0])/100;
				}
			}
		}
		var container=$("container_system_messages");
		container.style.overflow="";
		container.style.overflowX="hidden";
		container.style.overflowY="scroll";
		container=null;
		function build_log_all(){
			// GM_log("build_log filterPlayer="+filterPlayer+" filterProduct="+filterProduct+" mode="+mode);
			var cell=ALL.getElementsByClassName("error");
			if(cell[0]){ removeElement(cell[0]); }
			filterPlayerLow=filterPlayer.toLowerCase();
			var umsatz=0;
			var container=$("container_system_messages"); // document.getElementsByTagName("table")[2].parentNode
			container.innerHTML="";
			if(!build_log_all_scroll[0]){
				build_log_all_scroll[0]=true;
				container.addEventListener("scroll",build_log_all_scroll[1],false);
			}
	
			var newtable=createElement("table",{"style":"width:100%;"},container);
			// container.replaceChild(newtable,candtable[2]);
			var newtablebody=createElement("tbody",{"class":"hoverRowBgCc9"},newtable); // ,"style":"overflow-y:scroll; overflow-x:hidden;height: 228px;"
			var newtablefoot=createElement("tfoot",{},newtable);
			var newtr,newtd;
			kaufArrayHelper=new Array();
			for(var v in kauf){
				if(!kauf.hasOwnProperty(v)){ continue; }
				if ((kauf[v][0].toLowerCase().search(filterPlayerLow)!=-1) && ((filterProduct==null)||(kauf[v][3][filterProduct]))){
					umsatz += kauf[v][2];
					kaufArrayHelper.push(v);
				}
			}
	
			newtr=createElement("tr",{},newtablefoot);
			createElement("td",{},newtr);
			createElement("td",{},newtr);
			createElement("td",{"align":"right", "style":"border-top:1px solid"},newtr,moneyFormat(umsatz));
	
			container.nextElementSibling.innerHTML = "";
			newtable=createElement("table",{"style":"width: 530px;"},container.nextElementSibling);
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr,texte["waren"]+":");
			newtd=createElement("td",{},newtr);
			cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["summiere"]},newtd);
			cell.addEventListener("click",function(){
				build_log_sumWaren();
			},false);
	
			createElement("span",{"style":"padding-left:10px;"},newtd,texte["filter"]+":");
			cell=createElement("select",{"class":"link2"},newtd);
			createElement("option",{"value":"null"},cell,"");
			for(var v=0;v<prodNameSort[0].length;v++){
				if((!prodBlock[0][prodNameSort[0][v]].match(/t/))&&(!prodBlock[0][prodNameSort[0][v]].match(/l/))){
					createElement("option",{"value":prodNameSort[0][v]},cell,prodName[0][prodNameSort[0][v]]);
				}
			}
			cell.value=filterProduct;
			cell.addEventListener("change",function(){
				filterProduct = (this.value=="null"?null:this.value);
				build_log_all();
			},false);
	
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr,texte["kaeufer"]+":");
			newtd=createElement("td",{},newtr);
			var cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["summiere"]},newtd);
			cell.addEventListener("click",function(){
				mode="gewinn";
				build_log_sumKaeufer();
			},false);
	
			createElement("span",{"style":"padding-left:10px;"},newtd,texte["filter"]+":");
			cell=createElement("input",{"value":filterPlayer,"class":"link","style":"width:100px","maxlength":"20"},newtd);
			cell.addEventListener("change",function(){ 
				filterPlayer = this.value;
				build_log_all();
			},false);
	
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr);
			createElement("td",{"id":"kaufDataCount"},newtr);
	
			build_log_all_plot();
		
			container=null;newtable=null;newtablebody=null;newtablefoot=null;newtr=null;newtd=null;cell=null;
		}
		function build_log_all_plot(){
			var newtablebody=$("container_system_messages").getElementsByTagName("tbody")[0];
			var start=newtablebody.getElementsByTagName("tr").length;
			var end=Math.min(start+100,kaufArrayHelper.length);
			var newtr,newtd,newdiv;
			for(var w=start;w<end;w++){
				var v=kaufArrayHelper[w];
				newtr=createElement("tr",{"kaufId":v},newtablebody);
				if(typeof kauf[v][1][0]=="object") newtr.style.fontStyle="italic";
				newtd=createElement("td",{"class":"link"},newtr,kauf[v][0]);
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,kauf[this.parentNode.getAttribute("kaufId")][0])); },false);
				newtd.addEventListener("click",function(){ 
					filterPlayer=kauf[this.parentNode.getAttribute("kaufId")][0];
					filterProduct=null;
					build_log_all();
				},false);
				newtd=createElement("td",{},newtr);
				for(var i in kauf[v][3]){
					if(!kauf[v][3].hasOwnProperty(i)){ continue; }
					newdiv=createElement("div",{"class":"link","style":"height:16px","prod":i},newtd);
					produktPic(0,i,newdiv);
					createElement("span",{},newdiv,numberFormat(kauf[v][3][i][0])+" "+prodName[0][i]);
					newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,prodName[0][this.getAttribute("prod")])); },false);
					newdiv.addEventListener("click",function(){
						filterPlayer="";
						filterProduct=this.getAttribute("prod");
						build_log_all();
					},false);
				}
				newtd=createElement("td",{"class":"link","align":"right","href":"read.php?from=system&page=1&msg="+v+"&mass=0"},newtr);
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["zurNachricht"]); },false);
				newtd.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
				for(var i in kauf[v][3]){
					if(!kauf[v][3].hasOwnProperty(i)){ continue; }
					createElement("div",{"style":"height:16px"},newtd,moneyFormat(kauf[v][3][i][1]));
				}
				newtd=createElement("td",{"class":"link","align":"right","href":"read.php?from=system&page=1&msg="+v+"&mass=0"},newtr);
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["zurNachricht"]); },false);
				newtd.addEventListener("click",function(){location.href=this.getAttribute("href");},false);
				for(var i in kauf[v][3]){
					if(!kauf[v][3].hasOwnProperty(i)){ continue; }
					createElement("div",{"style":"height:16px;padding-right:20px;"},newtd,moneyFormat(kauf[v][3][i][2]));
				}
			}
			$("kaufDataCount").innerHTML=numberFormat(end)+"/"+numberFormat(kaufArrayHelper.length);
			newtablebody=null;newtr=null;newtd=null;newdiv=null;
		}
		var build_log_all_scroll=[false,function(){
			if((parseInt(this.scrollTop,10)+parseInt(this.style.height,10))>0.95*parseInt(this.scrollHeight,10)){
				build_log_all_plot();
			}
		}];
		function build_log_sumWaren(){
			//GM_log("build_log_sumWaren filterPlayer="+filterPlayer);
			filterPlayerLow=filterPlayer.toLowerCase();
			var kaufSum1=new Object();
			for(var v in kauf){
				if(!kauf.hasOwnProperty(v)){ continue; }
				if((kauf[v][0].toLowerCase().search(filterPlayerLow)!=-1)){
					for(var prod in kauf[v][3]){
						if(!kauf[v][3].hasOwnProperty(prod)){ continue; }
						if(!kaufSum1[prod]){
							kaufSum1[prod]=[prod,0,0,0];
						}
						kaufSum1[prod][1] += kauf[v][3][prod][0];
						kaufSum1[prod][2] += kauf[v][3][prod][1];
						kaufSum1[prod][3] += (typeof kauf[v][1][0]=="object"?1:0.9)*kauf[v][3][prod][1];
					}
				}
			}
	
			var kaufSum=new Array();
			for(var v in kaufSum1){
				if(!kaufSum1.hasOwnProperty(v)){ continue; }
				kaufSum.push(kaufSum1[v]);
			}
			kaufSum.sort(function(a,b){return b[2]-a[2];});
	
			var container=$("container_system_messages");
			if(build_log_all_scroll[0]){
				build_log_all_scroll[0]=false;
				container.removeEventListener("scroll",build_log_all_scroll[1],false);
			}
			var newtable=createElement("table",{"style":"width: 100%;"});
			container.replaceChild(newtable,container.children[0]);
			var newtablehead=createElement("thead",{},newtable);
			var newtablebody=createElement("tbody",{"class":"hoverRowBgCc9","style":"overflow-y:auto; overflow-x:hidden;height: 209px;"},newtable);
			var newtablefoot=createElement("tfoot",{},newtable);
			var newtr=createElement("tr",{},newtablehead);
			var newtd=createElement("th",{},newtr,texte["product"]);
			createElement("th",{},newtr,texte["menge"]);
			createElement("th",{},newtr,texte["umsatz"]);
			createElement("th",{},newtr,sign_average);
			createElement("th",{},newtr,texte["gewinn"]);
			createElement("th",{},newtr,sign_average);
			var umsatz=0;
			var gewinn=0;
			for(var v=0;v<kaufSum.length;v++){
				umsatz+=kaufSum[v][2];
				gewinn+=kaufSum[v][3];
				newtr=createElement("tr",{"kaufSumId":v,"class":"link"},newtablebody);
				newtr.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,prodName[0][kaufSum[this.getAttribute("kaufSumId")][0]])); },false);
				newtr.addEventListener("click",function(){
					filterPlayer="";
					filterProduct=kaufSum[this.getAttribute("kaufSumId")][0];
					build_log_all();
				},false);
				newtd=createElement("td",{},newtr);
				produktPic(0,kaufSum[v][0],newtd);
				createElement("span",{},newtd,prodName[0][kaufSum[v][0]]);
				createElement("td",{"align":"right","style":"padding-right:3px;border-right:1px solid black"},newtr,numberFormat(kaufSum[v][1],0));
				createElement("td",{"align":"right"},newtr,numberFormat(kaufSum[v][2]));
				createElement("td",{"align":"right","style":"padding-right:3px;border-right:1px solid black"},newtr,numberFormat(kaufSum[v][2]/kaufSum[v][1],2));
				createElement("td",{"align":"right"},newtr,numberFormat(kaufSum[v][3]));
				createElement("td",{"align":"right","style":"padding-right:20px;"},newtr,numberFormat(kaufSum[v][3]/kaufSum[v][1],2));
			}
			newtr=createElement("tr",{},newtablefoot);
			createElement("td",{},newtr);
			createElement("td",{},newtr);
			createElement("td",{"align":"right", "style":"border-top:1px solid"},newtr,numberFormat(umsatz));
			createElement("td",{},newtr);
			createElement("td",{"align":"right", "style":"border-top:1px solid"},newtr,numberFormat(gewinn));
	
			newtable=createElement("table",{"style":"width: 530px;"});
			container.nextElementSibling.replaceChild(newtable,container.nextElementSibling.children[0]);
			newtr=createElement("tr",{},newtable);
			newtd=createElement("td",{"colspan":"2"},newtr);
			var cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["zeigeLog"]},newtd);
			cell.addEventListener("click",function(){
				filterProduct=null;
				build_log_all();
			},false);
	
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr,texte["kaeufer"]+":");
			newtd=createElement("td",{},newtr);
			var cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["summiere"]},newtd);
			cell.addEventListener("click",function(){
				filterProduct=null;
				mode="gewinn";
				build_log_sumKaeufer();
			},false);
	
			createElement("span",{"style":"padding-left:10px;"},newtd,texte["filter"]+":");
			cell=createElement("input",{"value":filterPlayer,"class":"link","style":"width:100px","maxlength":"20"},newtd);
			cell.addEventListener("change",function(){
				filterPlayer=this.value;
				build_log_sumWaren();
			},false);
	
			container=null;newtable=null;newtablehead=null;newtablebody=null;newtablefoot=null;newtr=null;newtd=null;cell=null;
		}
		function build_log_sumKaeufer(){
			//GM_log("build_log_sumKaeufer filterProduct="+filterProduct+" mode="+mode);
			var kaufSum1=new Object();
			for(var v in kauf){
				if(!kauf.hasOwnProperty(v)){ continue; }
				if((filterProduct==null)||(kauf[v][3][filterProduct])){
					if(!kaufSum1[kauf[v][0]]){
						kaufSum1[kauf[v][0]]=new Object();
						kaufSum1[kauf[v][0]]["kaeufer"]=kauf[v][0];
						kaufSum1[kauf[v][0]]["v"]=new Object();
						kaufSum1[kauf[v][0]]["m"]=new Object();
						kaufSum1[kauf[v][0]]["umsatz"]=0;
						kaufSum1[kauf[v][0]]["gewinn"]=0;
					}
					for(var prod in kauf[v][3]){
						if(!kauf[v][3].hasOwnProperty(prod)){ continue; }
						var typ=typeof kauf[v][1][0]=="object"?"v":"m";
						if(!kaufSum1[kauf[v][0]][typ][prod]){ kaufSum1[kauf[v][0]][typ][prod]=[0,0];}
						kaufSum1[kauf[v][0]][typ][prod][0] += kauf[v][3][prod][0];
						kaufSum1[kauf[v][0]][typ][prod][1] += kauf[v][3][prod][1];
						kaufSum1[kauf[v][0]]["umsatz"] += kauf[v][3][prod][1];
						kaufSum1[kauf[v][0]]["gewinn"] += (typ=="v"?1:0.9)*kauf[v][3][prod][1];
					}
				}
			}
	
			var kaufSum=new Array();
			for(var v in kaufSum1){
				if(!kaufSum1.hasOwnProperty(v)){ continue; }
				kaufSum.push(kaufSum1[v]);
			}
			kaufSum.sort(function(a,b){return b[mode]-a[mode];});
	
			var container=$("container_system_messages");
			if(build_log_all_scroll[0]){
				build_log_all_scroll[0]=false;
				container.removeEventListener("scroll",build_log_all_scroll[1],false);
			}
			var newtable=createElement("table",{"style":"width: 100%;line-height:16px;"});
			container.replaceChild(newtable,container.children[0]);
			var newtablehead=createElement("thead",{},newtable);
			var newtablebody=createElement("tbody",{"class":"hoverRowBgCc9","style":"overflow-y:auto; overflow-x:hidden;height: 209px;"},newtable);
			var newtablefoot=createElement("tfoot",{},newtable);
			var newtr=createElement("tr",{},newtablehead);
			var newtd=createElement("th",{},newtr,texte["kaeufer"]);
			createElement("th",{},newtr,texte["product"]);
			createElement("th",{},newtr,texte[mode]);
			createElement("th",{},newtr,sign_average);
			var help=(mode=="gewinn"?0.9:1);
			var sum=0;
			for(var v=0;v<kaufSum.length;v++){
				sum += kaufSum[v][mode];
				newtr=createElement("tr",{"kaufSumId":v},newtablebody);
				newtd=createElement("td",{"class":"link"},newtr,kaufSum[v]["kaeufer"]);
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,this.innerHTML)); },false);
				newtd.addEventListener("click",function(){
					filterPlayer=this.innerHTML;
					filterProduct=null;
					build_log_all();
				},false);
				newtd=createElement("td",{},newtr);
				for(var prod in kaufSum[v]["m"]){
					if(!kaufSum[v]["m"].hasOwnProperty(prod)){ continue; }
					newdiv=createElement("div",{"prod":prod,"class":"link"},newtd);
					produktPic(0,prod,newdiv);
					createElement("span",{},newdiv,numberFormat(kaufSum[v]["m"][prod][0])+"&nbsp;"+prodName[0][prod]);
					newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,prodName[0][this.getAttribute("prod")])); },false);
					newdiv.addEventListener("click",function(){
						filterProduct=this.getAttribute("prod");
						build_log_sumKaeufer();
					},false);
				}
				for(var prod in kaufSum[v]["v"]){
					if(!kaufSum[v]["v"].hasOwnProperty(prod)){ continue; }
					newdiv=createElement("div",{"prod":prod,"class":"link"},newtd);
					produktPic(0,prod,newdiv);
					createElement("span",{"style":"font-style:italic;"},newdiv,numberFormat(kaufSum[v]["v"][prod][0])+"&nbsp;"+prodName[0][prod]);
					newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["filtern"].replace(/%1%/,prodName[0][this.getAttribute("prod")])); },false);
					newdiv.addEventListener("click",function(){
						filterProduct=this.getAttribute("prod");
						build_log_sumKaeufer();
					},false);
				}
				newtd=createElement("td",{"align":"right"},newtr);
				for(var prod in kaufSum[v]["m"]){
					if(!kaufSum[v]["m"].hasOwnProperty(prod)){ continue; }
					createElement("div",{},newtd,numberFormat(help*kaufSum[v]["m"][prod][1]));
				}
				for(var prod in kaufSum[v]["v"]){
					if(!kaufSum[v]["v"].hasOwnProperty(prod)){ continue; }
					createElement("div",{"style":"font-style:italic;"},newtd,numberFormat(kaufSum[v]["v"][prod][1]));
				}
				newtd=createElement("td",{"align":"right"},newtr);
				for(var prod in kaufSum[v]["m"]){
					if(!kaufSum[v]["m"].hasOwnProperty(prod)){ continue; }
					createElement("div",{},newtd,numberFormat(help*kaufSum[v]["m"][prod][1]/kaufSum[v]["m"][prod][0],2));
				}
				for(var prod in kaufSum[v]["v"]){
					if(!kaufSum[v]["v"].hasOwnProperty(prod)){ continue; }
					createElement("div",{"style":"font-style:italic;"},newtd,numberFormat(kaufSum[v]["v"][prod][1]/kaufSum[v]["v"][prod][0],2));
				}
				createElement("td",{"align":"right","style":"padding-right:20px;"},newtr,numberFormat(kaufSum[v][mode]));
	
			}
			newtr=createElement("tr",{},newtablefoot);
			createElement("td",{"colspan":"2"},newtr);
			createElement("td",{"align":"right", "style":"border-top:1px solid"},newtr,numberFormat(sum));
			createElement("td",{"colspan":"2"},newtr);
	
			newtable=createElement("table",{"style":"width: 530px;"});
			container.nextElementSibling.replaceChild(newtable,container.nextElementSibling.children[0]);
			newtr=createElement("tr",{},newtable);
			newtd=createElement("td",{"colspan":"2"},newtr);
			var cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["zeigeLog"]},newtd);
			cell.addEventListener("click",function(){ 
				filterPlayer="";
				build_log_all();
			},false);
			cell=createElement("input",{"type":"button","class":"link msg_input","value":texte[(mode=="gewinn"?"umsatz":"gewinn")]},newtd);
			cell.addEventListener("click",function(){
				mode=(mode=="gewinn"?"umsatz":"gewinn");
				build_log_sumKaeufer();
			},false);
	
			newtr=createElement("tr",{},newtable);
			createElement("td",{},newtr,texte["waren"]+":");
			newtd=createElement("td",{},newtr);
			var cell=createElement("input",{"type":"button","class":"link msg_input", "value":texte["summiere"]},newtd);
			cell.addEventListener("click",function(){
				filterPlayer="";
				build_log_sumWaren();
			},false);
			createElement("span",{"style":"padding-left:10px;"},newtd,texte["filter"]+":");
			cell=createElement("select",{"class":"link2"},newtd);
			createElement("option",{"value":"null"},cell,"");
			for(var v=0;v<prodNameSort[0].length;v++){
				if((!prodBlock[0][prodNameSort[0][v]].match(/t/))&&(!prodBlock[0][prodNameSort[0][v]].match(/l/))){
					createElement("option",{"value":prodNameSort[0][v]},cell,prodName[0][prodNameSort[0][v]]);
				}
			}
			cell.value=filterProduct;
			cell.addEventListener("change",function(){ 
				filterProduct=(this.value=="null"?null:this.value);
				build_log_sumKaeufer();
			},false);
	
			container=null;newtable=null;newtablehead=null;newtablebody=null;newtablefoot=null;newtr=null;newtd=null;cell=null;
		}
		var filterPlayer="";
		var filterPlayerLow="";
		var filterProduct=null;
		var mode="init";
		var kaufArrayHelper=new Array();
		build_log_all();
	}
}

//***********************************************************************************************************

function do_vertraege_head(){
	//GM_log("do_vertraege_head");
	var candtr=document.getElementsByTagName("table")[0].getElementsByTagName("tr");
	for(var v=0;v<candtr[0].childElementCount;v++){
		candtr[0].children[v].setAttribute("class","bordered link hoverBgLightbrown");
		candtr[0].children[v].firstElementChild.setAttribute("class","link");
	}
	var newtd=createElement("td",{"class":"bordered link hoverBgLightbrown","align":"center"},candtr[0]);
	var newa=createElement("a",{"style":"font-weight:bold;"},newtd,texte["alte"]);
	newa.addEventListener("click",function(){
		window.setTimeout(function(){
			GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeOverview",implode({"contractview":"old"}));
			if (PAGE=="vertraege/overview"){ do_vertraege_overview(); }
			else{ location.href="overview.php"; }
		},0);
	},false);
	candtr=null;newtd=null;newa=null;
}

function do_vertraege_new(){
try{
	var err_trace="init";
	loadProductData();
	var candtable=document.getElementsByTagName("table");
	candtable[0].firstElementChild.firstElementChild.firstElementChild.bgColor="lightblue";
	var contractPrices=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegePreise","[]"),"do_vertraege_new/vertraegePreise",[]);

	var candinput=candtable[1].getElementsByTagName("input");
	candtable=null;
	var newdiv;
	if (candinput.length>0){
		// contract submit page
		err_trace="contract submit page";
		var vertraegeOut=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut","{}"),"do_vertraege_new/vertraegeOut",{});
		var valContractLogAmount=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valContractLogAmount",200);
		var neuvertrag=new Array();
		neuvertrag[0]= Math.round((new Date()).getTime()/1000);
		neuvertrag[2]=new Array();
		for(var v=0;v<candinput.length;v++){
			if (candinput[v].name=="contract_to"){
				neuvertrag[1]=candinput[v].value;
				GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_lastContractTo",candinput[v].value);
			}
			else if (candinput[v].name.search("prod")!=-1){ neuvertrag[2][/(\d+)/.exec(candinput[v].name)[1]]=[parseInt(candinput[v].value,10),,]; }
			else if (candinput[v].name.search("anz")!=-1){ neuvertrag[2][/(\d+)/.exec(candinput[v].name)[1]][1]=parseInt(candinput[v].value,10); }
			else if (candinput[v].name.search("preis")!=-1){ neuvertrag[2][/(\d+)/.exec(candinput[v].name)[1]][2]=parseFloat(candinput[v].value,10); }
		}

		var help=[];
		for(var v in vertraegeOut){
			if(!vertraegeOut.hasOwnProperty(v)){ continue; }
			if(vertraegeOut[v][1].toLowerCase()==USERNAME){
				delete vertraegeOut[v];continue;
			}
			help.push(parseInt(v,10));
		}
		help.sort(function(a,b){return(b-a);});
		if(neuvertrag[1].toLowerCase()!=USERNAME){
			if(help.length==0){ help.push(0); }
			vertraegeOut[help[0]+1]=neuvertrag;
		}
		for(var v=valContractLogAmount;v<help.length;v++){
			delete vertraegeOut[help[v]];
		}
		vertraegeOut.sortObj(sortObjFunctions["int"],true);
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut",implode(vertraegeOut));

		if(neuvertrag[1].toLowerCase()!=USERNAME){
			for(var v=0;v<neuvertrag[2].length;v++){
				contractPrices[neuvertrag[2][v][0]]=neuvertrag[2][v][2];
			}
		}
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegePreise",implode(contractPrices));

		// multi submit
		err_trace="multi submit";
		var submitButton=document.getElementsByName("confirm_contract")[0];
		submitButton.style.display="none";
		var newdiv=createElement("div",{"style":"position:absolute;width:300px;height:50px;bottom:135px;left:150px;text-align:center;"},document.getElementsByName("form_confirmcontract")[0].parentNode);
		var newbutton=createElement("input",{"type":"button","class":"link msg_input","id":"multiSubmit","name":"1","value":submitButton.value},newdiv);
		newbutton.addEventListener("click",function(){
			var submitForm=document.getElementsByName("form_confirmcontract")[0];
			var help=submitForm.getElementsByTagName("input");
			var str="";
			for(var v=0;v<help.length;v++){ str += help[v].getAttribute("name")+"="+help[v].value+"&"; }
			str=str.slice(0,str.length-1);
			var c=parseInt(this.getAttribute("name"),10);
			var sentContracts=1;
			for(var d=1;d<c;d++){
				window.setTimeout(function(){
					GM_xmlhttpRequest({
					method: "POST",
					url: "http://s"+SERVER+"."+GAMEPAGES[LNG]+submitForm.getAttribute("action"),
					headers: {"Content-type": "application/x-www-form-urlencoded"},
					data: str,
					onload: function(response){
						showInLogBubble("Sent duplicate contract Nr "+(++sentContracts));
					}
					});
				},d*100);
			}
			window.setTimeout(function(){
				var submitButton=document.getElementsByName("confirm_contract")[0];
				click(submitButton);
				submitButton=null;submitForm=null;
			},c*100);
		},false);
		createElement("div",{},newdiv);
		newbutton=createElement("input",{"type":"button","class":"link msg_input","value":"-"},newdiv);
		newbutton.addEventListener("click",function(){
			var submitButton=document.getElementsByName("confirm_contract")[0];
			var multiSubmitButton=$("multiSubmit");
			multiSubmitButton.setAttribute("name",Math.max(1,parseInt(multiSubmitButton.getAttribute("name"),10)-1));
			if (multiSubmitButton.getAttribute("name")=="1"){ multiSubmitButton.value=submitButton.value; }
			else{ multiSubmitButton.value=multiSubmitButton.getAttribute("name")+"x "+submitButton.value; }
			submitButton=null;multiSubmitButton=null;
		},false);
		newbutton=createElement("input",{"type":"button","class":"link msg_input","value":"+"},newdiv);
		newbutton.addEventListener("click",function(){
			var submitButton=document.getElementsByName("confirm_contract")[0];
			var multiSubmitButton=$("multiSubmit");
			multiSubmitButton.setAttribute("name",parseInt(multiSubmitButton.getAttribute("name"),10)+1);
			multiSubmitButton.value=multiSubmitButton.getAttribute("name")+"x "+submitButton.value;
			submitButton=null;multiSubmitButton=null;
		},false);
		newdiv=null;newbutton=null;submitButton=null;
	}else{
		// contract edit page
		err_trace="contract edit page";
		var pagedata=explode(GM_getValue(LNG+"_"+SERVER+"_pagedataVertraegeNew","{}"),"do_vertraege_new/pagedataVertraegeNew",{});
		GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeNew","{}");

		var candtr=$("addproduct").getElementsByTagName("tr");
		var newtr=createElement("tr");
		candtr[4].parentNode.insertBefore(newtr,candtr[4]);
		createElement("td",{},newtr);
		createElement("td",{},newtr,texte["wert"]);
		var newtd=createElement("td",{"align":"left"},newtr);
		newdiv=createElement("input",{"id":"addproductWert","class":"text msg_input","type":"text","style":"width:100px;"},newtd);
		newdiv.addEventListener("keyup",function(event){
			var preis=parseFloat($("neu_preis").value.replace(regDelimDeci,"."),10);
			if (preis>0){
				$("neu_anzahl").value=Math.floor(0.01+parseFloat(this.value.replace(regDelimThou,"").replace(regDelimDeci,"."),10)/preis);
			}
			if (event.keyCode==13){ click($("btn_add_product")); }
		},false);
		// newdiv.addEventListener("focus",function(){this.style.border="1px solid #555555";},false);
		newdiv.addEventListener("blur",function(){
			this.value=numberFormat(parseInt($("neu_anzahl").value,10)*parseFloat($("neu_preis").value.replace(regDelimDeci,"."),10),2);this.style.border="1px solid #aaa";
		},false);
		if(newdiv=$("neu_anzahl")){
			// newdiv.addEventListener("focus",function(){this.style.border="1px solid #555555";},false);
			newdiv.addEventListener("keyup",function(event){
				var anzahl=parseInt(this.value.replace(/\D/g,""),10);
				$("addproductWert").value=numberFormat(anzahl*parseFloat($("neu_preis").value.replace(regDelimDeci,"."),10),2);
				this.value=(anzahl>0?anzahl:"");
				if (event.keyCode==13){ click($("btn_add_product")); }
			},false);
			// newdiv.addEventListener("blur",function(){this.style.border="1px solid #aaa";},false);
		}
		if(newdiv=$("neu_preis")){
			// newdiv.addEventListener("focus",function(){this.style.border="1px solid #555";},false);
			newdiv.addEventListener("keyup",function(event){
				$("addproductWert").value=numberFormat(parseInt($("neu_anzahl").value,10)*parseFloat(this.value.replace(regDelimDeci,"."),10),2);
				if (event.keyCode==13){ click($("btn_add_product")); }
			},false);
			// newdiv.addEventListener("blur",function(){this.style.border="1px solid #aaa";},false);
		}

		// selected products
		err_trace="selected products";
		/*
		for(var v=0;v<=7;v++){
			 $("delbtn_"+v).addEventListener("mouseover",function(event){
			 	showToolTip(event,texte["loeschen"]);
			 },false);
			$("platzhalter_"+v).addEventListener("mouseover",function(event){
				var currNr=this.id.replace(/platzhalter_/,"");
				prod=parseInt($("produkt_"+currNr).value,10);
				var amount=parseInt($("anzahl_"+currNr).value,10);
				var price=parseFloat($("preis_"+currNr).value.replace(regDelimDeci,"."),10);

				var str='<table class="white" cellspacing="0">';
				str += '<tr><th colspan="2" style="border-bottom:1px solid white;">'+prodName[0][prod]+'</td></tr>';
				str += '<tr><td style="text-align:right;">'+numberFormat(amount)+'&nbsp;'+sign_mult+'</td><td style="text-align:right;">'+moneyFormat(price)+'</td></tr>';
				str += '<tr><td style="text-align:right;">=</td><td style="text-align:right;">'+moneyFormat(amount*price)+'</td></tr>';

				str += '</table>';
				showToolTip(event,str);
			},false);

		}
		*/
		err_trace="currContract";
		var currContract=new Object();
		createElement("div",{"id":"preis_total","style":"position:absolute;top:215px;left:480px;padding:2px;color:black;background-color:#b8a789;border:1px solid black;border-radius:5px;"},ALL);
		// Change of the contract
		//unsafeWindow._buildCart=unsafeWindow.buildCart;
		unsafeWindow.buildCart = function (){
			// try{
			// 	unsafeWindow._buildCart();
			// }catch(err){ GM_log("ERROR _buildCart\n"+err); }		
			try{
				var html = '';
				var count = -1;
				var sum=0,amount,price;
				var newdiv,newdiv1,newdiv2;
				currContract=new Object();
				newdiv=$("contract_cart");
				newdiv.innerHTML = "";
				for(var prod in unsafeWindow.cart){
					if(!unsafeWindow.cart.hasOwnProperty(prod)){ continue; }
					amount=parseInt(unsafeWindow.cart[prod]["anzahl_neu"],10);
					price=parseFloat(unsafeWindow.cart[prod]["preis_neu"].replace(regDelimDeci,"."),10);
					currContract[prod]=[amount,price];
					sum += amount*price;
					count++;

					newdiv1=createElement("div",{"prod":prod,"style":"position:relative;float:left;margin:0 0 5px 5px;"},newdiv);
					newdiv2=createElement("div",{"onclick":"addItem("+prod+")","class":"v"+prod+" link"},newdiv1);
					newdiv2.addEventListener("mouseover",function(event){
						var prod=this.parentNode.getAttribute("prod");
						var amount=currContract[prod][0];
						var price=currContract[prod][1];
						var str='<table class="white" cellspacing="0">';
						str += '<tr><th colspan="2" style="border-bottom:1px solid white;">'+prodName[0][prod]+'</td></tr>';
						str += '<tr><td style="text-align:right;">'+numberFormat(amount)+'&nbsp;'+sign_mult+'</td><td style="text-align:right;">'+moneyFormat(price)+'</td></tr>';
						str += '<tr><td style="text-align:right;">=</td><td style="text-align:right;">'+moneyFormat(amount*price)+'</td></tr>';
						str += '</table>';
						showToolTip(event,str);
					},false);
					newdiv2=createElement("div",{"class":"link","onclick":"removeItem("+prod+")","style":"background:url(http://mff.wavecdn.de/mff/popin/contracts/delete.gif);width:11px; height:11px; position:absolute; top:-2px; right:-2px;"},newdiv1);
					newdiv2.addEventListener("mouseover",function(event){
						showToolTip(event,texte["loeschen"]);
					},false);
					newdiv2=createElement("input",{"type":"hidden","name":"prod["+count+"]","id":"produkt_"+count,"value":prod},newdiv1);
					newdiv2=createElement("input",{"type":"hidden","name":"anz["+count+"]","id":"anzahl_"+count,"value":unsafeWindow.cart[prod].anzahl_neu},newdiv1);
					newdiv2=createElement("input",{"type":"hidden","name":"preis["+count+"]","id":"preis_"+count,"value":unsafeWindow.cart[prod].preis_neu},newdiv1);
				}
				createElement("div",{"style":"clear:both;"},newdiv);
				
				$("preis_total").innerHTML=texte["total"]+":<br>"+moneyFormat(sum);
				newdiv=null;newdiv1=null;newdiv2=null;
			}catch(err){ GM_log("ERROR buildCart\n"+err); }		
		};
		unsafeWindow.buildCart();
		
		// Filling data
		err_trace="Filling data";
		unsafeWindow.fillContract = function(player,data){
			try{
				// player: string or null
				// data: {prod:[amount,single-price],...}
				// set receiver
				if(player){ $("to_player").value=player; }
				// clear data
				unsafeWindow.cart = new Object();
				// fill data
				for(var v in data){
					if(!data.hasOwnProperty(v)){ continue; }
					if(prodStock[0][v]>0){
						unsafeWindow.cart[v] = new Object();
						unsafeWindow.cart[v]["anzahl_neu"]=numberFormat(Math.min(prodStock[0][v],data[v][0]),0,".","");
						unsafeWindow.cart[v]["preis_neu"]=numberFormat(data[v][1],2,".","");
					}
				}
				// call displaying
				unsafeWindow.buildCart();
			}catch(err){ GM_log("ERROR fillContract\n"+err); }
		};
		newdiv=$("to_player");
		if (newdiv){
			if(pagedata["to"]){
				newdiv.value=pagedata["to"];
			}else if(newdiv.value==""){
				newdiv.value=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_lastContractTo","");
			}
		}
		if(pagedata["fillContract"]){
			unsafeWindow.fillContract(null,pagedata["fillContract"]);
		}

		// last message panel
		err_trace="last message panel";
		newdiv=createElement("div",{"id":"lastMessage","style":"position:absolute;top:110px;right:-403px;width:413px;height:134px;padding:5px;background-color:#b8a789;border:2px solid black;border-radius:10px 0px 0px 10px;z-index:101;z-index:15;color:black;overflow:auto;"},ALL,GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_nachrichten_letzte",""));
		newdiv.addEventListener("mouseover",function(){this.style.right="0";},false);
		newdiv.addEventListener("mouseout",function(){this.style.right="-403px";},false);

		// set remembered price
		err_trace="set remembered price";
		unsafeWindow._addItem=unsafeWindow.addItem;
		unsafeWindow.addItem = function (pid){
			try{
				unsafeWindow._addItem(pid);
			}catch(err){ GM_log("ERROR _addItem\npid="+pid+"\n"+err); }		
			try{
				window.setTimeout(function(){
					var contractPrices=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegePreise","[]"),"do_vertraege_new/addproduct/vertraegePreise",[]);
					var cell=$("neu_preis");
					if(cell&&(cell.value=="0")){
						var new_produkt=parseInt(unsafeWindow.addboxid,10);
						if(contractPrices[new_produkt]){
							cell.value=numberFormat(contractPrices[new_produkt],2,delimDeci,"");
							keyup(cell);
						}else if(gut[new_produkt]){
							cell.value=numberFormat(gut[new_produkt],2,delimDeci,"");
							keyup(cell);
						}else if(!isNaN(NPC[0][new_produkt])){
							cell.value=numberFormat(NPC[0][new_produkt],2,delimDeci,"");
							keyup(cell);
						}
					}
					cell=null;
				},0);
			}catch(err){ GM_log("ERROR addItem\npid="+pid+"\n"+err); }
		}

		// save contract, [target user,{"prod":[amount,price],...}]
		err_trace="save contract";
		var contractSave=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_contractSave","[]"),"do_vertraege_new/contractSave",[]);
		var top=345;
		var right=120;
		for(var v=0;v<10;v++){
			right -= 20;
			if(right<=0){
				top += 20;
				right=100;
			}
			newdiv=createElement("div",{"id":"contractSave"+v,"class":"link hoverBgLightblue","style":"position:absolute;top:"+top+"px;right:"+right+"px;width:13px;padding:1px;color:black;text-align:center;border:2px inset black;border-radius:10px;"+(contractSave[v]?"background-color:#bb7;":"")},ALL,v+1);
			newdiv.addEventListener("mouseover",function(event){
				try{
					var contractSave=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_contractSave","[]"),"do_vertraege_new/contractSave/mouseover",[]);
					var currNr=parseInt(this.id.replace(/contractSave/,""),10);
					var str='<table class="white" cellspacing="0" cellpadding="0" style="width:100%;">';
					if(contractSave[currNr]){
						str += '<tr><td>'+texte["click"]+':&nbsp;</td><td>'+texte["laden"]+'</td></tr>';
					}
					str += '<tr><td style="border-bottom:1px solid white;">'+texte["clickStrg"]+':&nbsp;</td><td style="border-bottom:1px solid white;">'+texte["speichern"]+'</td></tr>';
					str += '</table><table class="white" cellspacing="0" cellpadding="0" style="line-height:15px;width:100%;">';
					if(contractSave[currNr]){
						if(contractSave[currNr][0]!=""){
							str += '<tr><td colspan="3">&rarr;&nbsp;'+contractSave[currNr][0]+'</td></tr>';
						}
						for(var v in contractSave[currNr][1]){
							if(!contractSave[currNr][1].hasOwnProperty(v)){ continue; }
							str += '<tr><td style="text-align:right;padding-right:3px;">'+numberFormat(contractSave[currNr][1][v][0])+'</td><td style="padding-right:3px;">'+produktPic(0,v,createElement("div")).parentNode.innerHTML+prodName[0][v]+'</td><td style="text-align:right;">'+moneyFormat(contractSave[currNr][1][v][1])+'</td></tr>';
						}
					}else{
						str += '<tr><td colspan="3">---</td></tr>';
					}
					str += '</table>';
					showToolTip(event,str);
				}catch(err){ GM_log("ERROR contractSave.mouseover\n"+err); }
			},false);
			newdiv.addEventListener("click",function(event){
				try{
					var contractSave=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_contractSave","[]"),"do_vertraege_new/contractSave/click",[]);
					var currNr=parseInt(this.id.replace(/contractSave/,""),10);
					if(event.ctrlKey){
						// save this contract
						contractSave[currNr]=[$("to_player").value,currContract];
						if((contractSave[currNr][0]=="")&&(contractSave[currNr][1].isEmpty())){
							delete contractSave[currNr];
							this.style.backgroundColor="";
						}else{
							this.style.backgroundColor="#bb7";
						}
						GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_contractSave",implode(contractSave));
						adjustToolTip(this);
					}else{
						// load contract
						if(contractSave[currNr]){
							unsafeWindow.fillContract(contractSave[currNr][0]==""?null:contractSave[currNr][0],contractSave[currNr][1]);
						}
					}
				}catch(err){ GM_log("ERROR contractSave.click\n"+err); }
			},false);
		}
		newtr=null;newtd=null;candtr=null;candinput=null;
		raiseEventTop("gameWindowContractNew");
	}
	newdiv=null;
}catch(err){ GM_log("ERROR do_vertraege_new ("+err_trace+")\n"+err); }
}

function do_vertraege_overview(){
	//GM_log("do_vertraege_overview");
	var pagedata=explode(GM_getValue(LNG+"_"+SERVER+"_pagedataVertraegeOverview","{}"),"do_vertraege_overview/pagedataVertraegeOverview",{});
	GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeOverview","{}");
	loadProductData();
	// vertraegeX[id]=[time,person,[[prod,amount,single price],...]]
	var valContractLogAmount=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valContractLogAmount",200);
	var vertraegeIn=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn","{}"),"do_vertraege_overview/vertraegeIn",{});
	// var vertraegeOut=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut","{}"),"do_vertraege_overview/vertraegeOut",{});

	var candtable=document.getElementsByTagName("table");
	candtable[1].parentNode.style.height="310px";
	var candtd=candtable[0].getElementsByTagName("td");
	if (pagedata["contractview"]){
		candtd[1].bgColor="";
		candtd[2].bgColor="lightblue";
		buildAlteVertraege("In");
	}else{
		candtd[1].bgColor="lightblue";
		var candtr=candtable[1].getElementsByTagName("tr");
		var canda,user;
		var sumTotalOut=0;
		for(var v=0;v<candtr.length;v++){
			candtd=candtr[v].getElementsByTagName("td");
			canda=candtr[v].getElementsByTagName("a");
			if (canda[0]){
				var help=/'(\d+)',%20'(.*?)'%20/.exec(canda[0].href);
				if (help[2] == "in"){
					if(LNG=="se"){
						candtd[3].innerHTML=candtd[3].innerHTML.replace(/\.(\d\d)&/,",$1&");
					}
					if (vertraegeIn[help[1]]){
						vertraegeIn[help[1]][0]=getFormattedTime(candtd[0].innerHTML);
					}else{
						user=/(.*?)&nbsp;/.exec(candtd[2].innerHTML+"&nbsp;")[1];
						if(user.toLowerCase()!=USERNAME){
							vertraegeIn[help[1]]= new Array();
							vertraegeIn[help[1]][0]=getFormattedTime(candtd[0].innerHTML);
							vertraegeIn[help[1]][1]=user;
							var help2=candtd[1].firstElementChild.innerHTML.replace(' style=""',"").replace("<b>","").replace("</b>","");
							var preis=parseFloat(candtd[3].innerHTML.replace(/&nbsp;/g+texte["waehrung"],"").replace(regDelimThou,"").replace(regDelimDeci,"."),10);
							if (help2.search(",")==-1){
								var help3=help2.split(" x ");
								vertraegeIn[help[1]][2]=[[prodId[0][help3[1]],parseInt(help3[0],10),preis/parseInt(help3[0],10)]];
							}else{
								vertraegeIn[help[1]][2]=preis;
							}
						}
					}
				}else if(help[2] == "out"){
					if(LNG=="se"){
						candtd[3].innerHTML=candtd[3].innerHTML.replace(/\.(\d\d)&/,",$1&");
					}
					sumTotalOut += parseFloat(candtd[3].innerHTML.replace(regDelimThou,"").replace(regDelimDeci),10);
				}
			}
		}
		createElement("td",{"colspan":"3"},candtable[1]);
		createElement("td",{"style":"border-top:1px solid black;text-align:right;"},candtable[1],moneyFormatInt(sumTotalOut));
		vertraegeIn.sortObj(sortObjFunctions["int"],true);
		var c=0;
		for(var v in vertraegeIn){
			if(!vertraegeIn.hasOwnProperty(v)){ continue; }
			if(vertraegeIn[v][1].toLowerCase()==USERNAME){
				delete vertraegeIn[v];continue;
			}
			if(++c>valContractLogAmount){
				delete vertraegeIn[v];
			}
		}
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn",implode(vertraegeIn));

		candtr=null;canda=null;
	}
	candtable=null;candtd=null;

	function buildAlteVertraege(mode){
		//GM_log("buildAlteVertraege:"+mode);
		if (mode=="In"){ vertraege=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn","{}"),"do_vertraege_overview/vertraegeIn",{}); }
		else{ vertraege=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut","{}"),"do_vertraege_overview/vertraegeOut",{}); }
		var container=document.getElementsByTagName("table")[1].parentNode;
		container.innerHTML="";
		container.setAttribute("mode",mode);
		var newtable=createElement("table",{"style":"width:100%;margin-bottom:3px;"},container);
		var newtr=createElement("tr",{},newtable);
		var newtd=createElement("td",{"class":"link tnormal hoverBgLightbrown","align":"center","style":"color:black;font-weight:bold;"},newtr,texte["erhalteneVertraege"]);
		if (mode=="In"){ newtd.bgColor="lightblue"; }
		newtd.addEventListener("click",function(){buildAlteVertraege("In");},false);
		newtd=createElement("td",{"class":"link tnormal hoverBgLightbrown","align":"center","style":"color:black;font-weight:bold;"},newtr,texte["gesendeteVertraege"]);
		if (mode=="Out"){ newtd.bgColor="lightblue"; }
		newtd.addEventListener("click",function(){buildAlteVertraege("Out");},false);

		newdiv=createElement("div",{"style":"width:100%;height:280px;overflow-x:hidden;overflow-y:scroll;"},container);
		newtable=createElement("table",{"style":"width:100%;","cellspacing":"0"},newdiv);
		var newtablehead=createElement("thead",{},newtable);
		var newtablebody=createElement("tbody",{"class":"hoverRowBgLightbrown","style":"height:290px;overflow-x:hidden;overflow-y:scroll;"},newtable);
		var newtd1,newtd2,newimg;
		var help=((mode=="Out")&&($top("multiframe")));
		for(var v in vertraege){
			if(!vertraege.hasOwnProperty(v)){ continue; }
			newtr=createElement("tr",{"nr":v},newtablebody);
			newtd=createElement("td",{},newtr);
			if(help){
				newtd.setAttribute("class","link borderTop");
				newtd.addEventListener("mouseover",function(event){ showToolTip(event,texte["vertragNochmalSchicken"]); },false);
				newtd.addEventListener("click",function(){
					var help=vertraege[this.parentNode.getAttribute("nr")];
					var thisdata=new Object();
					thisdata["to"]=help[1];
					thisdata["fillContract"]=new Object();
					for(var v=0;v<help[2].length;v++){
						thisdata["fillContract"][help[2][v][0]]=[help[2][v][1],help[2][v][2]];
					}
					GM_setValue(LNG+"_"+SERVER+"_pagedataVertraegeNew",implode(thisdata));
					location.href="http://s"+SERVER+"."+GAMEPAGES[LNG]+"/vertraege/new.php";
				},false);
			}else{
				newtd.setAttribute("class","borderTop");
			}
			if (vertraege[v][0]>0){
				newtd.innerHTML=getFormattedDateStr(vertraege[v][0])+",<br>"+getDaytimeStr(vertraege[v][0],1)+"&nbsp;"+texte["uhr"];
			}else{
				newtd.innerHTML="---";
			}

			newtd=createElement("td",{"class":"borderTop"},newtr,vertraege[v][1]);
			newdiv=createElement("div",{},newtd);
			igm(vertraege[v][1],newdiv);
			stats(vertraege[v][1],newdiv);
			vertrag(vertraege[v][1],newdiv);

			newtd=createElement("td",{"class":"borderTop"},newtr);
			newtd1=createElement("td",{"class":"borderTop","style":"text-align:right;"},newtr);
			newtd2=createElement("td",{"class":"borderTop","style":"text-align:right;"},newtr);
			if(typeof vertraege[v][2]=="object"){
				var sum=0;
				for(var w=0;w<vertraege[v][2].length;w++){
					newdiv=createElement("div",{"class":"link hoverBgLightblue","style":"line-height:16px;white-space:nowrap;","prod":vertraege[v][2][w][0]},newtd);
					newdiv.addEventListener("mouseover",function(event){ showGoToMarketToolTip(event,this.getAttribute("prod")); },false);
					newdiv.addEventListener("click",function(){showMarket(this.getAttribute("prod"));},false);
					produktPic(0,vertraege[v][2][w][0],newdiv);
					createElement("span",{},newdiv,numberFormat(vertraege[v][2][w][1],0) +"&nbsp;"+ prodName[0][vertraege[v][2][w][0]]);
					createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newtd1,moneyFormat(vertraege[v][2][w][2]));
					createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newtd2,moneyFormatInt(vertraege[v][2][w][1]*vertraege[v][2][w][2]));
					sum += vertraege[v][2][w][1]*vertraege[v][2][w][2];
				}
				if (vertraege[v][2].length>1){
					createElement("div",{},newtd,"&nbsp;");
					createElement("div",{},newtd1,"&nbsp;");
					createElement("div",{"style":"border-top:1px solid black;text-align:right;"},newtd2,moneyFormatInt(sum));
				}
			}else{
				createElement("div",{"style":"line-height:16px;white-space:nowrap;"},newtd2,moneyFormatInt(vertraege[v][2]));
			}
			newtd=createElement("td",{"class":"borderTop","style":"text-align:right;padding-right:20px;"},newtr);
			newimg=createElement("img",{"objId":v,"src":GFX+"popin/contracts/anullieren.gif","class":"link2","style":"width:16px;height:16px;"},newtd);
			newimg.addEventListener("mouseover",function(event){ showToolTip(event,texte["loeschen"]); },false);
			newimg.addEventListener("click",function(){
				var objId=this.getAttribute("objId");
				var mode=this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getAttribute("mode");				
				alert2(texte["loeschen"]+"?",texte["yes"],texte["no"],function(){ return function(mode){
					if (mode=="In"){
						var vertraegeIn=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn","{}"),"do_vertraege_overview/vertraegeIn",{});
						delete vertraegeIn[objId];
						GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn",implode(vertraegeIn));
					}else{
						var vertraegeOut=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut","{}"),"do_vertraege_overview/vertraegeOut",{});
						delete vertraegeOut[objId];
						GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeOut",implode(vertraegeOut));
					}
					buildAlteVertraege(mode);
				}(mode)});
			},false);
		}
		container=null;newtable=null;newtablehead=null;newtablebody=null;newtr=null;newtd=null;newtd1=null;newtd2=null;newimg=null;newdiv=null;
	}
}

function do_vertraege_show(){
	var spanError=ALL.getElementsByClassName("error");
	if (spanError.length>0){
		spanError[0].parentNode.style.height="25px";
		spanError[0].parentNode.style.top="262px";
	}
	spanError=null;

	loadProductData();
	if (pageZusatz["typ"]=="in"){
		var vertraegeIn=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn","{}"),"do_vertraege_show/vertraegeIn",{});
	}
	var candtable=document.getElementsByTagName("table");
	var candtr=candtable[1].getElementsByTagName("tr");
	var candtd;
	candtable[1].previousElementSibling.appendChild(candtable[1]);
	candtable[1].setAttribute("style","height:250px;margin-left:auto;margin-right:auto;"); //centering the table
	removeElement(candtable[1].getElementsByTagName("colgroup")[0]);
	candtable[1].firstElementChild.insertBefore(createElement("tr",{"style":"height: 20px;"}),candtable[1].firstElementChild.firstElementChild);
	createElement("td",{"colspan":"3","style":"border-top:1px solid #aaa;padding-right:5px;padding-left:5px;"},candtr[0]);
	createElement("td",{"colspan":"2","style":"border-top:1px solid #aaa;border-left:1px dashed black;padding-right:5px;padding-left:5px;"},candtr[0],texte["preis"]);
	createElement("td",{"style":"border-top:1px solid #aaa;border-left:1px dashed black;padding-right:5px;padding-left:5px;"},candtr[0]);
	createElement("td",{"colspan":"2","style":"border-top:1px solid #aaa;border-left:1px dashed black;padding-right:5px;padding-left:5px;"},candtr[0],texte["marktpreis"]);
	if (pageZusatz["typ"]=="in"){
		if(!vertraegeIn[pageZusatz["v"]]){
			vertraegeIn[pageZusatz["v"]]=new Array();
			vertraegeIn[pageZusatz["v"]][0]=now;
			vertraegeIn[pageZusatz["v"]][1]=/\s*(.*)&nbsp;/.exec(candtable[1].parentNode.innerHTML)[1];
		}
		vertraegeIn[pageZusatz["v"]][2]=new Array();
	}
	var sum=0;
	var borderStr;
	for(var w=1;w<candtr.length-2;w++){
		candtr[w].setAttribute("class","hoverBgLightbrown");
		candtd=candtr[w].getElementsByTagName("td");
		if(LNG=="se"){ candtd[4].innerHTML=candtd[4].innerHTML.replace(/\.(\d\d)\&/,",$1&"); }
		var thisData=[prodId[0][candtd[2].innerHTML],parseInt(candtd[0].innerHTML,10),parseFloat(candtd[4].innerHTML.replace(regDelimThou,"").replace(regDelimDeci,"."),10)];
		if (pageZusatz["typ"]=="in"){
			vertraegeIn[pageZusatz["v"]][2][w-1]=thisData;
		}
		borderStr="border-bottom:"+candtd[0].style.borderBottom+";border-top:"+candtd[0].style.borderTop+";";
		candtd[0].innerHTML=numberFormat(thisData[1]);
		candtd[0].style.paddingRight="5px";
		candtd[1].innerHTML="";
		produktPic(0,thisData[0],candtd[1]);
		removeElement(candtd[3]);
		candtd[2].style.paddingRight="5px";
		candtd[3].style.borderLeft="1px dashed black";
		candtd[3].style.paddingLeft="5px";
		candtd[3].style.paddingRight="5px";
		candtd[3].innerHTML=numberFormat(thisData[2],2)+"&nbsp;:";
		createElement("td",{"style":borderStr+"padding-right:5px;padding-left:5px;text-align:right;"},candtr[w],numberFormat(thisData[1]*thisData[2],2));
		createElement("td",{"style":borderStr+"border-left:1px dashed black;padding-right:5px;padding-left:5px;text-align:right;"},candtr[w],numberFormat(100*thisData[2]/gut[thisData[0]],1)+"%");
		createElement("td",{"style":borderStr+"border-left:1px dashed black;padding-right:5px;padding-left:5px;text-align:right;"},candtr[w],numberFormat(gut[thisData[0]],2)+"&nbsp;:");
		var help=thisData[1]*gut[thisData[0]];
		createElement("td",{"style":borderStr+"padding-right:5px;padding-left:5px;text-align:right;"},candtr[w],numberFormat(help,2));
		sum += help;
	}
	candtd=candtr[candtr.length-2].getElementsByTagName("td");
	//removeElement(candtd[0]);
	candtd[0].style.paddingRight="5px";
	candtd[0].align="left";
	var preis=parseFloat(candtd[1].firstElementChild.innerHTML.replace(regDelimThou,"").replace(regDelimDeci,"."),10);
	candtd[1].firstElementChild.innerHTML=numberFormat(preis,2);
	candtd[1].style.paddingRight="5px";
	createElement("td",{"style":"border-left:1px dashed black;padding-right:5px;padding-left:5px;text-align:right;"},candtr[w],numberFormat(100*preis/sum,1)+"%");
	createElement("td",{"style":"border-left:1px dashed black;padding-right:5px;padding-left:5px;text-align:right;","colspan":"2"},candtr[w],numberFormat(sum,2));

	if (pageZusatz["typ"]=="in"){
		vertraegeIn.sortObj(sortObjFunctions["int"],true);
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_vertraegeIn",implode(vertraegeIn));
	}
	candtable=null;canddiv=null;candtr=null;candtd=null;
}

//***********************************************************************************************************

function do_hilfe(){
	GM_addStyle(".help_content{margin:20px 0 0 0;width: 345px;!IMPORTANT}");
	var canddiv=new Array();
	for(var v=0;v<ALL.childElementCount;v++){ if(ALL.children[v].id=="") canddiv.push(ALL.children[v]); }
	canddiv[1].id="helpmenu";
	canddiv[1].style.left="0";
	canddiv[1].style.width="155px";
	canddiv[1].style.overflowX="hidden";
	canddiv[1].style.overflowY="auto";
	canddiv[2].id="helpbody";
	canddiv=$("helpmenu").getElementsByTagName("div");
	for(var v=0;v<canddiv.length;v++){ if(canddiv[v].getAttribute("class")=="list_header"){ break; }}
	var newdiv=createElement("div",{"id":"helpmenuLinks","style":"margin-bottom:10px;"});
	$("helpmenu").insertBefore(newdiv,canddiv[v]);
	newdiv=createElement("div",{},newdiv);
	var newa=createElement("a",{"class":"list_header","href":"#"},newdiv,texte["berater"]);
	newa.addEventListener("click",function(){
		var cell=$("helpbody");
		cell.innerHTML="";
		createElement("div",{"class":"tnormal"},cell,"<b>"+texte["berater"]+"</b><br>");
		for(var w in texte["hilfe"]){
			if(!texte["hilfe"].hasOwnProperty(w)){ continue; }
			if (Number(w) != w) createElement("div",{"class":"tmenu"},cell,"<b>"+w+"</b>");
			createElement("p",{"class":"tmenu"},cell,texte["hilfe"][w]);
		}
	},false);
	if (GM_getValue("tutorial",0)==0){
		click(newa);
		GM_setValue("tutorial",1);
	}

	switch(pageZusatz["item"]){
	case "18":{ // Questlist
		loadProductData();
		top.unsafeData.questData=explode(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_questData"),"help/questData",INIT_questData);
		GM_addStyle(".divCurrentQuest{background-color:lightblue!important;}");
		var nodes = {};
		nodes["helpbody"]=$("helpbody");
		nodes["questinfos_select"]=createElement("select",{"id":"questinfos_select","class":"link"},nodes["helpbody"].children[0]);
		nodes["questinfos_select"].addEventListener("click",function(){
			for(var v=0;v<this.childElementCount;v++){
				if(this.children[v].value==this.value){
					$("questinfos_"+this.children[v].value).style.display="block";
					do_hilfe_questlist(this.children[v].value);
				}else{
					$("questinfos_"+this.children[v].value).style.display="none";
				}
			}
		},false);
		nodes["questinfos"]=$("questinfos");
		removeElement(nodes["questinfos"].children[nodes["questinfos"].childElementCount-1]);
		
		/*
		var normal_quest=new Array();
		var cand, canddiv, qnr=0;
		for(var v=0;v<$("questinfos").childElementCount;v++){
			try{
				cand = $("questinfos").children[v];
				qnr = parseInt(cand.children[0].innerHTML.replace(".",""),10);
				if(!normal_quest[qnr]){ normal_quest[qnr]= new Array();	}
				if(!normal_quest[qnr][0]){ normal_quest[qnr][0] = new Array(); }
				if(!normal_quest[qnr][3]){ normal_quest[qnr][3] = new Array(); }

				canddiv=cand.children[1];//.getElementsByTagName("div");
				normal_quest[qnr][0][0] = [parseInt(canddiv.children[0].getAttribute("class").replace("kp",""),10),parseInt(canddiv.children[1].innerHTML.replace(/[x*|&nbsp;|\.]/gi,""),10)];
				if(canddiv.children[4]){
					normal_quest[qnr][0][1] = [parseInt(canddiv.children[4].getAttribute("class").replace("kp",""),10),parseInt(canddiv.children[5].innerHTML.replace(/[x*|&nbsp;|\.]/gi,""),10)];
				}else{
					normal_quest[qnr][0][1] = [normal_quest[qnr][0][0][0],0];
				}
				normal_quest[qnr][1] = (v<100?1:2);

				for(var k=0;k<cand.children[2].childElementCount;k++){
					canddiv = cand.children[2].children[k];
					if(canddiv.innerHTML.indexOf("points.gif")>=0){
						normal_quest[qnr][2] = parseInt(canddiv.innerHTML.replace(/.*&nbsp;/,"").replace(/\./g,""),10);
					}else if(canddiv.innerHTML.indexOf("money.gif")>=0){
						//normal_quest[qnr][3].push([0,parseInt(canddiv.innerHTML.replace(/.*&nbsp;/,"").replace(/\./g,""),10)]);
						normal_quest[qnr][3]=[0,parseInt(canddiv.innerHTML.replace(/.*&nbsp;/,"").replace(/\./g,""),10)];
					}else if(canddiv.innerHTML.indexOf("adbonus.gif")>=0){
						//normal_quest[qnr][3].push([5,1]);
						normal_quest[qnr][3]=[5,1];
					}else if(canddiv.className.indexOf("kp")>=0 && cand.children[2].children[k+1].innerHTML.toLowerCase().indexOf("minuten")>=0){  //change to language where reading
						//normal_quest[qnr][3].push([4,parseInt(canddiv.className.replace("kp",""),10),parseInt(cand.children[2].children[k+1].innerHTML.replace(/[A-z ] /,""),10)]);
						normal_quest[qnr][3]=[4,parseInt(canddiv.className.replace("kp",""),10),parseInt(cand.children[2].children[k+1].innerHTML.replace(/[A-z ] /,""),10)];
						k++;
					}else if(canddiv.innerHTML.toLowerCase().indexOf("boerderij")>=0){ //change to language where reading
						//normal_quest[qnr][3].push([3,parseInt(canddiv.innerHTML.replace(/\.[A-z ] /,""),10)]);
						normal_quest[qnr][3]=[3,parseInt(canddiv.innerHTML.replace(/\.[A-z ] /,""),10)];
					}else if(canddiv.innerHTML.toLowerCase().indexOf("voorraadkast")>=0){  //change to language where reading
						//normal_quest[qnr][3].push([2,parseInt(canddiv.innerHTML.replace(/\.[A-z ] /,""),10)]);
						normal_quest[qnr][3]=[2,parseInt(canddiv.innerHTML.replace(/\.[A-z ] /,""),10)];
					}else if(canddiv.className.indexOf("kp")>=0){
						//normal_quest[qnr][3].push([1,parseInt(canddiv.className.replace("kp",""),10)]);
						normal_quest[qnr][3]=[1,parseInt(canddiv.className.replace("kp",""),10)];
					}
					//if (qnr==51){GM_log("qnr:"+qnr+" normal_quest:"+implode(normal_quest[qnr]));}
				}
				if(normal_quest[qnr][3].length==0){ delete normal_quest[qnr][3];}
				//if (qnr==51){GM_log("qnr:"+qnr+" cand:"+canddiv.innerHTML+" "+canddiv.className);}
			}catch(err){GM_log("ERROR at quest nr:"+qnr+" k:"+k+"\n"+err+"\n"+cand.children[2].innerHTML);}
		}
		GM_log("Questlist: "+implode(normal_quest));
		*/

		var line,cell,help;
		var type,prod,amount,item,questCurr,quCamp=1,quNr=0;
		// initial prepare of the tables
		nodes["questinfos_"+quCamp]=createElement("div",{"id":"questinfos_"+quCamp,"style":"color:black;display:block;height:325px;overflow-x:hidden;overflow-y:scroll;"},nodes["helpbody"]);
		createElement("option",{"value":quCamp},nodes["questinfos_select"],quCamp);
		//*task_new_quest*/ var ALL_GEN_QUESTS="";
		while(nodes["questinfos"].childElementCount>0){
			line=nodes["questinfos"].children[0];
			if(line.childElementCount==0){
				quCamp++;
				nodes["questinfos_"+quCamp]=createElement("div",{"id":"questinfos_"+quCamp,"style":"color:black;display:none;height:325px;overflow-x:hidden;overflow-y:scroll;"},nodes["helpbody"]);
				createElement("option",{"value":quCamp},nodes["questinfos_select"],quCamp);
				quNr=0;
				removeElement(line);
			} else {
				quNr++;
				if(QUESTS["farm"][quCamp]&&QUESTS["farm"][quCamp][quNr]){
					line.addEventListener("click",function(){
						var quCamp=this.parentNode.id.replace("questinfos_","");
						top.unsafeData.questData["farm"][quCamp]["nr"]=parseInt(this.children[0].innerHTML,10);
						GM_setValueCache(LNG+"_"+SERVER+"_"+USERNAME+"_questData",implode(top.unsafeData.questData));
						do_hilfe_questlist(quCamp);
						if((0<top.unsafeData.questData["farm"][quCamp]["calcTo"])&&(top.unsafeData.questData["farm"][quCamp]["calcTo"]<top.unsafeData.questData["farm"][quCamp]["nr"])){
							setCalcToQuest("farm",quCamp,top.unsafeData.questData["farm"][quCamp]["nr"]);
						}
					},false);
					questCurr=QUESTS["farm"][quCamp][quNr];
					for(var j=0;j<questCurr[0].length;j++){
						if(typeof questCurr[0][j][0]=="object"){
							for(var k=0;k<questCurr[0][j].length;k++){
								if(isNaN(NPC[questCurr[0][j][k][0]][questCurr[0][j][k][1]])){
									questCurr[0][j][k][3]=Math.round(questCurr[0][j][k][2]*gut[questCurr[0][j][k][1]]*100)/100;
								}else{
									questCurr[0][j][k][3]=Math.round(questCurr[0][j][k][2]*Math.min(gut[questCurr[0][j][k][1]],NPC[questCurr[0][j][k][0]][questCurr[0][j][k][1]])*100)/100;
								}
								questCurr[0][j][k][4]=true;
								for(var l=0;l<k;l++){
									if(questCurr[0][j][l][3]>questCurr[0][j][k][3]){ questCurr[0][j][l][4]=false; }
									else { questCurr[0][j][k][4]=false; }
								}
							}
						}else{
							if(isNaN(NPC[questCurr[0][j][0]][questCurr[0][j][1]])){
								questCurr[0][j][3]=Math.round(questCurr[0][j][2]*gut[questCurr[0][j][1]]*100)/100;
							}else{
								questCurr[0][j][3]=Math.round(questCurr[0][j][2]*Math.min(gut[questCurr[0][j][1]],NPC[questCurr[0][j][0]][questCurr[0][j][1]])*100)/100;
							}
							questCurr[0][j][4]=true;
						}
					}				
					for(var i=0;i<line.children[1].childElementCount;i++){
						cell = line.children[1].children[i];
						cell.style.backgroundColor = "";
						type=0;
						prod=parseInt(cell.children[0].getAttribute("class").replace("kp",""),10);
						amount=parseInt(cell.children[1].innerHTML.replace(/&nbsp;/g,"").replace("x",""),10);
						item=null;
						for(var j=0;j<questCurr[0].length;j++){
							if(typeof questCurr[0][j][0]=="object"){
								for(var k=0;k<questCurr[0][j].length;k++){
									if((type==questCurr[0][j][k][0])&&(prod==questCurr[0][j][k][1])){ item=questCurr[0][j][k]; }
								}
							}else{
								if((type==questCurr[0][j][0])&&(prod==questCurr[0][j][1])){ item=questCurr[0][j]; }
							}
						}	
						if(item){
							if(!item[4]){
								cell.children[1].style.textDecoration="line-through";
								cell.children[2].style.textDecoration="line-through";
							}
							cell.setAttribute("value",implode(item));
							cell.addEventListener("mouseover",function(event){
								var help=explode(this.getAttribute("value"),"questlist/mouseover",[]);
								showToolTip(event,numberFormat(help[2])+" "+prodName[help[0]][help[1]]+" ("+moneyFormatLimit(help[3]/help[2],100)+") = "+moneyFormatLimit(help[3],10000));
							},false);
							if(amount!=item[2]){
								GM_log("Questlist-Help: Quest farm."+quCamp+"."+quNr+". Amount of product "+prodName[type][prod]+ " wrong! data="+numberFormat(item[2])+" read="+numberFormat(amount));
							}
						}else{
							GM_log("Questlist-Help: Quest farm."+quCamp+"."+quNr+". Data of product "+prodName[type][prod]+ " unknown! [i="+i+", prod="+prod+"]"); 
						}
						if(amount>=10000){ cell.children[1].innerHTML="&nbsp;"+numberFormat(amount/1000)+"k&nbsp;"; }
						else { cell.children[1].innerHTML="&nbsp;"+numberFormat(amount)+"&nbsp;"; }
						if(prodBlock[type][prod]){ cell.children[2].style.backgroundColor="red"; }
						createElement("span",{"style":"color:red;"},cell.children[2]);
					}
				}else{
					GM_log("Questlist-Help: Quest farm."+quCamp+"."+quNr+" unknown!");
					//*task_new_quest*/ var GEN_QUESTS=[[],,0];
					//*task_new_quest*/ for(var i=0;i<line.children[1].childElementCount;i++){
					//*task_new_quest*/ 	cell = line.children[1].children[i];
					//*task_new_quest*/ 	type=0;
					//*task_new_quest*/ 	prod=parseInt(cell.children[0].getAttribute("class").replace("kp",""),10);
					//*task_new_quest*/ 	amount=parseInt(cell.children[1].innerHTML.replace(/&nbsp;/g,"").replace("x",""),10);
					//*task_new_quest*/ 	GEN_QUESTS[0].push([type,prod,amount]);
					//*task_new_quest*/ }
					//*task_new_quest*/ GEN_QUESTS[2]=line.children[2].innerHTML;
					//*task_new_quest*/ ALL_GEN_QUESTS+="GEN_QUESTS farm."+quCamp+"."+quNr+"="+implode(GEN_QUESTS)+"\n";
				}
				nodes["questinfos_"+quCamp].appendChild(line);
			}
		}
		//*task_new_quest*/ GM_log(ALL_GEN_QUESTS);
		removeElement(nodes["helpbody"].getElementsByTagName("table")[0]);

		createElement("div",{"id":"questcalculation","style":"position:fixed;top:7px;right:3px;width:80px;"},nodes["helpbody"]);
		var newsel=createElement("select",{"id":"selectQuestCalcTo","style":"position:absolute;top:7px;left:0;width:50px;height:18px;"},$("questcalculation"));
		createElement("div",{"id":"queststocks","style":"position:absolute;top:28px;left:0;width:80px;height:220px;border:1px solid #6c441e;overflow-y:auto;overflow-x:hidden;"},$("questcalculation"));
		var newinp=createElement("input",{"id":"questvsrack","type":"checkbox","class":"link","checked":true,"style":"position:absolute;top:250px;right:3px;"},$("questcalculation"));
		newdiv.addEventListener("mouseover",function(event){ showToolTip(event,texte["zeigeFehlendeProdukte"]); },false);
		newinp.addEventListener("click",function(){change($("selectQuestCalcTo"));},false);
		newsel.addEventListener("change",function(){
			var questinfos_select=$("questinfos_select");
			for(var v=0;v<questinfos_select.childElementCount;v++){
				if($("questinfos_"+questinfos_select.children[v].value).style.display=="block"){
					top.unsafeData.setCalcToQuest("farm",questinfos_select.children[v].value,this.value);
					fill_hilfe_calcToQuest(questinfos_select.children[v].value);
					break;
				}
			}
			questinfos_select=null;
		},false);

		function fill_hilfe_calcToQuest(quCamp){
			var cell=$("queststocks");
			cell.innerHTML="";
			var prd=new Object();
			var cand,prod,help=null;
			for(var v=top.unsafeData.questData["farm"][quCamp]["nr"]-1;v<top.unsafeData.questData["farm"][quCamp]["calcTo"];v++){
				cand=$("questinfos_"+quCamp).children[v].children[1];
				for(var i=0;i<cand.childElementCount;i++){
					help=cand.children[i].getAttribute("value");
					if(help){
						help=explode(help,"fill_hilfe_calcToQuest");
						if(help[4]){
							if (!prd[help[1]]){ prd[help[1]]=0; }
							prd[help[1]] += help[2];
						}
					}
				}
			}
			var counter=0;
			for(var v=0;v<prodNameSort[0].length;v++){
				prod = prodNameSort[0][v];
				//if ($("questvsrack").checked && (prodStock[0][v] > prd[v])) continue;
				if((!prodBlock[0][prod].match(/t/))&&(!prodBlock[0][prod].match(/l/))&&prd[prod]){
					var newdiv=createElement("div",{"style":"display:inline-block;width:100%;background-color:"+(prodBlock[0][prod]?"red":((counter%2)?"#ad9e7d;":"#a59574;"))},cell);
					produktPic(0,prod,newdiv);
					if($("questvsrack").checked){
						if(prodStock[0][prod] < prd[prod]){
							createElement("span",{"style":"color:"+(prodBlock[0][prod]?"black":"red")+ ";"},newdiv,"-"+numberFormat(prd[prod]-prodStock[0][prod]));
						}else{
							createElement("span",{"style":"color:black;"},newdiv,"+"+numberFormat(prodStock[0][prod]-prd[prod]));
						}
					}else{
						createElement("span",{"style":"color:black;"},newdiv,numberFormat(prd[prod]));
					}
					counter++;
				}
			}
			cell=null;newdiv=null;v=null;prd=null;counter=null;cand=null;help=null;prod=null;
		}

		function do_hilfe_questlist(quCamp){
			var questinfos=$("questinfos_"+quCamp);
			var line;
			for(var v=0;v<top.unsafeData.questData["farm"][quCamp]["nr"]-1;v++){
				line=questinfos.children[v];
				if(line.style.opacity!="0.5"){ line.style.opacity="0.5"; }
				if(line.getAttribute("class")!="hoverBgCc9"){ line.setAttribute("class","hoverBgCc9"); }
				// cand=line.getElementsByTagName("div");
				// if(cand[1].style.backgroundColor!=""){ cand[1].style.backgroundColor=""; }
				// if(cand[2].style.backgroundColor!=""){ cand[2].style.backgroundColor=""; }
				// if(cand[5].style.backgroundColor!=""){ cand[5].style.backgroundColor=""; }
				// if(cand[6].style.backgroundColor!=""){ cand[6].style.backgroundColor=""; }
			}

			if(top.unsafeData.questData["farm"][quCamp]["nr"]<=questinfos.childElementCount){
				var newsel=$("selectQuestCalcTo");
				newsel.innerHTML="";
				var prodcounter=new Object();
				createElement("option",{"value":0},newsel,"--");
				for(var v=top.unsafeData.questData["farm"][quCamp]["nr"]-1;v<questinfos.childElementCount;v++){
					createElement("option",{"value":v+1},newsel,v+1);
					line = questinfos.children[v];
					if(line.style.opacity!="1"){ line.style.opacity="1"; }
					if(line.getAttribute("class")!="hoverBgCc9"){ line.setAttribute("class","hoverBgCc9"); }
					for(var i=0;i<line.children[1].childElementCount;i++){
						help=line.children[1].children[i].getAttribute("value");
						if(help){
							help=explode(help,"do_hilfe_questlist",[]);
							if(help[4]){
								if(!prodBlock[help[0]][help[1]]){
									if (!prodcounter[help[1]]){ prodcounter[help[1]]=0; }
									prodcounter[help[1]] += help[2];
									if(v==top.unsafeData.questData["farm"][quCamp]["nr"]-1){
										if(top.unsafeData.questData["farm"][quCamp]["given"][help[0]]&&top.unsafeData.questData["farm"][quCamp]["given"][help[0]][help[1]]){
											prodcounter[help[1]] -= top.unsafeData.questData["farm"][quCamp]["given"][help[0]][help[1]];
										}
									}
									if(prodStock[help[0]][help[1]] < prodcounter[help[1]]){
										if(prodcounter[help[1]]-prodStock[help[0]][help[1]]>10000){
											line.children[1].children[i].children[2].children[0].innerHTML = "&nbsp;(" + numberFormat((prodcounter[help[1]]-prodStock[help[0]][help[1]])/1000) + "k)";
										}else{
											line.children[1].children[i].children[2].children[0].innerHTML = "&nbsp;(" + numberFormat(prodcounter[help[1]]-prodStock[help[0]][help[1]]) + ")";
										}
									}
								}
							}
						}
					}
				}
				questinfos.children[top.unsafeData.questData["farm"][quCamp]["nr"]-1].setAttribute("class","divCurrentQuest");
				if(questinfos.children[top.unsafeData.questData["farm"][quCamp]["nr"]-2]){
					questinfos.scrollTop=questinfos.children[top.unsafeData.questData["farm"][quCamp]["nr"]-2].offsetTop;
				}
				if(top.unsafeData.questData["farm"][quCamp]["calcTo"]>0){
					newsel.value=Math.max(top.unsafeData.questData["farm"][quCamp]["nr"],Math.min(questinfos.childElementCount,top.unsafeData.questData["farm"][quCamp]["calcTo"]));
				}
				fill_hilfe_calcToQuest(quCamp);
				newsel=null;
			}else{
				questinfos.scrollTop=questinfos.lastChildElement.offsetTop;
			}
			questinfos=null;line=null;
		}
		do_hilfe_questlist("1");

		line=null;cell=null;help=null;
		newsel=null;prodcounter=null;newinp=null;
	break; }
	}

	newdiv=null;newa=null;canddiv=null;
}

//***********************************************************************************************************

function do_multiframe(){
	var cell=$top("infoPanel");
	if(cell&&(cell.style.display=="block")){ cell.style.zIndex="99"; }

	cell=$top("multiframe");
	if(cell){
		if(GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_valDrag",false)){ makeDraggable(ALL,true,true,"multiframe"); }
		cell.style.zIndex="101";
		cell.style.display="block";
		cell.style.visibility="visible";
	}
	cell=null;
}

//***********************************************************************************************************
// Dragging
var valMouseXY=["",0,0,0,0];
var dragPos=new Object();
var doDrag=new Object();
function makeDraggable(appendTo,doDragX,doDragY,dragObjId){
	if(typeof(doDragX)!="boolean") doDragX=true;
	if(typeof(doDragY)!="boolean") doDragY=true;
	if(typeof(dragObjId)!="string") dragObjId=appendTo.id;
	//GM_log("makeDraggable:"+appendTo+":"+doDragX+":"+doDragY+":"+dragObjId);
	doDrag[dragObjId]=[doDragX,doDragY];
	var help=GM_getValue(LNG+"_"+SERVER+"_"+USERNAME+"_dragPos_"+dragObjId,"");
	var dragObj=$top(dragObjId);
	if (help){
		dragPos[dragObjId]=help.split("|");
		if(doDragX) dragObj.style.left=dragPos[dragObjId][0]+"px";
		if(doDragY) dragObj.style.top=dragPos[dragObjId][1]+"px";
		dragObj.style.margin="";
		dragObj.style.marginLeft="";
		dragObj.style.marginTop="";
	}else{
		x=parseInt(dragObj.style.left+"0",10)+parseInt(dragObj.style.marginLeft+"0",10);
		y=parseInt(dragObj.style.top+"0",10)+parseInt(dragObj.style.marginTop+"0",10);
		if(doDragX) dragObj.style.left=x+"px";
		if(doDragY) dragObj.style.top=y+"px";
		dragObj.style.margin="";
		dragObj.style.marginLeft="";
		dragObj.style.marginTop="";
		dragPos[dragObjId]=[x,y];
	}

	var newdiv=createElement("div",{"id":dragObjId+"Drag","style":"cursor:move;position:absolute;top:0;left:0;width:10px;height:20px;background-color:blue;opacity:0.4;"},appendTo);
	newdiv.addEventListener("mousedown", function(event){
		valMouseXY=[this.id.replace("Drag",""),"x","y"];
		top.window.addEventListener("mousemove", mousemoveDrag ,false);
		top.window.addEventListener("mouseup", mouseupDrag ,false);
		var dragObj=$top(valMouseXY[0]);
		createElement("div",{"id":"divDragHelper","style":"position:absolute;display:block;z-index:200;height:"+dragObj.style.height+";width:"+dragObj.style.width+";top:"+dragObj.style.top+";left:"+dragObj.style.left+";background-color:blue;"},dragObj.parentNode);
		dragObj=null;
	},false);
	dragObj=null;newdiv=null;
}
mousemoveDrag = function(event){
//GM_log("mousemoveDrag");
	if (valMouseXY[0] != ""){
		if(valMouseXY[1]=="x") valMouseXY=[valMouseXY[0],event.pageX,event.pageY]; // init
		var dragObj=$top(valMouseXY[0]);
		var divDragHelper=$top("divDragHelper");
		if(doDrag[valMouseXY[0]][0]){
			dragObj.style.left=(parseInt(dragObj.style.left+"0",10) + (event.pageX - valMouseXY[1]))+'px';
			divDragHelper.style.left=dragObj.style.left;
		}
		if(doDrag[valMouseXY[0]][1]){
			dragObj.style.top= (parseInt(dragObj.style.top+"0",10) + (event.pageY - valMouseXY[2]))+'px';
			divDragHelper.style.top=dragObj.style.top;
		}
		valMouseXY=[valMouseXY[0],event.pageX,event.pageY];
		dragObj=null;divDragHelper=null;
	}
};
mouseupDrag = function(event){
//GM_log("mouseupDrag");
	top.window.removeEventListener("mousemove", mousemoveDrag ,false);
	if (valMouseXY[0] != ""){
		var dragObj=$top(valMouseXY[0]);
		dragPos[valMouseXY[0]]=[parseInt(dragObj.style.left+"0",10),parseInt(dragObj.style.top+"0",10)];
		GM_setValue(LNG+"_"+SERVER+"_"+USERNAME+"_dragPos_"+valMouseXY[0],dragPos[valMouseXY[0]].join("|"));
		removeElement($top("divDragHelper"));
		dragObj=null;
	}
	valMouseXY=["",0,0,0,0];
	top.window.removeEventListener("mouseup", mouseupDrag ,false);
};

//***********************************************************************************************************
function resetVariables(){
/*
	createElement("div",{"id":"transp100","mode":"","style":"z-index:100;background-color:black;opacity:0.7;position:absolute;top:0;left:0;width:100%;height:100%;display:block;"},$("main_container"));
	newdiv=createElement("div",{"id":"infoPanel","mode":"","style":"position:absolute;top:50px;left:240px;width:660px;height:580px;background-color:#b8a789;z-index:101;display:block;"},$("main_container"));
	createElement("img",{"src":GFX+"guild/help_back.jpg","style":"position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;"},newdiv);
	createElement("div",{"id":"infoPanelInner","class":"tnormal","style":"position:absolute;width:595px;height:89%;margin:5%;overflow:auto;"},newdiv);
	var newimg=createElement("img",{"id":"infoPanelClose","class":"link","src":GFX+"close.jpg","style":"position:absolute;top:8px;right:8px;width:20px;height:20px;"},newdiv);
	newimg.addEventListener("click",function(){
		$("transp100").style.display = "none";
		$("infoPanel").style.display = "none";
	},false);

	try{
		var loginStr = new Array(new Object(), new Object(), new Object(), new Object());//[0]=global,[1]=server,[2]=user,[3]=vars over
		var listVars = GM_listValues();
		var found = false;
		try{logindata=explode(GM_getValue("logindata","[]"),"resetVariables\logindata");
			for(var v=0;v<logindata.length;v++){
				loginStr[0][logindata[v][0]]=true;
				loginStr[1][logindata[v][0]+"_"+logindata[v][1]]=true;
				loginStr[2][logindata[v][0]+"_"+logindata[v][1]+"_"+logindata[v][2]]=true;
			}
			loginStr[0].sortObj();
			GM_log("loginStr[0]:"+implode(loginStr[0]));
			loginStr[1].sortObj();
			GM_log("loginStr[1]:"+implode(loginStr[1]));
			loginStr[2].sortObj();
			GM_log("loginStr[2]:"+implode(loginStr[2]));

			for(var v in listVars){
				if(!listVars.hasOwnProperty(v)){continue;}
				found=false;
				for(var elm in loginStr[2]){
					if(!loginStr[2].hasOwnProperty(elm)){continue;}
					if(help=listVars[v].match(new RegExp("^"+elm+"_(.*)"))){
						found=true;
						loginStr[3][help[1]]=true;
					}
				}
				if(!found){
					for(var elm in loginStr[1]){
						if(!loginStr[1].hasOwnProperty(elm)){continue;}
						if(help=listVars[v].match(new RegExp("^"+elm+"_[^_]*_(.*)"))){
							found=true;
							loginStr[3][help[1]]=true;
						}
					}
				}
				if(found){
					delete listVars[v];
				}
			}
			loginStr[3].sortObj();
			GM_log("loginStr[3]:"+implode(loginStr[3]));
			listVars.sort();
			GM_log("listVars:"+implode(listVars));

		}catch(err){GM_log("1:"+err);}
	}catch(err){GM_log("2:"+err);}
	return false;
*/
	if(confirm("Do you really want to reset zone data?")){
		var help=GM_listValues();
		var help2;
		for(var v=0;v<help.length;v++){
			if(help[v].match(/_gut$/)){if(GM_getValue(help[v],"").indexOf("|")>0){ GM_deleteValue(help[v]); }}
			if(help[v].match(/_gutBeob$/)){if(GM_getValue(help[v],"").indexOf("|")>0){ GM_deleteValue(help[v]); }}

			if(help[v].match(/_prodName$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodNameSort$/)){GM_deleteValue(help[v]);}

			if(help[v].match(/_valGlobalTimeAdd$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_zoneEndTimes$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_zoneWaterTimes$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_zoneEndProducts$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_lodgeQuestData$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodStock$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodMinRack$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodMinRackInit$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_zoneErnte_0$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_zoneErnte$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_totalForestryFarmis$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodYield$/)){GM_deleteValue(help[v]);}
			if(help[v].match(/_prodRequire$/)){GM_deleteValue(help[v]);}

			if(help[v].match(/_changedata$/)){GM_deleteValue(help[v]);}
		}
		// GM_log(print_r(total));
		GM_deleteValue("loginbusy");
		location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1";
	}
}
function manageVariables(){
	// 1: historic data - not reproducible!
	// 2: collectable data
	// 3: options, settings
	// 4: temporary data = 2?
	// 5: useless, old data
	const variableInfo = {
				"USER":{"bargeld":["Cash amount",2],
						"calcToLodgeCampaign":["Target lodge campaign",3],
						"calcToLodgeQuest":["Target lodge quest",5],
						"calcToQuest":["Target quest",3],
						"changedata":["Data version",1],
						"clubmemberLog":["Log-data club",1],
						"contractSave":["Saved contract templates",3],
						"css_styles":["CSS",3],
						"farmiLog":["Log-data farmies",1],
						"farmiOk":["Limit at farmi-log",3],
						"farmname":["Name of farm",2],
						"highlight":["Highlighted users",3],
						"highlightProducts":["Highlighted products",3],
						"infoPanelFormulas":["Mode",4],
						"kauf":["Log-data sales",1],
						"lastContractTo":["Last contract recipient",2],
						"lastOffer":["Last market offer",2],
						"levelLog":["Log-data points",1],
						"lodgeCampaignNr":["Lodge campaign",5],
						"lodgeQuestData":["Lodge quest data",5],
						"lodgeQuestNr":["Lodge quest number",5],
						"lodgeTimeEnd":["Lodge quest time",5],
						"lotteryCollectForPrize":["Lottery collect data",3],
						"lotteryLastLot":["Lottery taken time",2],
						"lotteryLog":["Log-data lottery",1],
						"marketOffers":["Market offers",5],
						"ownMarketOffers":["Own market offers",2],
						"marketOfferTimes":["Market offer times",5],
						"modeBuildPreise":["Mode",4],
						"modeBuyNotepad":["Mode",4],
						"modeLotteryLog":["Mode",4],
						"modeMarket":["Mode",4],
						"modeProfittable":["Mode",4],
						"modeProfittableFeed":["Mode",4],
						"modeProfittableSterne":["Mode",4],
						"modeStockTable":["Mode",4],
						"nachrichten":["Messages",1],
						"nachrichten_doread":["Messages auto-read",4],
						"nachrichten_doreadState":["Messages auto-read",4],
						"nachrichten_letzte":["Messages",2],
						"nachrichten_system":["Messages",2],
						"nachrichtvorlage":["Message template",3],
						"notepad":["Notepad",3],
						"prodBestand":["Rack amounts",2],
						"prodBlock":["Blocked products",2],
						"prodGrowTime":["Product growtime",2],
						"prodMinRack":["Minimal rackamounts",2],
						"prodMinRackInit":["Minimal rackamounts",3],
						"prodRequire":["Recursive needed products",5],
						"prodStock":["Product stock",2],
						"prodStockMax":["Product stock limit",2],
						"prodYield":["Product yield",2],
						"quest":["Quest number",5],
						"questState":["Quest state",5],
						"questTime":["Quest time",5],
						"questData":["Quest data",2],
						"raisedEvents":["Raised events",4],
						"session":["Session",4],
						"show":["Mode",4],
						"totalFarmis":["Farmi needings",2],
						"valAssumeWater":["Option",3],
						"valAutoCrop":["Option",3],
						"valAutoWater":["Option",3],
						"valClickErrorbox":["Option",3],
						"valContractLogAmount":["Option",3],
						"valDrag":["Option",3],
						"valEmptyFieldForestLimit":["Option",5],
						"valErnte":["Option",5],
						"valErnteMsg":["Option",3],
						"valFarmiLimits":["Option",3],
						"valFarmiMiniInfo":["Option",3],
						"valGamecursor":["Option",3],
						"valGiess":["Option",5],
						"valGiessAnnehm":["Option",5],
						"valGiessNotw":["Option",5],
						"valGlobalTimeAdd":["Option",3],
						"valGlobaltimeShowCroppedZone":["Option",3],
						"valHotkey":["Option",3],
						"valJoinPreise":["Option",3],
						"valKauflimit":["Option",3],
						"valKauflimitNPC":["Option",3],
						"valLeereFelderLimit":["Option",5],
						"valLimitEmptyFields":["Option",3],
						"valMessageRe":["Option",3],
						"valMinRack":["Option",3],
						"valMinRackE":["Option",5],
						"valMinRackF":["Option",5],
						"valMinRackP":["Option",5],
						"valMinRackV":["Option",5],
						"valMinRackFarmis":["Option",3],
						"valMinRackForestryFarmis":["Option",3],
						"valMinRackGrowing":["Option",3],
						"valMinRackLodgeQuest":["Option",5],
						"valMinRackMan":["Option",3],
						"valMinRackPlantsize":["Option",3],
						"valMinRackQuest":["Option",5],
						"valMinRackRecursive":["Option",3],
						"valMoveAnimals":["Option",3],
						"valMsgFormat":["Option",3],
						"valNachr":["Option",3],
						"valPrivNachr":["Option",3],
						"valProtectMinRack":["Option",3],
						"valQuicklinks":["Option",3],
						"valSpoilerZoneUpdate":["Option",3],
						"valStatistik":["Option",3],
						"valStatistikNpc":["Option",3],
						"valStatistikTime":["Option",3],
						"valVerkaufLimitDown":["Option",3],
						"valVerkaufLimitUp":["Option",3],
						"valWaterNeeded":["Option",3],
						"vertraegeIn":["Contracts received",1],
						"vertraegeOut":["Contracts sent",1],
						"vertraegePreise":["Contract prices",3],
						"zoneAnimals":["Amount of animals",2],
						"zoneBlock":["Blocked zones",2],
						"zoneBonus":["Zones bonus",2],
						"zoneBonusSpecialAmount":["Zone special product",2],
						"zoneBonusSpecialProduct":["Zone special product",2],
						"zoneEndProducts":["Zones productions",2],
						"zoneEndTimes":["Zones endtimes",2],
						"zoneErnte":["Zones productions",2],
						"zoneFieldData":["Zones productions",5],
						"zoneProductionData":["Zones productions",2],
						"zoneMainprod":["Zones productions",2],
						"zoneTyp":["Zones types",2],
						"zoneWaterTimes":["Times watering",2]},
			  "SERVER":{"buildPreiseShowAll":["Mode",5],
						"changedata":["Data version",1],
						"competition":["Competition data",2],
						"farmNamen":["Farm names",2],
						"gut":["Product prices",3],
						"gutBeob":["Product observed prices",2],
						"NpcSaison":["Products saisons",2],
						"pagedataNachrichtenNew":["Page attributes",4],
						"pagedataStadtMarktstand":["Page attributes",4],
						"pagedataVertraegeNew":["Page attributes",4],
						"pagedataVertraegeOverview":["Page attributes",4],
						"preisBeob":["Price observation",2],
						"prodId":["Product names lookup",2],
						"prodName":["Product names",2],
						"prodNameSort":["Product names",2],
						"prodPlantSize":["Plant sizes",2],
						"prodPoints":["Product points",2],
						"prodRequire":["Recursive needed products",2],
						"prodTyp":["Product types",2],
						"sessionlost":["Page attributes",4],
						"username":["Username",4],
						"valNimmBeob":["Option",3]},
				 "LNG":{"changedata":["Data version",1],
						"pagedataLogin":["Page attributes",4],
						"valServerTimeOffset":["Option",3]},
			  "GLOBAL":{"changedata":["Data version",1],
						"devmode":["Option",3],
						"devmode_function":["Option",3],
						"devmode_events":["Option",3],
						"hotkeymap":["Option",3],
						"loginbusy":["Page attributes",4],
						"logindata":["Accounts",3],
						"tutorial":["Tutorial step",1],
						"updateCheck":["Script update",2],
						"valAutoLogin":["Option",3],
						"valUpdate":["Option",3]}
			};
	function buildManageVariables(){
		var container=$("divManageVariablesInner");
		container.innerHTML="";
		var containerPart = createElement("div",{"style":"height:10%;"},container);
		createElement("div",{"style":"font-weight:bold;"},containerPart,"Variable Management "+texte["berater"]);

		var newinput=createElement("select",{"class":"link"},containerPart);
		createElement("option",{"value":"GLOBAL"},newinput,"GLOBAL");
		createElement("option",{"value":"ALL"},newinput,"ALL");
		createElement("option",{"value":"UNKNOWN"},newinput,"UNKNOWN");
		createElement("option",{"value":"USELESS"},newinput,"USELESS");
		newinput.addEventListener("click",function(){
			buildExportTable(this.value);
		},false);

		var variables = {};
		variables["GLOBAL"] = [];
		var help = GM_listValues();
		help.sort();
		var help2;					
		for(var v=0;v<help.length;v++){
			help2 = (/^([a-z]{2}_\d+_.+?_)(.*)$/).exec(help[v]); // LNG_SERVER_USER_...
			if(!help2){ help2 = (/^([a-z]{2}_\d+_)(.*)$/).exec(help[v]); // LNG_SERVER_...
				if(!help2){ help2 = (/^([a-z]{2}_)(.*)$/).exec(help[v]); // LNG_...
			}	}
			
			if(help2){
				if(!variables[help2[1]]){ 
					variables[help2[1]] = []; 
					createElement("option",{"value":help2[1]},newinput,help2[1]);
				}
				variables[help2[1]].push(help2[2]);
			} else {
				variables["GLOBAL"].push(help[v]); // GLOBAL
			}
		}

		newinput=createElement("button",{"class":"link","style":"margin-left:20px;"},containerPart,"Select all");
		newinput.addEventListener("click",function(){
			var container=$("divManageVariablesInner");
			var rows = container.children[1].getElementsByTagName("tr");
			var checkedNew;
			if(this.innerHTML=="Select all"){
				checkedNew = true;
				this.innerHTML="Unselect all";
			} else {
				checkedNew = false;
				this.innerHTML="Select all";
			}
			for (var v=0;v<rows.length;v++){
				rows[v].children[0].children[0].checked = checkedNew;
			}
			
		},false);

		newinput=createElement("button",{"class":"link","style":"margin-left:20px;"},containerPart,"Delete");
		newinput.addEventListener("click",function(){
			var container=$("divManageVariablesInner");
			var rows = container.children[1].getElementsByTagName("tr");
			var variables = [];
			var acc, varname;
			var str = "Delete following variables:";
			for (var v=0;v<rows.length;v++){
				if(rows[v].children[0].children[0].checked){
					acc = rows[v].children[1].innerHTML;
					varname = rows[v].children[2].innerHTML;
					variables.push(acc+varname);
					if(variables.length<11){ str += "\n"+acc+varname; }
				}
			}
			if(variables.length>0){
				if(variables.length>10){ str += "\n..." }
				if(confirm(str)){
					for (var v=0;v<variables.length;v++){
						GM_deleteValue(variables[v]);
					}
					buildManageVariables();
				}
			} else {
				alert("Nothing selected");
			}
		},false);
	
		newinput=createElement("button",{"class":"link","style":"margin-left:20px;"},containerPart,"Create storage string");
		newinput.addEventListener("click",function(){
			var container=$("divManageVariablesInner");
			var rows = container.children[1].getElementsByTagName("tr");
			var variables = [];
			var acc, varname;
			for (var v=0;v<rows.length;v++){
				if(rows[v].children[0].children[0].checked){
					acc = rows[v].children[1].innerHTML;
					varname = rows[v].children[2].innerHTML;
					variables.push([acc+varname,GM_getValue(acc+varname)]);
				}
			}
			if(variables.length>0){
				prompt("Copy this string to a text-file", implode(variables));
			} else {
				alert("Nothing selected");
			}
		},false);

		newinput=createElement("button",{"class":"link","style":"margin-left:20px;"},containerPart,"Import storage string");
		newinput.addEventListener("click",function(){
			var data = prompt("Enter storage string");
			if(data){
				try{
					data = explode(data,"buildImportTable/storageString");
					buildImportTable(data);
				}catch(err){ alert("Sorry. Can't read the entered string.\n"+err); }
			}
		},false);
		
		newinput=createElement("button",{"class":"link","style":"margin-left:20px;"},containerPart,"Import OLD storage string");
		newinput.addEventListener("click",function(){
			var data = prompt("Enter storage string");
			var user = prompt("Enter prefix like 'de_7_Johnny_' if needed");
			if(data){
				try{
					data=data.split("::");
					for(var v=0;v<data.length;v++){
						data[v] = [,data[v].split(":")];
						data[v][0] = user+data[v][1].splice(0,1)[0];
						var impType=data[v][1].splice(0,1)[0];
						data[v][1] = data[v][1].join(":");
						if(impType == "n"){ data[v][1] = parseFloat(data[v][1],10); }
						else if(impType == "b"){ data[v][1] = (data[v][1]=="true"); }
					}
					buildImportTable(data);
				}catch(err){ alert("Sorry. Can't read the entered string.\n"+err); }
			}
		},false);
		
		containerPart = createElement("div",{"style":"height:90%;overflow-y:scroll;"},container);
		function buildExportTable(filter){
			var container=$("divManageVariablesInner");
			container.children[1].innerHTML = "";
			var newtable=createElement("table",{"border":"1","class":"hoverRowBgCc9","style":"width:100%"},container.children[1]);
			var newtr,newtd;
			var help=GM_listValues();
			var help2;
			for(var v=0;v<help.length;v++){
				help2 = (/^([a-z]{2}_\d+_.+?_)(.*)$/).exec(help[v]); // LNG_SERVER_USER_...
				if(help2){ 
					help[v] = [help2[1],help2[2],"USER"];
				} else {
					help2 = (/^([a-z]{2}_\d+_)(.*)$/).exec(help[v]); // LNG_SERVER_...
					if(help2){
						help[v] = [help2[1],help2[2],"SERVER"];
					} else {
						help2 = (/^([a-z]{2}_)(.*)$/).exec(help[v]); // LNG_...
						if(help2){
							help[v] = [help2[1],help2[2],"LNG"];
						} else {
							help[v] = ["",help[v],"GLOBAL"];
						}
					}	
				}
			}
			help.sort(function(a,b){
				if(a[0]==b[0]){ return ((a[1]>b[1])-(a[1]<b[1])); }
				          else{ return ((a[0]>b[0])-(a[0]<b[0])); }
			});

			for(var v=0;v<help.length;v++){
				switch(filter){
				case "ALL": break;
				case "GLOBAL":if(help[v][0]!=""){ continue; } break;
				case "UNKNOWN":if(variableInfo[help[v][2]][help[v][1]]){ continue; } break;
				case "USELESS":if((!variableInfo[help[v][2]][help[v][1]])||(variableInfo[help[v][2]][help[v][1]][1]!=5)){ continue; } break;
				default: if(help[v][0]!=filter){ continue; }
				}
				
				help[v][4] = GM_getValue(help[v][0]+help[v][1]);
				help[v][3] = "s";
				// if(help[v][4]==""){ help[v][4]=" "; }
				if(typeof help[v][4]=="number"){ help[v][3]="n"; }
				else if(typeof help[v][4]=="boolean"){ help[v][3]="b"; }
				else{	// help[v][4] = help[v][4].replace(/(:+)/g,":");
						if(help[v][4].length>100){
							help[v][4] = help[v][4].substr(0,97)+"..."; 
						}
					}
				
				newtr=createElement("tr",{},newtable);
				newtd = createElement("td",{},newtr);
				createElement("input",{"type":"checkbox","class":"link","checked":false},newtd);
				createElement("td",{},newtr,help[v][0]);
				createElement("td",{},newtr,help[v][1]);
				createElement("td",{},newtr,help[v][3]);
				if(variableInfo[help[v][2]][help[v][1]]){
					createElement("td",{},newtr,variableInfo[help[v][2]][help[v][1]][0]);
					createElement("td",{},newtr,[,"historic data - not reproducible!","collectable data","options, settings","temporary data","useless, old data"][variableInfo[help[v][2]][help[v][1]][1]]);
				} else {
					createElement("td",{},newtr,"unknown");
					createElement("td",{},newtr,"");
				}
				createElement("td",{},newtr,help[v][4]);
			
			}
			container=null;newtable=null;newtr=null;newtd=null;
		}
		buildExportTable("GLOBAL");

		function buildImportTable(data){
			var container=$("divManageVariablesInner");
			container.children[1].innerHTML = "";
			var newinput=createElement("button",{"class":"link"},container.children[1],"SAVE !");
			newinput.addEventListener("click",function(){
				var container=$("divManageVariablesInner");
				var rows = container.children[1].getElementsByTagName("tr");
				var variables = [];
				var acc, varname;
				for (var v=0;v<rows.length;v++){
					if(rows[v].children[0].children[0].checked){
						GM_setValue(data[v][0]+data[v][1],data[v][3]);
					}
				}
				buildManageVariables();
			},false);
			var newtable=createElement("table",{"border":"1","class":"hoverRowBgCc9","style":"width:100%"},container.children[1]);
			var newtr,newtd;
			var help2;
			var dataLevel;
			for(var v=0;v<data.length;v++){
				help2 = (/^([a-z]{2}_\d+_.+?_)(.*)$/).exec(data[v][0]); // LNG_SERVER_USER_...
				if(help2){ 
					dataLevel = "USER";
					data[v] = [help2[1],help2[2],"s",data[v][1]];
				} else {
					help2 = (/^([a-z]{2}_\d+_)(.*)$/).exec(data[v][0]); // LNG_SERVER_...
					if(help2){
						dataLevel = "SERVER";
						data[v] = [help2[1],help2[2],"s",data[v][1]];
					} else {
						help2 = (/^([a-z]{2}_)(.*)$/).exec(data[v][0]); // LNG_...
						if(help2){
							dataLevel = "LNG";
							data[v] = [help2[1],help2[2],"s",data[v][1]];
						} else {
							dataLevel = "GLOBAL";
							data[v] = ["",data[v][0],"s",data[v][1]];
						}
					}	
				}
				if(typeof data[v][3]=="number"){ data[v][2]="n"; }
				else if(typeof data[v][3]=="boolean"){ data[v][2]="b"; }

				newtr=createElement("tr",{},newtable);
				newtd = createElement("td",{},newtr);
				createElement("input",{"type":"checkbox","class":"link","checked":true},newtd);
				createElement("td",{},newtr,data[v][0]);
				createElement("td",{},newtr,data[v][1]);
				createElement("td",{},newtr,data[v][2]);
				if(variableInfo[dataLevel][data[v][1]]){
					createElement("td",{},newtr,variableInfo[dataLevel][data[v][1]][0]);
					createElement("td",{},newtr,[,"historic data - not reproducible!","collectable data","options, settings","temporary data","useless, old data"][variableInfo[dataLevel][data[v][1]][1]]);
				} else {
					createElement("td",{},newtr,"unknown");
					createElement("td",{},newtr,"");
				}
				if(data[v][3].length>100){
					createElement("td",{},newtr,data[v][3].substr(0,97)+"...");
				} else {
					createElement("td",{},newtr,data[v][3]);
				}
			}
			container=null;newtable=null;newtr=null;newtd=null;newinput=null;
		}

		container=null;containerPart=null;newselect=null;
		newdiv=null;newinput=null;
	}

	if($("divManageVariables")){ return false; }
	var newdiv=createElement("div",{"id":"divManageVariables","mode":"","style":"position:fixed;top:0;left:0;width:100%;height:100%;background-color:#b8a789;z-index:1000;display:block;"},ALL);
	createElement("img",{"src":GFX+"guild/help_back.jpg","style":"position:absolute;top:0;left:0;width:100%;height:100%;z-index:-1;"},newdiv);
	createElement("div",{"id":"divManageVariablesInner","class":"tnormal","style":"position:absolute;top:6%;left:5%;width:90%;height:88%;overflow:auto;"},newdiv);
	var newimg=createElement("img",{"id":"infoPanelClose","class":"link","src":GFX+"close.jpg","style":"position:absolute;top:8px;right:8px;width:20px;height:20px;"},newdiv);
	newimg.addEventListener("click",function(){ removeElement(this.parentNode); },false);
	newdiv = null;newimg=null;
	buildManageVariables();
}

function do_login(){
	try{
		if(top!=self){ return; }
		if((location.pathname.match(/^\/login\.php$/))&&(pageZusatz["logout"]=="1")){
			GM_log("Logout-page found ("+location.href+").\nReturn to login-page.");
			window.setTimeout(function(){ location.href="http://www."+GAMEPAGES[LNG]+"/login.php?start=1"; },1000); // go to login-page after logout (old page)
		}else if($("login_container")){
			do_login_old();
		}else if($("loginbar")){
			GM_log("Login-page found ("+location.href+")\npagedata="+implode(pagedata));		
			// paypal
			var newform=createElement("form",{"id":"paypalForm","action":"https://www.paypal.com/cgi-bin/webscr","method":"post","style":"position:absolute;left:50%;margin-left:-300px;top:120px;"},$("content"));
			createElement("input",{"type":"hidden","name":"cmd","value":"_donations"},newform);
			createElement("input",{"type":"hidden","name":"business","value":"jessicakanaan@web.de"},newform);
			createElement("input",{"type":"hidden","name":"lc","value":((LNG=="de")?"DE":"US")},newform);
			createElement("input",{"type":"hidden","name":"item_name","value":"MyFreeFarm Script"},newform);
			createElement("input",{"type":"hidden","name":"no_note","value":"0"},newform);
			createElement("input",{"type":"hidden","name":"currency_code","value":"EUR"},newform);
			createElement("input",{"type":"hidden","name":"bn","value":"PP-DonationsBF:btn_donate_LG.gif:NonHostedGuest"},newform);
			createElement("input",{"type":"image","border":"0","src":"https://www.paypal.com/"+((LNG=="de")?"de_DE/DE":"en_US")+"/i/btn/btn_donate_LG.gif","name":"submit",alt:"PayPal"},newform);
			createElement("img",{"alt":"","border":"0","src":"https://www.paypal.com/en_US/i/scr/pixel.gif","width":"1","height":"1"},newform);
			newform=null;
			// account data
			var logindata=explode(GM_getValue("logindata","[]"),"do_login/logindata",[]);
			var c=0;
			var servers=new Object(); // servers["language_serverNr"]=[logindataNr,logindataNr,...]
			for(var v=0;v<logindata.length;v++){ 
				if(logindata[v][4]){
					c++;
					if(!servers[logindata[v][0]+"_"+logindata[v][1]]){ servers[logindata[v][0]+"_"+logindata[v][1]]=new Array(); }
					servers[logindata[v][0]+"_"+logindata[v][1]].push(v);
				}	
			}
			// listener login-form to store username
			$("loginelements").querySelector("#loginbutton").parentNode.addEventListener("submit",function(){
				try{
					var currServer=this.querySelector("#loginserver").value;
					var currUser=this.querySelector("#loginusername").value.toLowerCase();
					GM_log("Login submitted. Server="+currServer+", user="+currUser);
					GM_setValueCache(LNG+"_"+currServer+"_username",currUser.toLowerCase());
				}catch(err){ GM_log("ERROR login_container listener\n"+err); }
			},false);
			// execute login
			function submit_login(accNr){
				window.setTimeout(function(){
					try{
						var logindata=explode(GM_getValue("logindata"),"submit_login/logindata",[]);
						if(logindata[accNr][0]==LNG){
							var login_container=$("loginelements");
							login_container.querySelector("#loginserver").value=logindata[accNr][1];
							login_container.querySelector("#loginusername").value=logindata[accNr][2];
							login_container.querySelector("#loginpassword").value=enc(logindata[accNr][3],-4242);
							GM_setValueCache(LNG+"_"+logindata[accNr][1]+"_username",logindata[accNr][2].toLowerCase());
							click(login_container.querySelector("#loginbutton"));
							login_container=null;
						}else{
							var help=explode(GM_getValue(logindata[accNr][0]+"_pagedataLogin","{}"),"submit_login/pagedataLogin",{});
							if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
								help["dologin"]=new Object();
							}
							help["dologin"][accNr]=true;
							GM_setValue(logindata[accNr][0]+"_pagedataLogin",implode(help));
							location.href="http://www."+GAMEPAGES[logindata[accNr][0]]+"/login.php?start=1";
						}
					}catch(err){ GM_log("ERROR submit_login("+accNr+")\n"+err); }
				},0);
			}
			var currDoLogin=null;
			var currDoServer=null;
			var pagedata=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"do_login/pagedataLogin",{});
			if(pagedata["doserver"]){
				if(typeof pagedata["doserver"]=="object"){
					for(var v in pagedata["doserver"]){
						if(!pagedata["doserver"].hasOwnProperty(v)){ continue; }
						currDoServer=v;
						delete pagedata["doserver"][v];
						break;
					}
					if(pagedata["doserver"].isEmpty()){ delete pagedata["doserver"]; }
				}else{
					delete pagedata["doserver"];
				}
			}else if(pagedata["dologin"]){
				if(typeof pagedata["dologin"]=="object"){
					for(var v in pagedata["dologin"]){
						if(!pagedata["dologin"].hasOwnProperty(v)){ continue; }
						currDoLogin=v;
						delete pagedata["dologin"][v];
						break;
					}
					if(pagedata["dologin"].isEmpty()){ delete pagedata["dologin"]; }
				}else{
					delete pagedata["dologin"];
				}
			}
			GM_setValue(LNG+"_pagedataLogin",implode(pagedata));
			if(currDoServer!=null){
				var help=GM_getValue(LNG+"_"+currDoServer+"_username","");
				for(var v=0;v<logindata.length;v++){
					if((logindata[v][4])&&(logindata[v][0]==LNG)&&(logindata[v][1]==currDoServer)&&(logindata[v][2].toLowerCase()==help)){
						currDoLogin=v;
						break;
					}
				}
				if(currDoLogin!=null){
					for(var v=0;v<logindata.length;v++){
						if((logindata[v][4])&&(logindata[v][0]==LNG)&&(logindata[v][1]==currDoServer)){
							currDoLogin=v;
							break;
						}
					}
				}
			}
			if(currDoLogin!=null){
				submit_login(currDoLogin);
			}else{
				GM_addStyle(
					 ".loginbutton{background-color:white;color:black;text-align:center;font-weight:bold;width:250px;line-height:20px;margin:3px;border:3px solid #6c441e;border-radius:10px;}\n"
					+".loginbutton:hover{background-color:lightblue;}"
				);
				// newbutton=createElement("div",{"class":"link loginbutton","id":"resetvariables","style":"background-color:red;position:absolute;top:-200px;"},newdiv,"Reset Variables");
				// newbutton.addEventListener("click",function(){
				// 	resetVariables();
				// },false);
				// Button manage variables
				var newdiv=createElement("div",{"id":"GM_manageVariables","style":"position:absolute;left:50%;margin-left:250px;top:120px;"},$("content"));
				var newbutton=createElement("div",{"class":"link loginbutton","style":"background-color:orange;"},newdiv,"Manage Variables "+texte["berater"]); // TODO texte
				newbutton.addEventListener("click",function(){
					if($("divInfo")){ click($("divInfo")); }
				 	manageVariables();
				},false);
				// Buttons accounts
				newdiv=createElement("div",{"style":"position:absolute;left:50%;margin-left:-125px;top:205px;height:263px;overflow-x:hidden;overflow-y:auto;padding-right:17px;"},$("content"));
				for(var v=0;v<logindata.length;v++){ if(logindata[v][4]){
					newbutton=createElement("div",{"class":"link loginbutton","id":"autologin"+v},newdiv,texte["server"]+"&nbsp;"+logindata[v][1]+"."+logindata[v][0]+":&nbsp;"+logindata[v][2]);
					newbutton.addEventListener("click",function(){
						if($("divInfo")){ click($("divInfo")); }
						submit_login(this.id.replace("autologin",""));
					},false);
				}}
				// Autologin
				var lastbusy=GM_getValue("loginbusy",0);
				if (isNaN(lastbusy) || now<lastbusy){ lastbusy=0; }
				if (GM_getValue("valAutoLogin",false) && (c>0) && (now-lastbusy>15)){
					GM_setValue("loginbusy",now);
					newdiv=createElement("div",{"id":"divInfo","class":"round transp shadow","style":"position:absolute;left:50%;margin-left:-150px;top:470px;height:130px;width:300px;z-index:200;"},$("content"));
					createElement("div",{"class":"buttontext4","style":""},newdiv,texte["autologinChecking"].replace(/%1%/,"5"));
					newdiv.addEventListener("click",function(){
						removeElement(this);
					},false);
					for(var v in servers){
						if(!servers.hasOwnProperty(v)){ continue; }
						GM_setValue(v+"_sessionlost",true);
					}
					var counter=5;
					function autologinLoop(){
						counter -= 0.5;
						if(!$("divInfo")){ return false; }
						if(counter>0){
							$("divInfo").firstElementChild.innerHTML=texte["autologinChecking"].replace(/%1%/,Math.ceil(counter));
							var c=0;
							for(var v in servers){
								if(!servers.hasOwnProperty(v)){ continue; }
								if (GM_getValue(v+"_sessionlost",true)){
									c++;
								}else{
									var help=GM_getValue(v+"_username","");
									for(var w=0;w<servers[v].length;w++){
										$("autologin"+servers[v][w]).style.backgroundColor=(logindata[servers[v][w]][2].toLowerCase()==help?"#00ff00":"#008800");
									}
									//delete servers[v];
								}
							}
							if(c==0){ counter=0; }
							window.setTimeout(autologinLoop,500);
						}else{
							var c=null;
							for(var v in servers){
								if(!servers.hasOwnProperty(v)){ continue; }
								if (GM_getValue(v+"_sessionlost",true)){
									if (c==null){
										c=servers[v][0];
									}else{
										var help=explode(GM_getValue(logindata[servers[v][0]][0]+"_pagedataLogin","{}"),"autologinLoop/pagedataLogin",{});
										if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
											help["dologin"]=new Object();
										}
										help["dologin"][servers[v][0]]=true;
										GM_setValue(logindata[servers[v][0]][0]+"_pagedataLogin",implode(help));
										window.open("http://www."+GAMEPAGES[logindata[servers[v][0]][0]]+"/login.php?start=1");
									}
								}
							}
                
							if (c==null){
								// all logged in
								$("divInfo").firstElementChild.innerHTML=texte["autologinAllOk"];
								window.setTimeout(function(){
									for(var v in servers){
										if(!servers.hasOwnProperty(v)){ continue; }
										for(var w=0;w<servers[v].length;w++){
											$("autologin"+servers[v][w]).style.backgroundColor="white";
										}
										GM_setValue(v+"_sessionlost",true);
									}
									now=Math.floor((new Date()).getTime()/1000);
									GM_setValue("loginbusy",now);
									counter=5;
									autologinLoop();
								},5000);
							}else{
								GM_setValue("loginbusy",0);
								submit_login(c);
							}
						}
					}
					window.setTimeout(autologinLoop,500);
				}
				newdiv=null;newbutton=null;
			}
		}
	}catch(err){ GM_log("ERROR do_login\n"+err); }
}
function do_login_old(){
	try{
		GM_log("Old login-page found ("+location.href+")");
		//paypal
		var newform=createElement("form",{"id":"paypalForm","action":"https://www.paypal.com/cgi-bin/webscr","method":"post","style":"position:absolute;top:30px;left:117px;"},ALL);
		createElement("input",{"type":"hidden","name":"cmd","value":"_donations"},newform);
		createElement("input",{"type":"hidden","name":"business","value":"jessicakanaan@web.de"},newform);
		createElement("input",{"type":"hidden","name":"lc","value":((LNG=="de")?"DE":"US")},newform);
		createElement("input",{"type":"hidden","name":"item_name","value":"MyFreeFarm Script"},newform);
		createElement("input",{"type":"hidden","name":"no_note","value":"0"},newform);
		createElement("input",{"type":"hidden","name":"currency_code","value":"EUR"},newform);
		createElement("input",{"type":"hidden","name":"bn","value":"PP-DonationsBF:btn_donate_LG.gif:NonHostedGuest"},newform);
		createElement("input",{"type":"image","border":"0","src":"https://www.paypal.com/"+((LNG=="de")?"de_DE/DE":"en_US")+"/i/btn/btn_donate_LG.gif","name":"submit",alt:"PayPal"},newform);
		createElement("img",{"alt":"","border":"0","src":"https://www.paypal.com/en_US/i/scr/pixel.gif","width":"1","height":"1"},newform);
		newform=null;
        
		//login
		var logindata=explode(GM_getValue("logindata","[]"),"do_login/logindata",[]);
		var c=0;
		var servers=new Object(); // servers["language_serverNr"]=[logindataNr,logindataNr,...]
		for(var v=0;v<logindata.length;v++){ 
			if(logindata[v][4]){
				c++;
				if(!servers[logindata[v][0]+"_"+logindata[v][1]]){ servers[logindata[v][0]+"_"+logindata[v][1]]=new Array(); }
				servers[logindata[v][0]+"_"+logindata[v][1]].push(v);
			}	
		}
        
		$("login_container").querySelector("#submitlogin").addEventListener("click",function(){
			try{
				var login_container=$("login_container");
				var currServer=login_container.querySelector("#loginserver").value;
				var currUser=login_container.querySelector("#loginusername").value.toLowerCase();
				GM_setValueCache(LNG+"_"+currServer+"_username",currUser.toLowerCase());
				login_container=null;
			}catch(err){ GM_log("ERROR login_container listener\n"+err); }
		},false);
        
		function submit_login(accNr){
			window.setTimeout(function(){
				try{
					var logindata=explode(GM_getValue("logindata"),"submit_login/logindata",[]);
					if(logindata[accNr][0]==LNG){
						var login_container=$("login_container");
						login_container.querySelector("#loginserver").value=logindata[accNr][1];
						login_container.querySelector("#loginusername").value=logindata[accNr][2];
						login_container.querySelector("#loginpassword").value=enc(logindata[accNr][3],-4242);
						GM_setValueCache(LNG+"_"+logindata[accNr][1]+"_username",logindata[accNr][2].toLowerCase());
						click(login_container.querySelector("#submitlogin"));
						login_container=null;
					}else{
						var help=explode(GM_getValue(logindata[accNr][0]+"_pagedataLogin","{}"),"submit_login/pagedataLogin",{});
						if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
							help["dologin"]=new Object();
						}
						help["dologin"][accNr]=true;
						GM_setValue(logindata[accNr][0]+"_pagedataLogin",implode(help));
						location.href="http://www."+GAMEPAGES[logindata[accNr][0]]+"/login.php?start=1";
					}
				}catch(err){ GM_log("ERROR submit_login("+accNr+")\n"+err); }
			},0);
		}
			
		var currDoLogin=null;
		var currDoServer=null;
		var pagedata=explode(GM_getValue(LNG+"_pagedataLogin","{}"),"do_login/pagedataLogin",{});
		GM_log("This is do_login_old@"+location.href+". pagedata:"+implode(pagedata));
		if(pagedata["doserver"]){
			if(typeof pagedata["doserver"]=="object"){
				for(var v in pagedata["doserver"]){
					if(!pagedata["doserver"].hasOwnProperty(v)){ continue; }
					currDoServer=v;
					delete pagedata["doserver"][v];
					break;
				}
				if(pagedata["doserver"].isEmpty()){ delete pagedata["doserver"]; }
			}else{
				delete pagedata["doserver"];
			}
		}else if(pagedata["dologin"]){
			if(typeof pagedata["dologin"]=="object"){
				for(var v in pagedata["dologin"]){
					if(!pagedata["dologin"].hasOwnProperty(v)){ continue; }
					currDoLogin=v;
					delete pagedata["dologin"][v];
					break;
				}
				if(pagedata["dologin"].isEmpty()){ delete pagedata["dologin"]; }
			}else{
				delete pagedata["dologin"];
			}
		}
		GM_setValue(LNG+"_pagedataLogin",implode(pagedata));

		if(currDoServer!=null){
			var help=GM_getValue(LNG+"_"+currDoServer+"_username","");
			for(var v=0;v<logindata.length;v++){
				if((logindata[v][4])&&(logindata[v][0]==LNG)&&(logindata[v][1]==currDoServer)&&(logindata[v][2].toLowerCase()==help)){
					currDoLogin=v;
					break;
				}
			}
			if(currDoLogin!=null){
				for(var v=0;v<logindata.length;v++){
					if((logindata[v][4])&&(logindata[v][0]==LNG)&&(logindata[v][1]==currDoServer)){
						currDoLogin=v;
						break;
					}
				}
			}
		}
        
		if(currDoLogin!=null){
			submit_login(currDoLogin);
		}else{
			var newdiv=createElement("div",{"style":"position:relative;top:-400px;left:300px;"},$("login_container"));
			var newbutton;
			GM_addStyle(
				 ".loginbutton{background-color:white;color:black;text-align:center;font-weight:bold;width:250px;line-height:20px;margin:3px;border:3px solid #6c441e;border-radius:10px;}\n"
				+".loginbutton:hover{background-color:lightblue;}"
			);

			newbutton=createElement("div",{"id":"GM_manageVariables","style":"position:absolute;top:-200px;"},newdiv);
			newbutton=createElement("div",{"class":"link loginbutton","style":"background-color:orange;"},newbutton,"Manage Variables "+texte["berater"]); // TODO texte
			newbutton.addEventListener("click",function(){
				if($("divInfo")){ click($("divInfo")); }
			 	manageVariables();
			},false);
        
			
			for(var v=0;v<logindata.length;v++){ if(logindata[v][4]){
				newbutton=createElement("div",{"class":"link loginbutton","id":"autologin"+v},newdiv,texte["server"]+"&nbsp;"+logindata[v][1]+"."+logindata[v][0]+":&nbsp;"+logindata[v][2]);
				newbutton.addEventListener("click",function(){
					if($("divInfo")){ click($("divInfo")); }
					submit_login(this.id.replace("autologin",""));
				},false);
			}}
        
			//Autologin
			var lastbusy=GM_getValue("loginbusy",0);
			if (isNaN(lastbusy) || now<lastbusy){ lastbusy=0; }
			if (GM_getValue("valAutoLogin",false) && (c>0) && (now-lastbusy>15)){
				GM_setValue("loginbusy",now);
				newdiv=createElement("div",{"id":"divInfo","style":"position:absolute;top:190px;left:455px;height:200px;width:280px;background-color:#842;border:4px solid black;z-index:200;"},$("main_container"),"<h1>"+texte["autologinChecking"].replace(/%1%/,"5")+"</h1>");
				newdiv.addEventListener("click",function(){
					removeElement(this);
				},false);
           
				for(var v in servers){
					if(!servers.hasOwnProperty(v)){ continue; }
					GM_setValue(v+"_sessionlost",true);
				}
				var counter=5;
				function autologinLoop(){
					counter -= 0.5;
					if(!$("divInfo")){ return false; }
					if(counter>0){
						$("divInfo").innerHTML="<h1>"+texte["autologinChecking"].replace(/%1%/,Math.ceil(counter))+"</h1>";
						var c=0;
						for(var v in servers){
							if(!servers.hasOwnProperty(v)){ continue; }
							if (GM_getValue(v+"_sessionlost",true)){
								c++;
							}else{
								var help=GM_getValue(v+"_username","");
								for(var w=0;w<servers[v].length;w++){
									$("autologin"+servers[v][w]).style.backgroundColor=(logindata[servers[v][w]][2].toLowerCase()==help?"#00ff00":"#008800");
								}
								//delete servers[v];
							}
						}
						if(c==0){ counter=0; }
						window.setTimeout(autologinLoop,500);
					}else{
						var c=null;
						for(var v in servers){
							if(!servers.hasOwnProperty(v)){ continue; }
							if (GM_getValue(v+"_sessionlost",true)){
								if (c==null){
									c=servers[v][0];
								}else{
									var help=explode(GM_getValue(logindata[servers[v][0]][0]+"_pagedataLogin","{}"),"autologinLoop/pagedataLogin",{});
									if(!(help["dologin"]&&(typeof help["dologin"]=="object"))){
										help["dologin"]=new Object();
									}
									help["dologin"][servers[v][0]]=true;
									GM_setValue(logindata[servers[v][0]][0]+"_pagedataLogin",implode(help));
									window.open("http://www."+GAMEPAGES[logindata[servers[v][0]][0]]+"/login.php?start=1");
								}
							}
						}
        
						if (c==null){
							// all logged in
							$("divInfo").innerHTML="<h1>"+texte["autologinAllOk"]+"</h1>";
							window.setTimeout(function(){
								for(var v in servers){
									if(!servers.hasOwnProperty(v)){ continue; }
									for(var w=0;w<servers[v].length;w++){
										$("autologin"+servers[v][w]).style.backgroundColor="white";
									}
									GM_setValue(v+"_sessionlost",true);
								}
								now=Math.floor((new Date()).getTime()/1000);
								GM_setValue("loginbusy",now);
								counter=5;
								autologinLoop();
							},5000);
						}else{
							GM_setValue("loginbusy",0);
							submit_login(c);
						}
					}
				}
				window.setTimeout(autologinLoop,500);
			}
			newdiv=null;newbutton=null;
		}
	}catch(err){ GM_log("ERROR do_login\n"+err); }
}
//***********************************************************************************************************

window.addEventListener("load",function(){
try{
var err_trace="init";
unsafeData.beraterVersion=VERSION;
// Userscripts.org
err_trace="Userscripts.org";
if(location.href==USO_Home){
	if($("summary")&&$("install_script")){
		var uso_version=/<p><b>Version:<\/b>(\d+\.\d+\.\d+)<\/p>/gi.exec($("summary").innerHTML.replace(/\s/gi,""))[1];
		if(compareVersions(uso_version,VERSION)<1){
			$("install_script").firstElementChild.innerHTML="Already installed";
		}else{
			$("install_script").firstElementChild.innerHTML="Update ("+VERSION+"&nbsp;&rarr;&nbsp;"+uso_version+")";
		}
	}
	return false;
}
// Multilingual
err_trace="Multilingual";
if(top.unsafeData.texte==undefined){
	texte=new Object();
	if (location.hostname.match(GAMEPAGES["au"])){
		LNG="au";
		delimThou=",";
		regDelimThou=",";
		regDelimThou2="([\\d\\.])(\\d),(\\d{1,2}\\D)";
		regDelimThou3="(\\d),(,*)(\\d{1,2}\\D)";
		delimDeci=".";
		regDelimDeci="\\.";
		texte["waehrung"]="pD";
		texte["coins"]="Coins";
		texte["msgMarketsale"]="Marketplace";
		texte["msgMarketsaleContent"]="(.*) bought\\s*(\\d+)x (.*?) for\\s*<br>\\s*(.*?) pD from you\\.";
		texte["msgContractsale"]="A contract has been accepted";
		texte["msgContractsaleContent"]="(.*) has signed a contract of yours!<br><br>\\s*The following products have been sold:<br>([\\S\\s]*)\\s*<br>\\s*The amount of (.*?) pD has been credited to your account\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) would like to add you as a friend";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+for\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["br"])){
		LNG="br";
		delimThou=",";
		regDelimThou=",";
		regDelimThou2="([\\d,])(\\d),(\\d{1,2}\\D)";
		regDelimThou3="(\\d),(,*)(\\d{1,2}\\D)";
		delimDeci=".";
		regDelimDeci="\\.";
		texte["waehrung"]="pD";
		texte["coins"]="Moedas";
		texte["msgMarketsale"]="Mercado";
		texte["msgMarketsaleContent"]="(.*) comprou a voc"+e_circumflex+" \\s*(\\d+)x (.*?) por\\s*<br>\\s*(.*?) pD\\.";
		texte["msgContractsale"]="Um contrato foi aceite";
		texte["msgContractsaleContent"]="(.*) assinou um contrato com voc"+e_circumflex+"!<br><br>\\s*Foram vendidos os seguintes produtos:<br>([\\S\\s]*)\\s*<br>\\s*Foram creditados (.*?) pD na sua conta\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) gostaria de adicionar voc"+e_circumflex+" como";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+para\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["bu"])){
		LNG="bu";
		delimThou=".";
		regDelimThou="\\.";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=",";
		regDelimDeci=",";
		texte["waehrung"]=cyr_ka+cyr_De;
		texte["coins"]=cyr_Ka+cyr_er+cyr_ie+cyr_de+cyr_i+cyr_te+cyr_i;
		texte["msgMarketsale"]=cyr_Pe+cyr_a+cyr_ze+cyr_a+cyr_er;		
		texte["msgMarketsaleContent"]="(.*) "+cyr_ze+cyr_a+cyr_ka+cyr_u+cyr_pe+cyr_i+"\\s*(\\d+)x (.*?) "+cyr_ze+cyr_a+"<br>\\s*(.*?) "+cyr_ka+cyr_De+" "+cyr_o+cyr_te+" "+cyr_te+cyr_ie+cyr_be+"\\.";
		texte["msgContractsale"]=cyr_Pe+cyr_er+cyr_i+cyr_ie+cyr_te+ +cyr_de+cyr_o+cyr_ghe+cyr_o+cyr_ve+cyr_o+cyr_er;
		texte["msgContractsaleContent"]="(.*) "+cyr_ie+" "+cyr_pe+cyr_o+cyr_de+cyr_pe+cyr_i+cyr_es+cyr_a+cyr_el+" "+cyr_ve+cyr_a+cyr_sha+" "+cyr_de+cyr_o+cyr_ghe+cyr_o+cyr_ve+cyr_o+cyr_er+"!<br><br>\\s*"+cyr_Es+cyr_el+cyr_ie+cyr_de+cyr_en+cyr_i+cyr_te+cyr_ie+" "+cyr_pe+cyr_er+cyr_o+cyr_de+cyr_u+cyr_ka+cyr_te+cyr_i+" "+cyr_es+cyr_a+" "+cyr_be+cyr_i+cyr_el+cyr_i+" "+cyr_pe+cyr_er+cyr_o+cyr_de+cyr_a+cyr_de+cyr_ie+cyr_en+cyr_i+":<br>([\\S\\s]*)\\s*<br>\\s*"+cyr_Es+cyr_u+cyr_em+cyr_a+cyr_te+cyr_a+" "+cyr_o+cyr_te+" (.*?) "+cyr_ka+cyr_De+" "+cyr_ie+" "+cyr_pe+cyr_er+cyr_ie+cyr_ve+cyr_ie+cyr_de+cyr_ie+cyr_en+cyr_a+" "+cyr_ve+cyr_hardsign+cyr_ve+" "+cyr_ve+cyr_a+cyr_sha+cyr_i+cyr_ya+cyr_te+" "+cyr_a+cyr_ka+cyr_a+cyr_u+cyr_en+cyr_te+"\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) wants to add you as friend";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+"+cyr_ze+cyr_a+"\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["de"])){
		LNG="de";
		delimThou=".";
		regDelimThou="\\.";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=",";
		regDelimDeci=",";
		texte["waehrung"]="kT";
		texte["coins"]="Coins";
		texte["msgMarketsale"]="Marktplatz";
		texte["msgMarketsaleContent"]="(.*) hat am Marktplatz\\s*(\\d+)x (.*?) von dir<br>\\s*f"+u_dots+"r (.*?) kT gekauft\\.";
		texte["msgContractsale"]="Ein Vertrag wurde angenommen";
		texte["msgContractsaleContent"]="(.*) hat einen Vertrag von dir unterzeichnet!<br><br>\\s*Folgende Produkte wurden verkauft:<br>([\\S\\s]*)\\s*<br>\\s*Die Vertragssumme von (.*?) kT wurde deinem Konto gutgeschrieben\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) m"+o_dots+"chte dich als Freund hinzuf"+u_dots+"gen";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+zu je\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["dk"])){
		LNG="dk";
		delimThou=".";
		regDelimThou="\\.";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=",";
		regDelimDeci=",";
		texte["waehrung"]="kD";
		texte["coins"]="Coins";
		texte["msgMarketsale"]="Markedsplads";
		texte["msgMarketsaleContent"]="(.*) har ved markedspladsen k"+o_stroke+"bt\\s*(\\d+)x (.*?) af dig<br>\\s*for(.*?) kD\\.";
		texte["msgContractsale"]="En kontrakt blev accepteret";
		texte["msgContractsaleContent"]="(.*) har underskrevet en kontrakt fra dig!<br><br>\\s*F"+o_stroke+"lgende produkter blev solgt:<br>([\\S\\s]*)\\s*<br>\\s*Kontraktsummen p"+a_ring+" (.*?) kD blev indsat p"+a_ring+" din konto\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) m"+o_dots+"chte dich als Freund hinzuf"+u_dots+"gen";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+til hver\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["es"])){
		LNG="es";
		delimThou=".";
		regDelimThou="\\.";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=",";
		regDelimDeci=",";
		texte["waehrung"]="MG";
		texte["coins"]="Coins";
		texte["msgMarketsale"]="Mercado";
		texte["msgMarketsaleContent"]="(.*) te ha comprado\\s*(\\d+) (.*?)\\s*<br>\\s*por (.*?) MG en el mercado\\.";
		texte["msgContractsale"]="Un contrato ha sido aceptado";
		texte["msgContractsaleContent"]=invert_exclamation+"(.*) ha firmado un contrato tuyo!<br><br>\\s*Los siguientes productos se han vendido:<br>([\\S\\s]*)\\s*<br>\\s*El importe del contrato de (.*?) MG se ha sumado a tu cuenta\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) would like to add you as a friend";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+por\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["fr"])){
		LNG="fr";
		delimThou=".";
		regDelimThou="\\.";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=",";
		regDelimDeci=",";
		texte["waehrung"]="fL";
		texte["coins"]="Coins";
		texte["msgMarketsale"]="March"+e_ac;
		texte["msgMarketsaleContent"]="(.*) a achet"+e_ac+"\\s*(\\d+)x (.*?) pour\\s*(.*?) fL\\.";
		texte["msgContractsale"]="Un contrat a "+e_ac+"t"+e_ac+" accept"+e_ac;
		texte["msgContractsaleContent"]="(.*) a sign"+e_ac+" un de tes contrats!<br><br>\\s*Les produits suivants ont "+e_ac+"t. vendu:<br>([\\S\\s]*)\\s*<br>\\s*Le total de (.*?) fL a "+e_ac+"t"+e_ac+" cr"+e_ac+"dit"+e_ac+" "+a_grave+" ton compte\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) souhaite t'ajouter "+a_grave+" ses amis";
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+"+a_grave+"\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEPAGES["gr"])){
		LNG="gr";
		delimThou=",";
		regDelimThou=",";
		regDelimThou2="([\\d\\.])(\\d)\\.(\\d{1,2}\\D)";
		regDelimThou3="(\\d)\\.(\\.*)(\\d{1,2}\\D)";
		delimDeci=".";
		regDelimDeci="\\.";
		texte["waehrung"]="pD";
		texte["coins"]=greek_Kappa+greek_epsilon_tonos+greek_rho+greek_mu+greek_alpha+greek_tau+greek_alpha;
		texte["msgMarketsale"]=greek_Alpha+greek_gamma+greek_omicron+greek_rho+greek_alpha_tonos;
		texte["msgMarketsaleContent"]="(.*) "+greek_alpha+greek_gamma+greek_omicron_tonos+greek_rho+greek_alpha+greek_sigma+greek_epsilon+"\\s*(\\d+)x (.*?) "+greek_gamma+greek_iota+greek_alpha+"<br>\\s*(.*?) pD "+greek_alpha+greek_pi+greek_omicron+" "+greek_epsilon+greek_sigma+greek_epsilon_tonos+greek_nu+greek_alpha+"\\.";
		texte["msgContractsale"]="Ein Vertrag wurde angenommen";
		texte["msgContractsaleContent"]="(.*) "+greek_upsilon+greek_pi+greek_epsilon_tonos+greek_gamma+greek_rho+greek_alpha+greek_psi+greek_epsilon+" "+greek_tau+greek_eta+" "+greek_sigma+greek_upsilon_tonos+greek_mu+greek_beta+greek_alpha+greek_sigma+greek_eta_tonos+" "+greek_sigma+greek_omicron+greek_upsilon+"!<br><br>\\s*"+greek_Tau+greek_alpha+" "+greek_alpha+greek_kappa+greek_omicron_tonos+greek_lambda+greek_omicron+greek_upsilon+greek_theta+greek_alpha+" "+greek_pi+greek_rho+greek_omicron+greek_iota_dialytika +greek_omicron_tonos+greek_nu+greek_tau+greek_alpha+" "+greek_pi+greek_omicron+greek_upsilon+greek_lambda+greek_eta_tonos+greek_theta+greek_eta+greek_kappa+greek_alpha+greek_nu+":<br>([\\S\\s]*)\\s*<br>\\s*"+greek_Tau+greek_omicron+" "+greek_pi+greek_omicron+greek_sigma+greek_omicron_tonos+" "+greek_tau+greek_omega+greek_nu+" (.*?) pD "+greek_Pi+greek_iota+greek_sigma+greek_tau+greek_omega_tonos+greek_theta+greek_eta+greek_kappa+greek_epsilon+" "+greek_sigma+greek_tau+greek_omicron+" "+greek_lambda+greek_omicron+greek_gamma+greek_alpha+greek_rho+greek_iota+greek_alpha+greek_sigma+greek_mu+greek_omicron_tonos+" "+greek_sigma+greek_omicron+greek_upsilon+"\\.";
		texte["msgContractsaleList"]="\\s*(\\d+)x (.*?)<br>";
		texte["msgFriend"]="(.+) "+greek_theta+greek_epsilon_tonos+greek_lambda+greek_epsilon+greek_iota+" "+greek_nu+greek_alpha+" "+greek_sigma+greek_epsilon+" "+greek_pi+greek_rho+greek_omicron+greek_sigma+greek_theta+greek_epsilon_tonos+greek_sigma+greek_epsilon+greek_iota+" "+greek_sigma+greek_alpha+" "+greek_phi+greek_iota_tonos+greek_lambda+greek_omicron;
		texte["msgMarketplace"]="(\\d+)\\s+(\\D+)\\s+"+greek_gamma+greek_iota+greek_alpha+"\\s+(\\d+)";
	}
	else if (location.hostname.match(GAMEP