Travian AutoTask [TW]

By 魎皇鬼 Uploaded Jul 16, 2009

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

// ==UserScript==
// @name 	Travian AutoTask
// @author 	congxz6688
// @version 	1.0.3.7
// @description This is my first script, it is unfinished. I shall update it step by step.^_^ simplified Chinese support only.
// @include 	http://*.travian*
// @exclude 	http://*.travian*.*/hilfe.php*
// @exclude	http://*.travian*.*/log*.php*
// @exclude 	http://*.travian*.*/index.php*
// @exclude 	http://*.travian*.*/anleitung.php*
// @exclude 	http://*.travian*.*/impressum.php*
// @exclude 	http://*.travian*.*/anmelden.php*
// @exclude 	http://*.travian*.*/gutscheine.php*
// @exclude 	http://*.travian*.*/spielregeln.php*
// @exclude 	http://*.travian*.*/links.php*
// @exclude 	http://*.travian*.*/geschichte.php*
// @exclude 	http://*.travian*.*/tutorial.php*
// @exclude 	http://*.travian*.*/manual.php*
// @exclude 	http://*.travian*.*/ajax.php*
// @exclude 	http://*.travian*.*/ad/*
// @exclude 	http://*.travian*.*/chat/*
// @exclude 	http://forum.travian*.*
// @exclude 	http://board.travian*.*
// @exclude 	http://shop.travian*.*
// @exclude 	http://*.travian*.*/activate.php*
// @exclude 	http://*.travian*.*/support.php*
// @exclude  	http://help.travian*.*/*log
// @exclude 	*.css
// @exclude 	*.js
// ==/UserScript==


var cssStyle = "";
cssStyle += "table#tasklisttable th {border:0px !important;font-weight:bolder; margin:10px;padding-top:8px; }"
cssStyle += "table#tasklisttable tr td {border:0px !important;margin:20px;}";
cssStyle += ".floatClose {float:right; padding:2px 4px; color:white; margin:-5px -15px 0 0;}";
cssStyle += "#closeautran {position:relative;top:1px;left:150px}"
cssStyle += "#autoResdiv,#translimit {padding:0px 3px; }";
cssStyle += "#autotransbtn {margin: 0px 0px 0px  20px; position:relative;top:-5px}";
cssStyle += "#updataform, #printmsg,#transform,#translimitform,#demolistform {padding:10px 30px; }";
cssStyle += "#translimit {padding:0px 3px 15px 3px;}";
cssStyle += "#demolishdiv {padding:10px 3px 3px 3px;}";
cssStyle += "#taskForm_wrapper,#MSG_wrapper,#tranForm_wrapper,#tranlmtform_wrapper,#demolistform_wrapper {position:fixed; max-width:900px !important; min-width:260px !important; min-height:50px !important; background-color:RGB(255, 255, 192); margin:0; color:black; border:1px #000000 solid; z-index:100; -moz-border-radius:5px;}";
cssStyle += "#tasklisttable_wrapper {position:fixed; padding:10px 20px 10px 20px; max-width:auto !important; min-width:260px !important; min-height:50px !important; background-color:RGB(200, 240, 200); margin:0; color:black; border:1px #000000 solid; z-index:100; -moz-border-radius:5px;}";
cssStyle += "#taskForm_wrapper p {}";
cssStyle += ".handle {cursor: move;}";
cssStyle +="#autoResform1,#changeit {color:green;}";
cssStyle +="#autoResform2,#demolishlnk {color:red;}";
GM_addStyle(cssStyle);

var deleteBtn = "data:image/gif;base64,R0lGODlhDAAMANU2AN4ZCtAgFNAgHdsgA9waCs4cDMwkHPNfHcspJ9oYCsoYDc8pINAYCvg0AORNOeFFPtA7O+c+QNRTU8BMSb4gHN5lTNooGsc1N+g+PuEkJOhOKLlVWOwxD9MlGtUiFMwjFcI7LtcfDPY9ANs5L+JMSOxhJLRDO+YfDdYEAPdvHORZRMkZC9EcDcwXE8ssLtonG9gbG+M8EOEZGdkZDNwVCb0pKwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAADYALAAAAAAMAAwAQAZJQNNgYisajzZVDHRMBJC2TEvxOY40HNfRsEJGYBKS51gS1aA2gCXVQEApDONDBikuCmgMioV2vC5FMx1GFQchG0g0BDYnAmhFQQA7";
var movedownBtn = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAARCAIAAABbzbuTAAAABmJLR0QAAAAAAAD5Q7t%2FAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACXklEQVR42p2S20vTYRjH%2FTuCiEBLWwepoC4kLSWdxZrImBeri7IjokS6eaFikGCZHaxBB5DWPNVwREKm2GSz1FKHXghFsYFaJnP%2B3Obv9B6ep3ezgsKbenkv3ovv5%2F0%2Bz%2Fd50vAfT9p%2FARwRgHPKASmg%2FdZQY%2FuHGmfAfn%2F4Skt%2Fb2BBp2tCw1BFDn8AjAPh6BqRL7S%2BPX97vKJt%2FM7Lrx7%2FHGHyxgBloFG8ObBqaRq1NgfLmt%2FXdnx55gtTrmwAADBhIQBHz%2FzxhjFjfbC4fuzio9keX3hjh9%2BAEBXWvjtin8y3%2B22tY52Dn%2F920IQWOCMqIbJCFdvd2QOXBnMqRw9d9p%2B4Nu4eCQMhqCmUIVCeclAlVYcE4CrHmI6lTVM7T3r3nHq193RfQc2bdv%2FiMkcJMMqRMzkJgK5OhyN55W2mmtcWe8BcN2mwegyW3l1lvXkVQ6bq4eLq%2FlJH91Wnh2KqJAYYB%2BybiRQ7BjaXeDPNXZnm7vW7zdSZWeI5XBU41%2FBCJZigqcEBEd1IVI8%2F9s4UVPnSC93pRU%2B2H3NlGF0ZRe59Zzz5lc9VikiiMvBfKXEmnNYAG53e%2FWf9Weanu00Pth51Zlm92UV1UV1kmBDpiFrSfqaKYsq6iEsGtFa6cmxdm3Ifbim4l21uiWrJmpFzBE7Xd4kgUmEBmhiDpqnilVt6Y4fJbTBe%2F7SoMK4AASESRVDUUz0kd46rlMTi0tL8XOjjdGAilH6w3NkxPBGcCoVmI0uRRFxlVCApACkBjgSAUE5kRqm2EpOicenb9%2FnlpYWVhKKQpIKLjxn8ABAenc7LXVdbAAAAAElFTkSuQmCC";
var moveupBtn = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAIAAADdWck9AAAABmJLR0QAAAAAAAD5Q7t%2FAAAACXBIWXMAAA7EAAAOxAGVKw4bAAACbElEQVR42pVT70tTURj2f4joexGrT0XfggqGrabUIrLol4FiOiiwMCxZzQyMROzDqMD8gShCiLQNdQi2cc1tZrrmls1i1lzLLFzzunbv7r3nx9u5Zw360Jdd7j3ncN7nOe97n%2Bc9ZVDiU1Y6gRI2Uf6yL5fbyGHoHhbSEs3kRAoEA%2BBitJhBh1OdSQhDj05F4yJ09npEzDeBFKC0kIFT2UGIYoIw9UbWfXGp6dns2JJ8xzGGCA9ixCb8D4Ew9KYC75KZ0ZDY4JirfrxgfRpxL%2BOO%2FilRBU3T8%2BDiP7A1wQQ%2BpdV7g4GLDwTL%2FZljbcGqzojFLjhjuNcVUhA%2FFAjPkJcVTVtH5OYT4VJ7qKI1YLLNmO2zZnuQrc0t4%2B3OzPD0SlZDNC%2FqhDyGtErqWp22odSNgbX6nsRxW8B463X57elznYt1PcvW59GWvmA4kVZ4TWUYlNjKdyGUmpj%2F6gonr%2FWnDjf6jE3BQ43eK45YlzsxFln1vF32BZdQUdYMgEQJxpTKCFm7Px%2BoGd9fPbmv2n2%2BYyGwKCuACdW4FyonEF1WShVCqapAreODoWpk75nxPWdHTrf5%2FXMIQZ5QmYmKQCmq9FcpYLuX26OGkwMGy9DuE%2F2nmv3CQjYPTJ%2BcPmD4D%2BHC3cjOo327TINsrLg%2B7XvzQ2UhKgF3nMvK7GcaU8yagBEqmye3Gx%2FtMHZtO%2FLw4NUXr%2FxfkE6QQYdRTtDNp5qm%2FM7KP9e3ymtcphpPZb3XVOupbPC8nJgVJVHTcgyGeHPoJbFqVDW%2FtSX92pDDH1fno8m5SDIUS72Pf1vbUDezaVWR9O4pOF3qffgDH4Xh0bQHBfwAAAAASUVORK5CYII%3D";
var sCloseBtn = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAIAAAAmdTLBAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1gYKECMhBqiEGQAAADJ0RVh0Q29tbWVudABFcnN0ZWxsdCB2b24gRmxvcmlhbiBTY2hyZWllciBtaXQgVGhlIEdJTVCOHcWrAAADLUlEQVR42pWUPYhdRRiG32/OuTdZXTcas0n2ZiVVYBttLFLFQuNPZTQgiIIphGBAtNTC0lZBRRQVEYWoBAyk8ActRFCRLa3SpNH9icm699695+6Z+X5ei7Obtc1UH+/MM+/M9w4jJD0wnNi9czVuZ3iwSlKbQ5ohP3rzn+FGTBvmlqbUgpRgBQDdAbC0AOAepbV2ezI3v/Txd+nuQ0Jy4+3XqsMDqeqYjHxryJJRCiPgRneAMKU7rbBktlNrtoaj0WrvrpMXlxMAH29Kf5/0+6hqqXtS16h7SImpkqqSVCHVkipIQqq6NanuTdZXDs7VNQA2WzEZS12znTJvM2eWQi1UpSnDqQUgtcCVpnRHSqmqACQA1BKToY83oxnPPvz0/BvvR9OwaaKZeDOO8TC2NmP077FPfjzw/CvM23STlKTu3eKV04bbE+a8/8FTAI6+dTG00Aq00DK1LF78HcDs6bNwAwPcSaHjc5TCXKh6/fVz3cTggytwQzjc7vt6uRP/OrOEcGEAAXKHB8DcRm5pCvf1V5/pxGOf/kT64pd/7MBPnoArXEEXUrDLRztFyVCFOSMoXH35TMcsfvFrV6ycXUqJIiFwoUmYROz6mzK30LJ7Nwq5+tITt57a6rP3S6IIk0TqeBrC9/oXVhjOcGGIAAmDD7+/xQ+++jMl7PmHwlXC9vrHkqkFYWSQXHjvSkeun3+oK458tizdFjAJEytpz98KNdMK3Ri+8M43O/CFRwBef/EkALlj7sila4IQBlzFC013+bLjT9WFdy938NqFx0CCBHjj3AOdePjyqoSmDv7f+Qtzy9JS8/SXbwGsnT8NN3b5hzP8xnMnALQ/fI5wmkELzQAIyWun5qsD98jMbNq3X6oaAjAEAYRQJYpYFi+wgtKyFMtlPPWrW3zqatQAVEu020kqiZCqliQIh6CLOoXCi1iBFahRzdTVQh0A6pujaA4OuHkDyqqfUdWAgCFCYQi9gsNVwukqZjQ35UghC8cByDSTG3///MKjo7WVfq+mSEhCRJVEAKFXdAlPDPdAeMUozjh6/PFLv/UPDYRkVuzr3dbfh5sjv3OmmunjP4EhhHJu9NM9AAAAAElFTkSuQmCC";
allbuildwithid = ["伐木場", "泥坑", "鐵礦場", "農場", "", "鋸木廠", "磚廠", "鋼鐵鑄造廠", "麵粉廠", "麵包店房", "倉庫", "穀倉", "鐵匠", "盔甲廠", "競技場", "村莊大樓", "集結點", "市場", "大使館", "兵營", "馬廄", "工場", "研究院", "山洞", "城鎮聽", "行宮", "皇宮", "寶物庫", "交易所", "大兵營", "大馬廄", "城牆", "土牆", "木牆", "石匠舖", "釀酒廠", "陷阱機", "英雄館", "大倉庫", "大穀倉", "世界奇觀", "放牧水槽"];
addTaskText = ["添加任務", "任務類型", "所在村", "任務對象", "目標","模式","支援建設","資源集中","上移","下移","刪除","任務内容","移動","清除所有任務"]
TaskKind = ["升级", "新建", "攻擊", "研發", "訓練", "運輸", "平倉", "拆除", "活動"]
maxlevel = ["10", "10", "10", "10", "0", "5", "5", "5", "5", "5", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "10", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "20", "10", "20", "20", "20", "20", "100", "20"];
gametext = ["等級", "商人", "坑號", "主村", "執行時間", "如使用默認,則自動安排執行時間", "到","村莊","運送","回來","向","來自於","從","資源","建築","建造新的建築","空","級"]
raceName = ["羅馬人", "條頓人", "高盧人"]
taskoftext = ["預定升级", "預定新建","資源自動升级","尚未開啟","馬上開啟","已經開啟","點擊關閉","該村資源田分布","自動運輸","自動運輸尚未设定","已设定","運送成功","任務列表","運輸限額","默認","更改","木/磚/鐵","穀物","預定拆除"]
errorText = ["資源不足", "已經有建築在建造中", "建造完成", "將馬上開始全部建造", "在開發中", "建造所需資源超過倉庫容量上限,請先升級你的倉庫","建造所需資源超過穀倉容量上限,請先升級你的穀倉"]
otherText = ["重要提示", "只有主村的資源田可以升級到20,<br>目前主村尚未識別,點擊個人資料<br>頁面可以解决這一問題", "五星級傳送門^_^","已經設置完成","已經取消","開始執行任務","升级成功","已順利執行"]
allsourceString="伐木場泥坑鐵礦場農場" //此為羅馬的資源生及檢查,如果是其它種族,則要同時包含所有建築。
allbuildString="鋸木廠磚廠鋼鐵鑄造廠麵粉廠麵包店倉庫穀倉鐵匠盔甲廠競技場村莊大樓集結點市場大使館兵營馬廄工廠研究所山洞城鎮廳行宮皇宮寶物庫交易所大兵營大馬廄城牆土牆木牆石匠舖釀酒廠陷阱機英雄館大倉庫大穀倉世界奇觀放牧水槽"

allString=allsourceString+allbuildString
	var mts = new Array();
	mts[0]	= 16;
	mts[1]	= 12;
	mts[2]	= 24;


var inputs = document.evaluate('//form/descendant::input[@type="password"]', document, null, 7, null);
if (inputs.snapshotLength == 1 && 0 < inputs.snapshotItem(0).value.length) {
	inputs.snapshotItem(0).form.submit();
}


	getSingleVillageNum()
	if (!GM_getValue(currentServer() + "_" + getuid() + "_option")) {
		GM_setValue(currentServer() + "_" + getuid() + "_option", "");
	}
	getTaskCookies()
	
	var mybar = document.createElement("div");
	mybar.style.width = "100%"
	mybar.style.backgroundColor = "silver"
	mybar.style.position = "fixed"
	mybar.style.bottom = "0"
	mybar.style.textAlign = "center"
	document.body.insertBefore(mybar, document.body.lastChild.nextSibling);
	
	
	function $(id){
		return document.getElementById(id);
	}
	
	
	function currentID(){
		var theboys = document.evaluate("//table[@id='vlist']/descendant::td[@class='dot hl']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		theUrl=theboys.singleNodeValue.nextSibling.innerHTML.match(/newdid=\d{1,}/)
		getit=theUrl.toString().match(/\d{1,}/)
		return getit
	}
	
	
	function currentVillageName(){
		var theVillageName = document.evaluate("//table[@id='vlist']/descendant::a[contains(@href,"+ currentID()+")]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return theVillageName.singleNodeValue.innerHTML
	}
	
	
	function getAllVillageNewdids(){
		var allNewdids = new Array();
		var allvillages = document.evaluate('id("vlist")/descendant::a[@href]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		if (allvillages.snapshotLength > 0) {//multi-villages
			for (var i = 0; i < allvillages.snapshotLength; i++) {
				if (allvillages.snapshotItem(i).href.indexOf("newdid") != -1) {
					newdiddd = allvillages.snapshotItem(i).href.match(/\d{3,}(?!\.)/);
					thenewlength = allNewdids.push(newdiddd);//+ ":" + thevillagenum
				}
			}
		}
		else {//single village
			allNewdids[0] = (GM_getValue(currentServer() + '_' + getuid() + '_singleTownNEWDID')) ? GM_getValue(currentServer() + '_' + getuid() + '_singleTownNEWDID') : ""
		}
		return allNewdids
	}
	
	
	
	function getSingleVillageNum(){
		if (!GM_getValue(currentServer() + "_" + getuid() + '_singleTownNEWDID')) {
			GM_xmlhttpRequest({
				method: 'GET',
				url: "http://s7.travian.cn/dorf3.php",
				onload: function(result){
					var theString = result.responseText.match(/newdid=\d{1,}/)
					var villageNum = theString.toString().match(/\d{1,}/);
					GM_setValue(currentServer() + "_" + getuid() + '_singleTownNEWDID', villageNum.toString())
				}
			});
		}
	}
	
	
	
	function getErrorInfor(){
		var errors = document.evaluate('//*[@class="none"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		if (errors) {
			return errors.singleNodeValue.innerHTML
		}
	}
	
	
	
	function getuid(){
		var privatee = document.evaluate('id("sleft")/descendant::a[contains(@href,"spieler")]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return privatee.singleNodeValue.href.split("uid=")[1]
	}
	
	
	
	function getthebuildUrl(vil, task){
		var myower = window.clearInterval(myower);	
		GM_log("come into getthebuildUrl(), task= "+task)
		var url = "http://" + window.location.hostname + "/build.php?newdid=" + vil + "&id=" + task[1];
		var getbuildurl = new XMLHttpRequest();
		getbuildurl.open('GET', url, false);
		getbuildurl.onreadystatechange = callback;
		getbuildurl.send(null);
		function callback(){
			if (getbuildurl.readyState == 4) {
				if (getbuildurl.status == 200) {
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getbuildurl.responseText;
					aDoc.appendChild(aElem);
					
					switch (task[0]) {//0_id_level_time_name
						case "0":
							var level = aDoc.getElementsByTagName("h1")[0].innerHTML.split(" ")[2];
							GM_setValue(currentServer() + "_" + getuid() + "_" + vil + "_crtBuildlevel", level)
							var allanchors = aDoc.evaluate('id("content")//a[contains(@href,"?a=")]', aElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							if (allanchors.singleNodeValue) {
								GM_log("i get the url ,it is " + allanchors.singleNodeValue.href)
								return allanchors.singleNodeValue.href
							}
							else {
							    GM_log("oh No! I can't get the url")
								return false
							}
							break;
						case "1"://1_id_level_gid_time_name
							var newbdurl = aDoc.evaluate('id("content")//a[contains(@href,"?a='+task[3]+'")]', aElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
							if (newbdurl.singleNodeValue) {
								GM_log("i get the newbuild url ,it is " + newbdurl.singleNodeValue.href)
								return newbdurl.singleNodeValue.href
							}
							else {
								GM_log("oh, it is so bad, can't get the build url")
								return false
							}
							break;
					}
				}
			}
		}
		return callback()
	}
	
	
	function getcrtlevel(){
		var theTitle = document.getElementsByTagName("h1")[0]
		if (theTitle.innerHTML.split(" ")[2]) {
			return theTitle.innerHTML.split(" ")[2]
		}
	}
	
	
	
	function currentServer(){
		var serverr = window.location.hostname.replace(/\.travian\./, "")
		return serverr
	}
	
	
	
	function getMainVillageid(){
		if (window.location.href.split("?uid=")[1] == getuid()) {
			if (window.location.href.indexOf("spieler.php") != -1) {
				var mainvi = document.evaluate('//table[@id="villages"]/descendant::span[@class="none3"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
				themainv = mainvi.singleNodeValue.parentNode.firstChild.innerHTML
				mainpos=mainvi.singleNodeValue.parentNode.firstChild.href.match(/\d{2,}(?=&)/)
				GM_setValue(currentServer() + "_" + getuid() + "_mainvillageName", themainv);
				GM_setValue(currentServer() + "_" + getuid() + "_mainvillageId", getDidFromVillage(themainv));
				for (oo in raceName) {
					therace = new RegExp(raceName[oo])
					if (document.getElementsByTagName("body")[0].innerHTML.match(therace)) {
						GM_setValue(currentServer() + "_" + getuid() + "_raceID", oo.toString());
						break;
					}
				}
			}
		}
	}
	
	function getResourceCap(){
		resource = [document.getElementById("l4").innerHTML.split("/")[0], document.getElementById("l3").innerHTML.split("/")[0], document.getElementById("l2").innerHTML.split("/")[0], document.getElementById("l1").innerHTML.split("/")[0]]
		resstring = resource.join("/")
		WarehouseCap = document.getElementById("l4").innerHTML.split("/")[1];
		GranaryCap = document.getElementById("l1").innerHTML.split("/")[1];
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_WarehouseCap", WarehouseCap);
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_GranaryCap", GranaryCap);
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_ResourceNow", resstring);
	}
	
	
	
	function HttpRequire(url, v, ta, k, l){
		GM_log("come into HttpRequire(), to build "+ta[ta.length-1])
		var myower = window.clearInterval(myower)
		if (url) {
			GM_xmlhttpRequest({
				method: 'GET',
				url: url,
				headers: "",
				onload: function(){
					switch (k) {
						case "0"://resource updata
							GM_deleteValue(currentServer() + "_" + getuid() + "_" + v + "_ResourceUpdataTime")
							GM_setValue(currentServer() + "_" + getuid() + "_" + v + "_autoResourceDone", ta[1])
							if (l == ta[2]) {
								deleteTaskFromCookie(v, ta)
							}
							break;
						case "1"://build task
							GM_deleteValue(currentServer() + "_" + getuid() + "_" + v + "_BuildingUpdataTime")

							switch (ta[0]) {
								case "0"://build updata
									if (l == ta[2]) {
										deleteTaskFromCookie(v, ta)
									}
									break;
								case "1"://new build
									if (l == ta[2]) {
										deleteTaskFromCookie(v, ta)
									}
									else {//new build 1_id_level_gid_time_name  to  Updata 0_id_level_time_name
										var changeToUP=new Array();
										changeToUP[0]="0"
										changeToUP[1]=ta[1]
										changeToUP[2]=ta[2]
										changeToUP[3]=ta[4]
										changeToUP[4]=ta[5]
										deleteTaskFromCookie(v, ta,changeToUP)
									}
									break;
							}
						
							break;
						case "2":
							GM_deleteValue(currentServer() + "_" + getuid() + "_" + v + "_UpdataTime")
							GM_setValue(currentServer() + "_" + getuid() + "_" + v + "_autoResourceDone", ta[1])

							switch (ta[0]) {
								case "0":
									if (l == ta[2]) {
										deleteTaskFromCookie(v, ta)
									}
									break;
								case "1":
									if (l == ta[2]) {
										deleteTaskFromCookie(v, ta)
									}
									else {//new build 1_id_level_gid_time_name  to  Updata 0_id_level_time_name
										var changeToUP=new Array();
										changeToUP[0]="0"
										changeToUP[1]=ta[1]
										changeToUP[2]=ta[2]
										changeToUP[3]=ta[4]
										changeToUP[4]=ta[5]
										deleteTaskFromCookie(v, ta,changeToUP)
									}
									break;
							}
							break;
					}
					printMSG(gametext[7] + getvillagefromdid(v) + otherText[6]);
					window.location.replace("dorf1.php")
					GM_log("built ok!!!!lalalalala!!!!!!!!!!!!!!!!!!!")
				},
			})
		}
		else {
			var nextt=new Date();
			tt=nextt.getTime()+1800000;
			nextt.setTime(tt)
			switch (k){
				case "0":
					GM_setValue(currentServer() + "_" + getuid() + "_" + v + "_ResourceUpdataTime",nextt)
					break;
				case "1":
					GM_setValue(currentServer() + "_" + getuid() + "_" + v + "_BuildingUpdataTime",nextt)
					break;
				case "2":
					GM_setValue(currentServer() + "_" + getuid() + "_" + v + "_UpdataTime",nextt)
					break;
			}
		}
	}
	
	
	
	function setTaskCookies(){
		taskkindss = $("taskkindss").value;
		crtvillagee = $("crtvillagee").value;
		buildnamee = $("buildNamee").value;
		bidid = $("bidid").value;
		levelselect = $("levelselect").value;
		taskTimee = $("userSetTime").value;
		todday = new Date(taskTimee)
		userSetTime = todday.getTime()
		
		switch (taskkindss) {
			case "0":
				thisTask = taskkindss + "_" + bidid + "_" + levelselect + "_" + userSetTime+"_"+buildnamee
				
				break;
			case "1":
				thisTask = taskkindss + "_" + bidid + "_" + levelselect + "_" + getGidFromName(buildnamee) + "_" + userSetTime+"_"+buildnamee
				break;
		}
		allTask = (GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask")) ? GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask") + "|" + thisTask : thisTask
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", allTask)
		document.body.removeChild(document.getElementById("taskForm_wrapper"));
		if ($("tasklisttable_wrapper")) {
			document.body.removeChild($("tasklisttable_wrapper"))
		}
		showTaskList()
		getTaskCookies()
	}
	
	
	
	/****************************************************************************/
	var mouseOffset = null;
	var iMouseDown = false;
	var lMouseState = false;
	var dragObject = null;
	var curTarget = null;
	
	
	function setOption(key, value){
		var options = GM_getValue(currentServer() + "_" + getuid() + "_option");
		if (options & options != '' & options != null) {
			options = options.split(",");
		}
		else {
			GM_setValue(currentServer() + "_" + getuid() + "_option", "")
			options = [];
		}
		var myOption = options.indexOf(key);
		if (myOption < 0) {
			options.push(key);
			options.push(value);
		}
		else {
			options[myOption + 1] = value;
		}
		options = options.join(",");
		GM_setValue(currentServer() + "_" + getuid() + "_option", options);
	}
	
	function getOption(key, defaultValue, type){
		var options = GM_getValue(currentServer() + "_" + getuid() + "_option");
		options = options.split(",");
		var myOption = options.indexOf(key);
		if (myOption < 0) {
			return defaultValue;
		}
		switch (type) {
			case "boolean":
				var myOption = (options[myOption + 1] == "true") ? true : false;
				break;
			case "integer":
				var myOption = parseInt(options[myOption + 1]);
				break;
			case "string":
			default:
				var myOption = options[myOption + 1];
				break;
		}
		return myOption;
	}
	
	function mouseCoords(ev){
		return {
			x: ev.pageX,
			y: ev.pageY
		};
	}
	
	function makeClickable(object){
		object.onmousedown = function(){
			dragObject = this;
		}
	}
	
	function getMouseOffset(target, ev){
		var docPos = getPosition(target);
		var mousePos = mouseCoords(ev);
		return {
			x: mousePos.x - docPos.x,
			y: mousePos.y - docPos.y
		};
	}
	
	function getPosition(e){
		var left = 0;
		var top = 0;
		while (e.offsetParent) {
			left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
			top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
			e = e.offsetParent;
		}
		left += e.offsetLeft + (e.currentStyle ? (parseInt(e.currentStyle.borderLeftWidth)).NaN0() : 0);
		top += e.offsetTop + (e.currentStyle ? (parseInt(e.currentStyle.borderTopWidth)).NaN0() : 0);
		return {
			x: left,
			y: top
		};
	}
	
	function mouseMove(ev){
		var target = ev.target;
		var mousePos = mouseCoords(ev);
		
		if (dragObject) {
			dragObject.style.position = 'fixed';
			dragObject.style.top = (mousePos.y - mouseOffset.y) + "px";
			dragObject.style.left = (mousePos.x - mouseOffset.x) + "px";
		}
		lMouseState = iMouseDown;
		return false;
	}
	
	function mouseUp(ev){//
		if (dragObject) {
			switch (dragObject.id) {
				case "demolistform_wrapper":
					var key = "DEMOLISH_POSITION";
					break;
				case "tranlmtform_wrapper":
					var key = "TRANLMT_POSITION";
					break;
				case "tasklisttable_wrapper":
					var key = "TASKLIST_POSITION";
					break;				
				case "taskForm_wrapper":
					var key = "FORM_POSITION";
					break;
				case "tranForm_wrapper":
					var key = "TRAN_POSITION";
					break;
				case "MSG_wrapper":
					var key = "MSG_POSITION";
					break;
				default:
					var key = "LIST_POSITION";
					break;
			}
			setOption(key, dragObject.style.top + "_" + dragObject.style.left);
		}
		dragObject = null;
		iMouseDown = false;
	}
	
	function mouseDown(ev){
		var mousePos = mouseCoords(ev);
		var target = ev.target;
		iMouseDown = true;
		if (target.getAttribute('DragObj')) {
			return false;
		}
	}
	
	
	function makeDraggable(item){
		if (!item) 
			return;
		item.addEventListener("mousedown", function(ev){
			dragObject = this.parentNode;
			mouseOffset = getMouseOffset(this.parentNode, ev);
			return false;
		}, false);
	}
	
	document.addEventListener("mousemove", mouseMove, false);
	document.addEventListener("mousedown", mouseDown, false);
	document.addEventListener("mouseup", mouseUp, false);


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

	function createDemolishlnk(){
		var nposi=$("contract");
		var errors = document.evaluate('//p[@class="none"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		nextposition=(nposi)?nposi:errors.singleNodeValue
		var demolishdiv=document.createElement("div");
		demolishdiv.id="demolishdiv"
		var demolishlnk=document.createElement("a");
		demolishlnk.id="demolishlnk";
		demolishlnk.href="#";
		demolishlnk.innerHTML=taskoftext[18]
		demolishlnk.addEventListener("click", createDemolishFloat, false);
		demolishdiv.appendChild(demolishlnk);
		nextposition.parentNode.insertBefore(demolishdiv,nextposition);
	}
	
	
	
	function createNewbuildLnk(){
		crtvillagedid = currentID();
		buildnextlevel="1";
		buildidss = window.location.href.match(/[^d]id=\d{1,2}/);
		buildidid = buildidss.toString().match(/\d{1,2}/);		
		var allnewbuilds = document.evaluate('//div[@id="build"]/table[@class="new_building"]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		for (var i = 0; i < allnewbuilds.snapshotLength; i++) {
			buildName=allnewbuilds.snapshotItem(i).previousSibling.previousSibling.innerHTML;
			buildName=(buildName.indexOf(allbuildwithid[10])!=-1)?allbuildwithid[10]:((buildName.indexOf(allbuildwithid[11])!=-1)?allbuildwithid[11]:buildName)
			buildgid=getGidFromName(buildName);
			buildmaxlevel = maxlevel[buildgid]
			theposition = allnewbuilds.snapshotItem(i).lastChild
			
			var createUrl = document.createElement("a");
			createUrl.href = "#";
			createUrl.innerHTML = "&#160;&#160;&#160;" + taskoftext[1];
			createUrl.setAttribute("crtvillage", crtvillagedid);
			createUrl.setAttribute("buildName", buildName);
			createUrl.setAttribute("buildnextlevel", buildnextlevel);
			createUrl.setAttribute("buildmaxlevel", buildmaxlevel);
			createUrl.setAttribute("buildgid", buildgid);
			createUrl.setAttribute("buildidid", buildidid);
			createUrl.addEventListener("click", createUpdateFloat, false)
			theposition.appendChild(createUrl)	
		}
	}

	
	function createbuildlink(){
		crtvillagedid = currentID();
		mainv1 = GM_getValue(currentServer() + "_" + getuid() + "_mainvillageId");
		h1inner = document.getElementsByTagName("h1")[0].innerHTML;
		h1inner = h1inner.split(" ");
		buildName = h1inner[0];
		crtlevel = parseInt(h1inner[2]);
		for (yyy in allbuildwithid) {
			if (buildName == allbuildwithid[yyy]) {
				buildmaxlevel = maxlevel[yyy];
				if (crtvillagedid == mainv1 & parseInt(yyy) < 4) {
					buildmaxlevel *= 2 //mainvillage resource level 20
				}
			}
		}
		if (crtlevel < buildmaxlevel) {
			buildnextlevel = crtlevel + 1;
			if (window.location.href.indexOf("&gid=17") != -1) {
				var rere = document.evaluate('id("textmenu")/descendant::a[@href]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
				buildidid = rere.singleNodeValue.href.split("id=")[1]
			}
			else {
				buildidss = window.location.href.match(/[^dg]id=\d{1,2}/);
				buildidid = buildidss.toString().match(/\d{1,2}/);
			}
			
			var myget = document.evaluate('//div/descendant::a[contains(@href,"a=' + buildidid + '")]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			var errors = document.evaluate('//p/span[@class="none"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			var othererror=document.evaluate('//span[@class="c"]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			
			theposition = (myget.singleNodeValue) ? myget.singleNodeValue : (errors.singleNodeValue?errors.singleNodeValue:othererror.singleNodeValue)
			
			var createUrl = document.createElement("a");
			createUrl.id = "createUrl";
			createUrl.name = "createUrl";
			createUrl.href = "#";
			createUrl.innerHTML = "&#160;&#160;&#160;" + taskoftext[0];
			createUrl.setAttribute("crtvillage", crtvillagedid);
			createUrl.setAttribute("buildName", buildName);
			createUrl.setAttribute("buildnextlevel", buildnextlevel);
			createUrl.setAttribute("buildmaxlevel", buildmaxlevel);
			createUrl.setAttribute("buildidid", buildidid);
			createUrl.addEventListener("click", createUpdateFloat, false)
			theposition.parentNode.appendChild(createUrl)
			
		}
	}
	
	function createDemolishFloat(){
		var options=document.evaluate('//select[@name="abriss"]/descendant::option', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		GM_log(options.snapshotItem(0).innerHTML)
		myoptions=""
		for (var i=0; i<options.snapshotLength; i++) {
			if(options.snapshotItem(i).innerHTML.indexOf(gametext[16])!=-1){continue;}
			myoptions+="<option value='"+options.snapshotItem(i).innerHTML+"'>"+options.snapshotItem(i).innerHTML+"</option>"
		}
		var DemoListForm=document.createElement("form");
		DemoListForm.id="demolistform";
		var floatClose = "<a href='#' onclick='document.body.removeChild($(\"demolistform_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>";
		DemoListForm.innerHTML = floatClose;
		DemoListForm.innerHTML += "<br />" + taskoftext[18].big() +"<br /><br />";
		DemoListForm.innerHTML+=  gametext[7] + ":  <select id='crtvillagee'><option value='" + currentID() + "'>" + currentVillageName() + "</option></select><br /><br />";		
		DemoListForm.innerHTML+=taskoftext[18]+": <select id='selecteddemo'>"+myoptions+"</select><br /><br />"

		var tSubmitBtn = document.createElement("input");
		tSubmitBtn.value = "OK";
		tSubmitBtn.type = "button";
		tSubmitBtn.addEventListener('click', setDemoCookies, true);
		DemoListForm.appendChild(tSubmitBtn);
		
		var doWrapper = document.createElement("div");
		doWrapper.id = "demolistform_wrapper";
		doWrapper.appendChild(DemoListForm);
		
		var formCoords = getOption("DEMOLISH_POSITION", "218px_468px");
		formCoords = formCoords.split("_");
		doWrapper.style.top = formCoords[0];
		doWrapper.style.left = formCoords[1];
		
		document.body.appendChild(doWrapper);
		makeDraggable($("demolistform"));		
	}
	
	function setDemoCookies(){
		selecteddemo = $("selecteddemo").value;
		theID=selecteddemo.split(". ")[0]
		theBuild=selecteddemo.split(". ")[1].split(" ")[0]
		crtlevel=selecteddemo.split(". ")[1].split(" ")[1]
		
		thisTask = "7_" + theID +"_" + crtlevel + "_" + currentID() + "_" +theBuild
		allTask = (GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask")) ? GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask") + "|" + thisTask : thisTask
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", allTask)
		document.body.removeChild($("demolistform_wrapper"));
		if ($("tasklisttable_wrapper")) {
			document.body.removeChild($("tasklisttable_wrapper"))
		}
		showTaskList()
		getTaskCookies()
	}
	
	function getGidFromName(name){
		for (i in allbuildwithid) {
			if (allbuildwithid[i]==name) {
				return i
			}
		}		
	}
	
	
	function createAutoResLink(){
		var producee = document.getElementById("production");
		var autoResDiv = document.createElement("div");
		autoResDiv.id = "autoResdiv";
		autoResDiv.innerHTML = taskoftext[2].bold() + ":&#160;&#160;";
		producee.parentNode.insertBefore(autoResDiv, producee.nextSibling);

		
		var autoResStatus = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource", "0")
		if (autoResStatus == "0") {
			autoResDiv.innerHTML += taskoftext[3].fontcolor("gray") + "&#160;&#160;";
			var autoResLnk = document.createElement("a");
			autoResLnk.id = "autoResform1"
			autoResLnk.href = "#";
			autoResLnk.innerHTML = taskoftext[4];
			autoResLnk.addEventListener("click", createAutoResFloat, false)
		}
		else {
			autoResDiv.innerHTML += taskoftext[5].fontcolor("green") + "&#160;&#160;";
			var autoResLnk = document.createElement("a");
			autoResLnk.id = "autoResform2"
			autoResLnk.href = "#";
			autoResLnk.innerHTML = taskoftext[6];
			autoResLnk.addEventListener("click", closeAutoRes, false)
		}
		autoResDiv.appendChild(autoResLnk);

/***********************************transport limit here***************************************************/
		var transLimit=document.createElement("div");
		transLimit.id="translimit";
		transLimit.innerHTML=taskoftext[13].bold() + ":&#160;&#160;";
		autoResDiv.parentNode.insertBefore(transLimit, autoResDiv.nextSibling);
		
		var userTranSetup = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_userTranSetup", "false")
		transLimit.innerHTML+=(userTranSetup=="false")?taskoftext[14]:userTranSetup
		transLimit.innerHTML+="&#160;&#160;";
		
		var changeIt=document.createElement("a");
		changeIt.id="changeit";
		changeIt.href="#";
		changeIt.innerHTML=taskoftext[15]
		changeIt.addEventListener("click", createTranLimitFlt, false)
		transLimit.appendChild(changeIt);
/***********************************transport limit here***************************************************/
	} 
	
	function createTranLimitFlt(){
		var userTranSetup = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_userTranSetup", "false")
		usersetup=(userTranSetup=="false")?taskoftext[14]:userTranSetup 
		var TransLimitForm = document.createElement("form");
		TransLimitForm.id="translimitform"
		var floatClose = "<a href='#' onclick='document.body.removeChild($(\"tranlmtform_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>";
		TransLimitForm.innerHTML = floatClose;
		TransLimitForm.innerHTML += "<br />" + taskoftext[15].big() +taskoftext[13].big()+"<br /><br />";
		TransLimitForm.innerHTML += gametext[7] + ":  <select id='crtvillagee'><option value='" + currentID() + "'>" + currentVillageName() + "</option></select><br /><br />";
		TransLimitForm.innerHTML += taskoftext[13]+":  <select id='crtlimit'><option value='" + usersetup + "'>" + usersetup + "</option></select><br /><br />";
		TransLimitForm.innerHTML += taskoftext[15]+gametext[6]+":  <select id='reslimitto'>"+resLimitOption() + "</select>";
		TransLimitForm.innerHTML += "  "+taskoftext[17]+"<select id='croplimitto'>"+cropLimitOption() + "</select><br /><br />";

		var tSubmitBtn = document.createElement("input");
		tSubmitBtn.value = "OK";
		tSubmitBtn.type = "button";
		tSubmitBtn.addEventListener('click', setTranLmtCookies, true);
		TransLimitForm.appendChild(tSubmitBtn);
		
		var tWrapper = document.createElement("div");
		tWrapper.id = "tranlmtform_wrapper";
		tWrapper.appendChild(TransLimitForm);
		
		var formCoords = getOption("TRANLMT_POSITION", "218px_468px");
		formCoords = formCoords.split("_");
		tWrapper.style.top = formCoords[0];
		tWrapper.style.left = formCoords[1];
		
		document.body.appendChild(tWrapper);
		makeDraggable($("translimitform"));		
	}
	
	function setTranLmtCookies(){
		var userSet = new Array()
		userSet[0] = $("reslimitto").value;
		userSet[1] = $("croplimitto").value;
		if (userSet[0] == "default" || userSet[1] == "default") {
			GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_userTranSetup")
		}
		else {
			GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_userTranSetup", userSet.join("/"))
		}
		document.body.removeChild($("tranlmtform_wrapper"));
		$("autoResdiv").parentNode.removeChild($("autoResdiv"))
		$("translimit").parentNode.removeChild($("translimit"))
		createAutoResLink()
		msg = taskoftext[13].bold() + " " + otherText[3]
		printMSG(msg)
	}
	
	function resLimitOption(){
		var WareCap = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_WarehouseCap");
		WareCap=parseInt(WareCap)
		var string="<option value='"+WareCap*0.8+"'>"+taskoftext[16]+"</option><option value='default'>"+taskoftext[14]+"</option>"
		for(i=10; i<101; i=i+10){
			cnm=(WareCap*i/100).toString()
			string += "<option value='" + cnm + "'>" + cnm + "</option>"
		}
		return string
	}
	
	
	function cropLimitOption(){
		var GranCap = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_GranaryCap");
		GranCap=parseInt(GranCap)
		var string="<option value='"+GranCap*0.8+"'>"+taskoftext[17]+"</option><option value='default'>"+taskoftext[14]+"</option>"
		for(i=10;i<101;i=i+10){
			rpy=(GranCap*i/100).toString()
			string += "<option value='" + rpy + "'>" + rpy + "</option>"
		}
		return string
	}
	

	
	function createAutoTransBtn(){
		var bposition = document.evaluate('id("btn_ok")', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		AutoTransBtn = document.createElement("a");
		AutoTransBtn.id = "autotransbtn";
		AutoTransBtn.href = "#";
		AutoTransBtn.innerHTML = taskoftext[8];
		AutoTransBtn.addEventListener("click", createAutoTransFloat, false);
		bposition.singleNodeValue.parentNode.appendChild(AutoTransBtn);
	}
	
	
	function createAutoTransFloat(){
		var TransForm = document.createElement("form");
		TransForm.id = "transform";
		var floatClose = "<a href='#' onclick='document.body.removeChild($(\"tranForm_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>";
		TransForm.innerHTML = floatClose;
		TransForm.innerHTML += "<br />" + addTaskText[0].big() + "<br /><br />";
		TransForm.innerHTML += addTaskText[1] + ":  <select id='taskkindss'><option value='5'>" + TaskKind[5] + "</option></select><br /><br />";
		TransForm.innerHTML += addTaskText[2] + ":  <select id='crtvillagee'><option value='" + currentID() + "'>" + currentVillageName() + "</option></select><br /><br />";
		TransForm.innerHTML += addTaskText[5] + ":  <select id='tranmodel'><option value='0'>" + addTaskText[6] + "</option><option value='1'>" + addTaskText[7] + "</option></select><br /><br />"
		TransForm.innerHTML += addTaskText[3] + ":  <select id='villageposition'>" + VillagePosOption() + "</select><br /><br />";
		
		var tSubmitBtn = document.createElement("input");
		tSubmitBtn.name = "submitBtn";
		tSubmitBtn.id = "submitBtn";
		tSubmitBtn.value = "OK";
		tSubmitBtn.type = "button";
		tSubmitBtn.addEventListener('click', setTranCookies, true);
		TransForm.appendChild(tSubmitBtn);
		
		var tWrapper = document.createElement("div");
		tWrapper.id = "tranForm_wrapper";
		tWrapper.appendChild(TransForm);
		
		var formCoords = getOption("TRAN_POSITION", "218px_468px");
		formCoords = formCoords.split("_");
		tWrapper.style.top = formCoords[0];
		tWrapper.style.left = formCoords[1];
		
		document.body.appendChild(tWrapper);
		makeDraggable($("transform"));
	}
	
	function setTranCookies(){
		taskkindss = "5"
		tranmodel = $("tranmodel").value
		villageposition = $("villageposition").value;
		targetVid = getVillFromPos(villageposition);
		
		thisTask = taskkindss + "_" + tranmodel + "_" + targetVid + "_" + villageposition;
		allTask = (GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask")) ? GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask") + "|" + thisTask : thisTask
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", allTask)
		allTarget = (GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo")) ? GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo") + "|" + targetVid : targetVid;
		GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo", allTarget)
		document.body.removeChild(document.getElementById("tranForm_wrapper"));
		if ($("tasklisttable_wrapper")) {
			document.body.removeChild($("tasklisttable_wrapper"))
		}
		showTaskList()
		getTaskCookies()
		msg = taskoftext[8].bold() + " " + otherText[3]
		printMSG(msg)
	}
	
	
	function VillagePosOption(){
		string = "";
		for (i = 0; i < getallVillagePos().length; i++) {
			if (getallVillagePos()[i].split(":")[0] == currentVillageName()) {
				continue;
			}
			name = getallVillagePos()[i].split(":")[0];
			position = getallVillagePos()[i].split(":")[1];
			string += "<option value='" + position + "'>" + name + "</option>"
		}
		return string
	}
	
	
	function getallVillagePos(){
		allposition = new Array();
		var allX = document.evaluate('//table[@id="vlist"]/descendant::div[@class="cox"]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		var allY = document.evaluate('//table[@id="vlist"]/descendant::div[@class="coy"]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		var allN = document.evaluate('//table[@id="vlist"]/descendant::a[contains(@href,"newdid")]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		for (var i = 0; i < allY.snapshotLength; i++) {
			xx = allX.snapshotItem(i).innerHTML.match(/\d{1,}/);
			yy = allY.snapshotItem(i).innerHTML.match(/\d{1,}/);
			na = allN.snapshotItem(i).innerHTML + ":" + getCoordfromXY(xx, yy)
			gugaga = allposition.push(na)
		}
		return allposition
	}
	
	
	function getVillFromPos(position){
		for (i = 0; i < getallVillagePos().length; i++) {
			if (getallVillagePos()[i].split(":")[1] == position) {
				return getDidFromVillage(getallVillagePos()[i].split(":")[0]);
				break;
			}
		}
	}
	
	function getPosFromVill(vi){
		for (i = 0; i < getallVillagePos().length; i++) {
			if (getallVillagePos()[i].split(":")[0] == vi) {
				return getallVillagePos()[i].split(":")[1];
				break;
			}
		}
	}
	
	
	
	function getCoordfromXY(x, y){
		x = parseInt(x);
		y = parseInt(y);
		var coordZ = (x + 401) + ((400 - y) * 801);
		return coordZ;
	}
	
	function getXfromCoord(z){
		z = parseInt(z);
		var x = ((z - 1) % 801) - 400;
		return x;
	}
	
	function getYfromCoord(z){
		z = parseInt(z);
		var y = 400 - (parseInt(((z - 1) / 801)));
		return y;
	}
	
	
	function createAutoResFloat(){
		var nowtaskstring = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", "false");
		var autoTask = "0_50_100"
		if (GM_getValue(currentServer() + "_" + getuid() + "_mainvillageId", "false") == "false") {
			msg0 = otherText[0].big() + "!!!<br /><br />" + otherText[1] + "<br /><br />";
			var privateeee = document.evaluate('id("sleft")/descendant::a[contains(@href,"spieler")]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			msg0 += otherText[2] + ":    <a href='" + privateeee.singleNodeValue.href + "'>&#160;&#160;&#160;&#160;&#160;" + privateeee.singleNodeValue.innerHTML + "</a><br /><br />";
			printMSG(msg0);
		}
		else {
			var msg1 = gametext[7].bold() + ":&#160;&#160;" + currentVillageName() + "<br /><br/ >" + taskoftext[2].bold() + ":&#160;&#160;" + otherText[3] + "<br /><br/ >" + taskoftext[7].bold() + ":<br />" + allbuildwithid[0] + " : " + allbuildwithid[1] + " : " + allbuildwithid[2] + " : " + allbuildwithid[3] + " = " + getResourceRate() + "<br />";
			if (nowtaskstring != "false" & nowtaskstring.indexOf(autoTask) != -1) {
				GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource", "1")
				if ($("tasklisttable_wrapper")) {
					document.body.removeChild($("tasklisttable_wrapper"))
				}
				showTaskList()
				$("autoResdiv").parentNode.removeChild($("autoResdiv"))
				$("translimit").parentNode.removeChild($("translimit"))
				createAutoResLink()
				printMSG(msg1);
			}
			else {
				autoResT = autoTask + "_" + getResourceRate()
				allTask = (GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask")) ? GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask") + "|" + autoResT : autoResT
				GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", allTask)
				GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource", "1")
				if ($("tasklisttable_wrapper")) {
					document.body.removeChild($("tasklisttable_wrapper"))
				}
				showTaskList()
				$("autoResdiv").parentNode.removeChild($("autoResdiv"))
				$("translimit").parentNode.removeChild($("translimit"))
				createAutoResLink()
				printMSG(msg1);
			}
		}
	}
	
	function closeAutoRes(){
		var msg = gametext[7].bold() + ":&#160;&#160;" + currentVillageName() + "<br /><br/ >" + taskoftext[2].bold() + ":&#160;&#160;" + otherText[4] + "<br />";
		villaa = currentID();
		Task = new Array();
		Task[0] = "0";
		Task[1] = "50";
		Task[2] = "100";
		Task[3] = getResourceRate();
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource");
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_CorpRemain");
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_minLevelId");
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_minLevelCropId");
		deleteTaskFromCookie(villaa, Task)
		if ($("tasklisttable_wrapper")) {
			document.body.removeChild($("tasklisttable_wrapper"))
		}
		showTaskList()
		$("autoResdiv").parentNode.removeChild($("autoResdiv"))
		$("translimit").parentNode.removeChild($("translimit"))
		createAutoResLink()
		printMSG(msg);
	}
	
	
	function getResourceRate(){
		mydiv = document.getElementById("rx");
		rate = new Array()
		for (i = 0; i < 4; i++) {
			reg = new RegExp(allbuildwithid[i], "g");
			mysearch = mydiv.innerHTML.match(reg)
			newlength = rate.push(mysearch.length);
		}
		return rate.join(":")
	}
	
	
	function printMSG(msg){
		var printmsg = document.createElement("form");
		printmsg.id = "printmsg";
		var floatClose = "<a href='#' onclick='document.body.removeChild($(\"MSG_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>";
		printmsg.innerHTML = floatClose;
		printmsg.innerHTML += "<br/ >";
		printmsg.innerHTML += msg + "<br /><br/ >";
		
		var mWrapper = document.createElement("div");
		mWrapper.id = "MSG_wrapper";
		mWrapper.appendChild(printmsg);
		
		var formCoords = getOption("MSG_POSITION", "300px_500px");
		formCoords = formCoords.split("_");
		mWrapper.style.top = formCoords[0];
		mWrapper.style.left = formCoords[1];
		
		document.body.appendChild(mWrapper);
		makeDraggable($("printmsg"));
	}
	
	
	function createUpdateFloat(eventt){ //this eventt is the "click" on the TaskUrl. it is a event object.
		myUrl = eventt.target; //by this method, define the event object and get the <a> that call this function. 
		crtvillagee = myUrl.getAttribute("crtvillage");//then the Attributes of the <a> are usable.
		buildNamee = myUrl.getAttribute("buildName");
		bnextlevel = parseInt(myUrl.getAttribute("buildnextlevel"));
		bmaxlevel = parseInt(myUrl.getAttribute("buildmaxlevel"));
		buildgid=(myUrl.getAttribute("buildgid"))?myUrl.getAttribute("buildgid"):"";
		bidid = myUrl.getAttribute("buildidid");
		
		var taskKind=(buildgid=="")?"0":"1"
		var updataform = document.createElement("form");
		updataform.id = "updataform";
		var floatClose = "<a href='#' onclick='document.body.removeChild($(\"taskForm_wrapper\"));' class='floatClose'><img src='" + sCloseBtn + "' alt='X' /></a>";
		updataform.innerHTML = floatClose;
		if (bidid < 19 & !GM_getValue(currentServer() + "_" + getuid() + "_mainvillageId")) {
			updataform.innerHTML += "<br />" + otherText[0].big() + "!!!<br /><br />" + otherText[1] + "<br /><br />";
			var privateeee = document.evaluate('id("sleft")/descendant::a[contains(@href,"spieler")]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			updataform.innerHTML += otherText[2] + ":    <a href='" + privateeee.singleNodeValue.href + "'>&#160;&#160;&#160;&#160;&#160;" + privateeee.singleNodeValue.innerHTML + "</a><br /><br />";
		}
		else {
			updataform.innerHTML += "<br />" + addTaskText[0].big() + "<br /><br />";
			updataform.innerHTML += addTaskText[1] + ":  <select id='taskkindss'><option value='" + taskKind + "'>" + TaskKind[0] + "</option></select><br /><br />";
			updataform.innerHTML += addTaskText[2] + ":  <select id='crtvillagee'><option value='" + crtvillagee + "'>" + getvillagefromdid(crtvillagee) + "</option></select><br /><br />";
			updataform.innerHTML += addTaskText[3] + ":  <select id='buildNamee'><option value='" + buildNamee + "'>" + buildNamee + "</option></select><br /><br />";
			updataform.innerHTML += gametext[2] + ":  <select id='bidid'><option value='" + bidid + "'>" + bidid + "</option></select><br /><br />";
			updataform.innerHTML += addTaskText[4] + ":  " + levelselect(bnextlevel, bmaxlevel) + "<br /><br />";
			tod = new Date();
			ye = tod.getFullYear();
			mon = tod.getMonth();
			dat = tod.getDate();
			hou = tod.getHours();
			minu = tod.getMinutes();
			sec = tod.getSeconds();
			nowtime = ye + "/" + mon + "/" + dat + " " + hou + ":" + minu + ":" + sec
			updataform.innerHTML += gametext[4] + ":  <input type='text' id='userSetTime' value='" + nowtime + "' /><br />";
			updataform.innerHTML += "(" + gametext[5] + ")<br /><br />"
			
			
			var oSubmitBtn = document.createElement("input");
			oSubmitBtn.name = "submitBtn";
			oSubmitBtn.id = "submitBtn";
			oSubmitBtn.value = "OK";
			oSubmitBtn.type = "button";
			oSubmitBtn.addEventListener('click', setTaskCookies, true);
			//			oSubmitBtn.addEventListener('click', addToTasklist, true);
			updataform.appendChild(oSubmitBtn);
		}
		var oWrapper = document.createElement("div");
		oWrapper.id = "taskForm_wrapper";
		oWrapper.appendChild(updataform);
		
		var formCoords = getOption("FORM_POSITION", "218px_468px");
		formCoords = formCoords.split("_");
		oWrapper.style.top = formCoords[0];
		oWrapper.style.left = formCoords[1];
		
		document.body.appendChild(oWrapper);
		makeDraggable($("updataform"));
	}
	
	
	function getvillagefromdid(did){
		var getitit = document.evaluate('id("vlist")//a[contains(@href,"' + did + '")]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return (getitit.singleNodeValue) ? getitit.singleNodeValue.innerHTML : GM_getValue(currentServer() + "_" + getuid() + "_mainvillageName")
	}
	
	
	function getDidFromVillage(vil){
		var getfoots = document.evaluate('id("vlist")/descendant::a[@href]', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		if (getfoots.snapshotLength > 0) {
			for (var i = 0; i < getfoots.snapshotLength; i++) {
				if (getfoots.snapshotItem(i).innerHTML==vil) {
					longstring = getfoots.snapshotItem(i).href.match(/newdid=\d{3,}/);
					break;
				}
			}
			return longstring.toString().match(/\d{3,}/).toString()
		}
		else {
			return GM_getValue(currentServer() + "_" + getuid() + '_singleTownNEWDID')
		}
	}
	
	
	function levelselect(min, max){
		var levelsel = '<select id="levelselect" name="levelselect">'
		for (min; min <= max; min++) {
			levelsel += '<option value="' + min + '">' + gametext[6] + ' ' + gametext[0] + ' ' + min + '</option>'
		}
		levelsel += '</select>';
		return levelsel
	}
	
	
	function getTaskCookies(){
		for (e in getAllVillageNewdids()) { //check all villages task cookies
			whatever = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_waitTask", "false")
			if (whatever != "false") {
				allTasks = whatever.split("|")
				for (nnn in allTasks) {
					thisTask = allTasks[nnn].split("_")
					
					switch (thisTask[0]) {
					
						case "0":// 0 is update
							var buildTimepoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_BuildingUpdataTime", "false")
							var resourceTimepoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_ResourceUpdataTime", "false")
							var updataTimepoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_UpdataTime", "false")
							if (GM_getValue(currentServer() + "_" + getuid() + "_raceID") == "0") { //Romans double build
								if (thisTask[1] < 19) {//resource
									if (resourceTimepoint == "false") {
										taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allsourceString, thisTask)
										GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
									}
								}
								else 
									if (thisTask[1] > 18 & thisTask[1] < 42) { //build in village
										if (buildTimepoint == "false") {
											taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allbuildString, thisTask)
											GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
										}
									}
									else {//if >=42, it is autoResourceModel
										if (resourceTimepoint == "false") {
											taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allsourceString, thisTask)
											GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
										}
									}
							}
							else {// others race single build
								if (updataTimepoint == "false") {
									taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allString, thisTask)
									GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
								}
							}
							break;
							
							
						case "1"://"1" is new building 
							var buildTimepoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_BuildingUpdataTime", "false")
							var updataTimepoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_UpdataTime", "false")
							if (GM_getValue(currentServer() + "_" + getuid() + "_raceID") == "0") { //Romans double build
								if (buildTimepoint == "false") {
									taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allbuildString, thisTask)
									GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
								}
							}
							else {// others race single build
								if (updataTimepoint == "false") {
									taskTime = startBuildOrSetTime(getAllVillageNewdids()[e], allString, thisTask)
									GM_log("the taskTime return from startBuildOrSetTime is " + taskTime)
								}
							}
							break;
							
							
						/*					 case TaskKind[2]:
					 break;
					 case TaskKind[3]:
					 break;
					 case TaskKind[4]:
					 break;*/
						case "5"://"5" is auto transport  5_model_toid_toposition
							var hereResource = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_ResourceNow", "false")
							var tarResource = GM_getValue(currentServer() + "_" + getuid() + "_" + thisTask[2] + "_ResourceNow", "false")
							var resTraning = GM_getValue(currentServer() + "_" + getuid() + "_" + thisTask[2] + "_ResourceTraning", "0/0/0/0")
							var userTranSetup = GM_getValue(currentServer() + "_" + getuid() + "_" + thisTask[2] + "_userTranSetup", "false")
							var WareCap = GM_getValue(currentServer() + "_" + getuid() + "_" + thisTask[2] + "_WarehouseCap", "false");
							var GranCap = GM_getValue(currentServer() + "_" + getuid() + "_" + thisTask[2] + "_GranaryCap", "false");
							var tranTimePoint = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_to_" + thisTask[3] + "_autoTransTime", "false")
							if (tarResource == "false" || WareCap == "false" || GranCap == "false") {
								window.location.replace("http://" + window.location.hostname + "/dorf2.php?newdid=" + thisTask[2])
							}
							if (hereResource == "false") {
								window.location.replace("http://" + window.location.hostname + "/dorf2.php?newdid=" + getAllVillageNewdids()[e])
							}
							var WareCap = parseInt(WareCap)
							var GranCap = parseInt(GranCap)
							var resnow = tarResource.split("/");
							resnow[0] = parseInt(resnow[0])
							resnow[1] = parseInt(resnow[1])
							resnow[2] = parseInt(resnow[2])
							resnow[3] = parseInt(resnow[3])
							var restran = resTraning.split("/");
							restran[0] = parseInt(restran[0])
							restran[1] = parseInt(restran[1])
							restran[2] = parseInt(restran[2])
							restran[3] = parseInt(restran[3])
							var reshere = hereResource.split("/");
							reshere[0] = parseInt(reshere[0])
							reshere[1] = parseInt(reshere[1])
							reshere[2] = parseInt(reshere[2])
							reshere[3] = parseInt(reshere[3])
							if (tranTimePoint == "false") {
								switch (thisTask[1]) {
									case "0"://building surport model.
										if (userTranSetup == "false") {
											if (WareCap < 18000 || GranCap < 18000) {//  80%warehouse remain
												var transtarget1 = WareCap * 0.8
												var transtarget2 = GranCap * 0.8
											}
											else {//15000 and 16000 remain
												var transtarget1 = 15000;
												var transtarget2 = 16000;
											}
										}
										else {
											var transtarget1 = parseInt(userTranSetup.split("/")[0]);
											var transtarget2 = parseInt(userTranSetup.split("/")[1]);
										}
										break;
										
									case "1":
										var transtarget1 = WareCap * 0.9
										var transtarget2 = GranCap * 0.9
										break;
								}
								if ((resnow[0] + restran[0]) < transtarget1 && reshere[0] > 500 || (resnow[1] + restran[1]) < transtarget1 && reshere[1] > 500 || (resnow[2] + restran[2]) < transtarget1 && reshere[2] > 500 || (resnow[3] + restran[3]) < transtarget2 && reshere[3] > 500) {
									trantime = startTransOrSetTime(getAllVillageNewdids()[e], thisTask)
									GM_log("the autotrantime back from startTransOrSetTime() is " + trantime)
								}
							}
							break;
					/*	
					 
					 case TaskKind[6]:
					 break;*/
					 case "7"://"7_" + theID +"_" + crtlevel + "_" + currentID() + "_" +theBuild
					 	var demoTime = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[e] + "_demolishTime", "false");
						if(demoTime=="false"){
							demotimee=startDemoOrSetTime(getAllVillageNewdids()[e], thisTask)
							GM_log("the demotime back from startDemoOrSetTime() is " + demotimee)
						}
					 break;
					/* case TaskKind[8]:
					 break;
					 case TaskKind[9]:
					 break;  */
					}
				}
			}
		}
	}
	
	function startDemoOrSetTime(vi){
		GM_log("come into startDemoOrSetTime() at " + getvillagefromdid(vi) )
		var myower = window.clearInterval(myower);
		var turl= "http://" + window.location.hostname + "/build.php?newdid=" + vi + "&gid=15"
		var getDelayTime = new XMLHttpRequest();
		getDelayTime.open('GET', turl, false);
		getDelayTime.onreadystatechange = callback;
		getDelayTime.send(null);
		function callback(){
			if (getDelayTime.readyState == 4) {
				if (getDelayTime.status == 200) {
					GM_log("here is startTransOrSetTime callback function")
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getDelayTime.responseText;
					aDoc.appendChild(aElem);
					
					var ddg=new Date();
					if(aDoc.getElementById("demolish")){
						gettime=aDoc.getElementById("demolish").innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
						demot = gettime.toString().split(":")
						endt = ddg.getTime() + Number(demot[0]) * 60 * 60 * 1000 + Number(demot[1]) * 60 * 1000 + Number(demot[2]) * 1000+10000;
						ddg.setTime(endt)
						GM_log("some demolish is doing, next demo start at "+ddg)
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_demolishTime", endt.toString());
						return endt
					}
					else{
						endt = ddg.getTime() +10000;
						ddg.setTime(endt)
						GM_log("No demolish is doing, next demo start soon, just at "+ddg)
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_demolishTime", endt.toString());
						return endt
					}
				}
			}
		}
		return callback()
	}

	
	function startTransOrSetTime(vi, tTask){
		GM_log("come into startTransOrSetTime() from " + getvillagefromdid(vi) + " to " + getvillagefromdid(tTask[2]))
		var myower = window.clearInterval(myower)
		var turl = "http://" + window.location.hostname + "/build.php?newdid=" + vi + "&gid=17"
		var getDelayTime = new XMLHttpRequest();
		getDelayTime.open('GET', turl, false);
		getDelayTime.onreadystatechange = callback;
		getDelayTime.send(null);
		function callback(){
			if (getDelayTime.readyState == 4) {
				if (getDelayTime.status == 200) {
					GM_log("here is startTransOrSetTime callback function")
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getDelayTime.responseText;
					aDoc.appendChild(aElem);
					
					resource = [aDoc.getElementById("l4").innerHTML.split("/")[0], aDoc.getElementById("l3").innerHTML.split("/")[0], aDoc.getElementById("l2").innerHTML.split("/")[0], aDoc.getElementById("l1").innerHTML.split("/")[0]]
					resstring = resource.join("/")
					GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_ResourceNow", resstring);
					resource[0] = parseInt(resource[0])
					resource[1] = parseInt(resource[1])
					resource[2] = parseInt(resource[2])
					resource[3] = parseInt(resource[3])
					
					var ma = "0"//this is just a mark,if transing is found ,it is "1", else "0".
					var transing = [0, 0, 0, 0]
					var Transtime = 1500000000000;
					var gugagaa = new Date()
					var reg111 = gametext[10] + gametext[7]//to
					var reg222 = gametext[12] + gametext[7]//back from
					var alltranTo = aDoc.evaluate('//table//a[contains(@href,"php?d=' + tTask[3] + '")]', aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
					if (alltranTo.snapshotLength > 0) {
						for (var z = 0; z < alltranTo.snapshotLength; z++) {
							if (alltranTo.snapshotItem(z).innerHTML.indexOf(reg111) != -1) {
								var ma = "1"
								ress = alltranTo.snapshotItem(z).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/>\d{1,}(?![:(\d:)])/g)
								
								transing[0] += parseInt(ress[0].split(">")[1])
								transing[1] += parseInt(ress[1].split(">")[1])
								transing[2] += parseInt(ress[2].split(">")[1])
								transing[3] += parseInt(ress[3].split(">")[1])
								
								resttt = alltranTo.snapshotItem(z).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
								restttttt = resttt.toString().split(":")
								gobacktime = gugagaa.getTime() + Number(restttttt[0]) * 60 * 60 * 1000 + Number(restttttt[1]) * 60 * 1000 + Number(restttttt[2]) * 1000;
								Transtime = Math.min(Transtime, gobacktime)
							}
						}
						if (ma == "0") {
							GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", "1500000000000")
						}
						lastTrantime = (Transtime == 1500000000000) ? 1500000000000 : Transtime + 5000
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", lastTrantime.toString())
						var oioi = new Date(lastTrantime)
						GM_log("the traning will arrive at " + oioi)
						GM_setValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_ResourceTraning", transing.join("/"))
						GM_log("all resources on transporting are " + transing.join("/"))
					}
					else {
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", "1500000000000")
					}
					
					var tarResource = GM_getValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_ResourceNow")
					var WareCap = GM_getValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_WarehouseCap");
					var GranCap = GM_getValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_GranaryCap");
					var userTranSetup = GM_getValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_userTranSetup", "false")
					
					var WareCap = parseInt(WareCap)
					var GranCap = parseInt(GranCap)
					var resnow = tarResource.split("/");
					resnow[0] = parseInt(resnow[0])
					resnow[1] = parseInt(resnow[1])
					resnow[2] = parseInt(resnow[2])
					resnow[3] = parseInt(resnow[3])
					
					var comm = [0, 0]
					var pp = getDelayTime.responseText.match(/<b>\d{3,4}<\/b>/)
					comm[1] = pp.toString().match(/\d{3,4}/)
					var qq = aDoc.evaluate('//table[@id="target_select"]/descendant::td[@class="mer"]', aElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
					comm[0] = qq.singleNodeValue.innerHTML.split(" ")[1].split("/")[0]
					GM_log("now Merchants at home is " + comm[0] + ", and each Merchants can load " + comm[1])
					comm[0] = parseInt(comm[0])
					comm[1] = parseInt(comm[1])
					
					switch (tTask[1]) {
						case "0"://building surport model.
							if (userTranSetup == "false") {
								if (WareCap < 18000 || GranCap < 18000) {//  80%warehouse remain
									var transtarget1 = WareCap * 0.8
									var transtarget2 = GranCap * 0.8
								}
								else {//15000 and 16000 remain
									var transtarget1 = 15000;
									var transtarget2 = 16000;
								}
							}
							else {//user setup
								var transtarget1 = parseInt(userTranSetup.split("/")[0]);
								var transtarget2 = parseInt(userTranSetup.split("/")[1]);
							}
							break;
							
						case "1":
							var transtarget1 = WareCap * 0.9
							var transtarget2 = GranCap * 0.9
							break;
					}

					
					var ddg = new Date();
					if ((resnow[0] + transing[0]) < transtarget1 || (resnow[1] + transing[1]) < transtarget1 || (resnow[2] + transing[2]) < transtarget1 || (resnow[3] + transing[3]) < transtarget2) {
						if (comm[0] > 0) {
							Tasktime = ddg.getTime() + 10000
							GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_autoTransTime", Tasktime.toString())
							var d = new Date(Tasktime)
							GM_log("next transport begin from " + d)
							return Tasktime
						}
						else {
							var waitTimee = 1500000000000;
							var allback = aDoc.evaluate('//table//a[contains(@href,"php?d=")]', aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
							if (allback.snapshotLength > 0) {
								for (var j = 0; j < allback.snapshotLength; j++) {
									if (allback.snapshotItem(j).innerHTML.indexOf(reg111) != -1) {
										ttt = allback.snapshotItem(j).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
										tttar = ttt.toString().split(":")
										gotime = parseInt(tttar[0]) * 60 * 60 * 1000 + parseInt(tttar[1]) * 60 * 1000 + parseInt(tttar[2]) * 1000
										alltimeback = gotime + getMerchanTime(vi, tTask[3])
										waitTimee = Math.min(waitTimee, alltimeback)
										GM_log("the transout will came back after " + waitTimee)
									}
									else 
										if (allback.snapshotItem(j).innerHTML.indexOf(reg222) != -1) {
											ttt = allback.snapshotItem(j).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
											tttar = ttt.toString().split(":")
											gotime = parseInt(tttar[0]) * 60 * 60 * 1000 + parseInt(tttar[1]) * 60 * 1000 + parseInt(tttar[2]) * 1000
											waitTimee = Math.min(waitTimee, gotime)
											GM_log("the comebacks will come back after..." + waitTimee)
										}
								}
							}
							Tasktime = ddg.getTime() + waitTimee + 10000;
							GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_autoTransTime", Tasktime.toString())
							var d = new Date(Tasktime)
							GM_log("next transport begin from " + d)
							return Tasktime
						}
					}
					else {
						return "1500000000000"
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_autoTransTime")
					}
				}
			}
		}
		return callback()
	}
	
	
	function fleshTraning(vi, tTask){
		GM_log("come into fleshTraning in " + getvillagefromdid(vi))
		var turl = "http://" + window.location.hostname + "/build.php?newdid=" + vi + "&gid=17"
		GM_log("url=" + turl)
		var getDelayTime = new XMLHttpRequest();
		getDelayTime.open('GET', turl, false);
		getDelayTime.onreadystatechange = callback;
		getDelayTime.send(null);
		function callback(){
			if (getDelayTime.readyState == 4) {
				if (getDelayTime.status == 200) {
					GM_log("transporting flesh Require callback here")
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getDelayTime.responseText;
					aDoc.appendChild(aElem);
					var ma = "0"
					var transing = [0, 0, 0, 0]
					var Transtime = 1500000000000;
					var gugagaa = new Date()
					var reg111=gametext[10]+gametext[7]//to
					var reg222=gametext[12]+gametext[7]//back from
					
					var alltranTo = aDoc.evaluate('//table//a[contains(@href,"php?d=' + tTask[3] + '")]', aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
					
					if (alltranTo.snapshotLength > 0) {
						for (var g = 0; g < alltranTo.snapshotLength; g++) {
							if (alltranTo.snapshotItem(g).innerHTML.indexOf(reg111) != -1) {
								var ma = "1"
								ress = alltranTo.snapshotItem(g).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/>\d{1,}(?![:(\d:)])/g)
								transing[0] += parseInt(ress[0].split(">")[1])
								transing[1] += parseInt(ress[1].split(">")[1])
								transing[2] += parseInt(ress[2].split(">")[1])
								transing[3] += parseInt(ress[3].split(">")[1])
								
								resttt = alltranTo.snapshotItem(g).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
								restttttt = resttt.toString().split(":")
								gobacktime = gugagaa.getTime() + Number(restttttt[0])*60*60*1000 + Number(restttttt[1]) *60*1000 + Number(restttttt[2])*1000;
								Transtime = Math.min(Transtime, gobacktime)
							}
						}
						if (ma == "0") {
							GM_log("some transport on road, but no out just back...")
							GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", "1500000000000")
							GM_setValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_ResourceTraning", "0/0/0/0")
						}
						lastTrantime = (Transtime == 1500000000000) ? 1500000000000 : Transtime + 5000
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", lastTrantime.toString())
						var ggr=new Date(lastTrantime)
						GM_log("next reflesh start at " + ggr)
						GM_setValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_ResourceTraning", transing.join("/"))
						GM_log("all resources on transporting are " + transing.join("/"))
						window.location.replace("http://" + window.location.hostname + "/build.php?newdid=" + tTask[2])
						return Transtime
					}
					else {
						GM_log("No transport at all...")
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tTask[3] + "_TraningTime", "1500000000000")
						GM_setValue(currentServer() + "_" + getuid() + "_" + tTask[2] + "_ResourceTraning", "0/0/0/0")
						window.location.replace("http://" + window.location.hostname + "/build.php?newdid=" + tTask[2])
						return "1500000000000"
					}
				}
			}
		}
		return callback()
	}
	
	
	
	function getMerchanTime(vi, positionnum){
		xRace = GM_getValue(currentServer() + "_" + getuid() + "_raceID")
		posi1 = getPosFromVill(getvillagefromdid(vi));
		sx1 = getXfromCoord(posi1)
		sy1 = getYfromCoord(posi1)
		sx2 = getXfromCoord(positionnum)
		sy2 = getYfromCoord(positionnum)
		qDist = getDistance(sx1, sy1, sx2, sy2)
		xRace=parseInt(xRace);
		var aTime = Math.round(qDist * 3600000 / mts[xRace]);
		return aTime;
	}
	
	
	function getDistance(sx1, sy1, sx2, sy2){
		var x1 = parseInt(sx1);
		var y1 = parseInt(sy1);
		var x2 = parseInt(sx2);
		var y2 = parseInt(sy2);
		var dX = Math.min(Math.abs(x2 - x1), Math.abs(801 - Math.abs(x2 - x1)));
		var dY = Math.min(Math.abs(y2 - y1), Math.abs(801 - Math.abs(y2 - y1)));
		var dist = Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2));
		return dist;
	}
	
	
	function startBuildOrSetTime(Villageid, str, task){
		GM_log("come into startBuildOrSetTime() at "+getvillagefromdid(Villageid))
		var myower = window.clearInterval(myower)
		var turl = "http://" + window.location.hostname + "/dorf1.php?newdid=" + Villageid
		var getDelayTime = new XMLHttpRequest();
		getDelayTime.open('GET', turl, false);
		getDelayTime.onreadystatechange = callback;
		getDelayTime.send(null);
		function callback(){
			if (getDelayTime.readyState == 4) {
				if (getDelayTime.status == 200) {
					GM_log("startBuildOrSetTime ")
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getDelayTime.responseText;
					aDoc.appendChild(aElem);
					if (task[0] == "0" & task[1] > 42) {//autoResource date get
						var CorpRemain = aDoc.evaluate("id('res')/descendant::td", aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
						hehe = CorpRemain.snapshotLength - 1
						corpcost = CorpRemain.snapshotItem(hehe).innerHTML.split("/")[0]
						corpprod = CorpRemain.snapshotItem(hehe).innerHTML.split("/")[1]
						GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_CorpRemain", (corpprod - corpcost))
						
						var doneID = GM_getValue(currentServer() + "_" + getuid() + "_" + Villageid + "_autoResourceDone", "20")
						var allRess = aDoc.evaluate('id("rx")//area[contains(@href,"build.php?id=")]', aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
						var numm = 20;
						var numm2 = 20;
						for (var i = 0; i < allRess.snapshotLength; i++) {//get the min level
							ddq = parseInt(allRess.snapshotItem(i).title.split(" ")[2])
							numm = Math.min(numm, ddq);
						}
						sounttt = "0";//this is just a mark....found XXX, change to "1", no found remain "0"
						for (j = 0; j < allRess.snapshotLength; j++) {
							if (parseInt(allRess.snapshotItem(j).title.split(" ")[2]) == numm & allRess.snapshotItem(j).href.split("id=")[1].toString() != doneID) {
								myid = allRess.snapshotItem(j).href.split("id=")[1];
								GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_minLevelId", myid)
								sounttt = "1";
								break;
							}
						}
						if (sounttt == "0") {//the min level is onbuilding one, ok, i search for a higher level one
							for (n = 0; n < allRess.snapshotLength; n++) {
								if (parseInt(allRess.snapshotItem(n).title.split(" ")[2]) == (numm + 1) & allRess.snapshotItem(n).href.split("id=")[1].toString() != doneID) {
									myid = allRess.snapshotItem(n).href.split("id=")[1];
									GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_minLevelId", myid)
									break;
								}
							}
						}
						
						for (k = 0; k < allRess.snapshotLength; k++) {//collect all Crop level ,find the lowest one
							if (allRess.snapshotItem(k).title.split(" ")[0] == allbuildwithid[3]) {
								ffq = parseInt(allRess.snapshotItem(k).title.split(" ")[2])
								numm2 = Math.min(numm2, ffq);
							}
						}
						mouu = "0"//this is a mark too, to find the minlevel crop
						for (l = 0; l < allRess.snapshotLength; l++) {
							if (parseInt(allRess.snapshotItem(l).title.split(" ")[2]) == numm2 & allRess.snapshotItem(l).title.split(" ")[0] == allbuildwithid[3] & allRess.snapshotItem(l).href.split("id=")[1].toString() != doneID) {
								myids = allRess.snapshotItem(l).href.split("id=")[1];
								GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_minLevelCropId", myids)
								mouu = "1";
								break;
							}
						}
						if (mouu == "0") {
							for (m = 0; m < allRess.snapshotLength; m++) {
								if (parseInt(allRess.snapshotItem(m).title.split(" ")[2]) == (numm2 + 1) & allRess.snapshotItem(m).title.split(" ")[0] == allbuildwithid[3] & allRess.snapshotItem(m).href.split("id=")[1].toString() != doneID) {
									myids = allRess.snapshotItem(m).href.split("id=")[1];
									GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_minLevelCropId", myids)
									break;
								}
							}
						}
					}//autoResouce data end here
					
					var aValue = aDoc.evaluate('id("building_contract")/descendant::td', aElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
					if (aValue.snapshotLength > 0) {
						var testttt = "0"//this is a mark for search result, default is 0 ,if found ,change to 1
						for (var i = 0; i < aValue.snapshotLength; i++) {
							thestring = aValue.snapshotItem(i).innerHTML.match(/[\u4E00-\u9FA5]{2,}/);
							if (str.indexOf(thestring) != -1) {//index resource name from the resourcestring
								GM_log("which in building is " + thestring)
								testttt = "1"
								var tt = aValue.snapshotItem(i).parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
								ttar = tt.toString().split(":")
								arriveTime = parseInt(ttar[0]) * 60 * 60 * 1000 + parseInt(ttar[1]) * 60 * 1000 + parseInt(ttar[2]) * 1000 + 10000
								ddg = new Date()
								Tasktime = ddg.getTime() + arriveTime
								switch (str) {
									case allsourceString:
										GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_ResourceUpdataTime", Tasktime.toString())
										GM_log("startBuildOrSetTime(Villageid):resource is building, will return milsec=" + Tasktime.toString())
										var d = new Date(Tasktime)
										GM_log("next task begin from " + d)
										return Tasktime
										break;
									case allbuildString:
										GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_BuildingUpdataTime", Tasktime.toString())
										GM_log("startBuildOrSetTime(Villageid):building is building, will return milsec=" + Tasktime.toString())
										var d = new Date(Tasktime)
										GM_log("next task begin from " + d)
										return Tasktime
										break;
									case allString:
										GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_UpdataTime", Tasktime.toString())
										GM_log("startBuildOrSetTime(Villageid):something is building, will return milsec=" + Tasktime.toString())
										var d = new Date(Tasktime)
										GM_log("next task begin from " + d)
										return Tasktime
										break;
								}
							}
						}
						if (testttt == "0") {//another kinds of building is building
							GM_log("oh,another kinds of building is building, i can updata immediately")
							ddg = new Date()
							Tasktime = ddg.getTime() + 10000 //10 seconds later start build.
							switch (str) {
								case allsourceString:
									GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_ResourceUpdataTime", Tasktime.toString())
									GM_log("startBuildOrSetTime(Villageid):resource will build soon, will return milsec=" + Tasktime.toString())
									return Tasktime
									break;
								case allbuildString:
									GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_BuildingUpdataTime", Tasktime.toString())
									GM_log("startBuildOrSetTime(Villageid):building will build soon, will return milsec=" + Tasktime.toString())
									return Tasktime
									break;
								case allString: //it is impossible.
									GM_log("it is impossible.")
									break;
							}
						}
					}
					else {
						GM_log("now,i find no build is building")
						ddg = new Date()
						Tasktime = ddg.getTime() + 10000
						switch (str) {
							case allsourceString:
								GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_ResourceUpdataTime", Tasktime.toString())
								GM_log("startBuildOrSetTime(Villageid):resource will build soon, will return milsec=" + Tasktime.toString())
								return Tasktime
								break;
							case allbuildString:
								GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_BuildingUpdataTime", Tasktime.toString())
								GM_log("startBuildOrSetTime(Villageid):building will build soon, will return milsec=" + Tasktime.toString())
								return Tasktime
								break;
							case allString:
								GM_setValue(currentServer() + "_" + getuid() + "_" + Villageid + "_UpdataTime", Tasktime.toString())
								GM_log("startBuildOrSetTime(Villageid):something will build soon, will return milsec=" + Tasktime.toString())
								return Tasktime
								break;
						}
					}
				}
			}
		}
		return callback()
	}
	
	
	function startBuildnow(vill, kind){
		GM_log("come into startBuildnow()" +vill +" "+ kind)
		var myower = window.clearInterval(myower)
		whatever = GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_waitTask", "false")
		allTasks = whatever.split("|")
		
		switch (kind) {
			case "0"://Romans Resource
				for (nnn in allTasks) {
					thisTask = allTasks[nnn].split("_")
					if (thisTask[0] == "0" & thisTask[1] < 19) {
						b = getthebuildUrl(vill, thisTask)
						if (b) {
							buildurl = "http://" + window.location.hostname + "/" + b
							thislevel = parseInt(GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_crtBuildlevel")) + 1
							GM_log("start Require now")
							HttpRequire(buildurl, vill, thisTask, kind, thislevel)
							break;
						}
					}
					else 
						if (thisTask[0] == "0" & thisTask[1] > 42) {//Romans autoResource
						thisTask[1]=getAutoResourceId(vill)
						b = getthebuildUrl(vill, thisTask)
						if (b) {
							buildurl = "http://" + window.location.hostname + "/" + b
							thislevel = parseInt(GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_crtBuildlevel")) + 1
							GM_log("start Require now")
							HttpRequire(buildurl, vill, thisTask, kind, thislevel)
							break;
						}
							else 
								if (getErrorInfor() == errorText[5]) {
									addtaskbefore(vill, "10", kind);
								}
								else 
									if (getErrorInfor() == errorText[6]) {
										addtaskbefore(vill, "11", kind);
									}
							break;
						}
				}
			break;
			case "1"://Romans building
				for (nnn in allTasks) {
					thisTask = allTasks[nnn].split("_")
					if (thisTask[0] == "0" & thisTask[1] > 18 & thisTask[1] < 42) {
						b = getthebuildUrl(vill, thisTask)
						if (b) {
							buildurl = "http://" + window.location.hostname + "/" + b
							thislevel = parseInt(GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_crtBuildlevel")) + 1
							GM_log("start Require now")
							HttpRequire(buildurl, vill, thisTask, kind, thislevel)
							break;
						}
					}
					else if(thisTask[0] == "1"){//Romans new build
						b = getthebuildUrl(vill, thisTask)
						if (b) {
							buildurl = "http://" + window.location.hostname + "/" + b
							thislevel = 1
							GM_log("start Require now")
							HttpRequire(buildurl, vill, thisTask, kind, thislevel)
							break;
						}						
					}
				}
			break;
			case "2"://other race every updata
				for (nnn in allTasks) {
					thisTask = allTasks[nnn].split("_");
					if (thisTask[0] == "0" && thisTask[1] < 42) {
						b = getthebuildUrl(vill, thisTask)
						if (b) {
							buildurl = "http://" + window.location.hostname + "/" + b
							thislevel = parseInt(GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_crtBuildlevel")) + 1
							GM_log("start Require now")
							HttpRequire(buildurl, vill, thisTask, kind, thislevel)
							break;
						}
					}
					else 
						if (thisTask[0] == "0" & thisTask[1] > 41) {//autoResource
							thisTask[1] = getAutoResourceId(vill)
							b = getthebuildUrl(vill, thisTask)
							if (b) {
								buildurl = "http://" + window.location.hostname + "/" + b
								thislevel = parseInt(GM_getValue(currentServer() + "_" + getuid() + "_" + vill + "_crtBuildlevel")) + 1
								GM_log("start Require now")
								HttpRequire(buildurl, vill, thisTask, kind, thislevel)
								break;
							}
							else 
								if (getErrorInfor() == errorText[5]) {
									addtaskbefore(vill, "10", kind);
								}
								else 
									if (getErrorInfor() == errorText[6]) {
										addtaskbefore(vill, "11", kind);
									}
						}
						else 
							if (thisTask[0] == "1") {//new build
								b = getthebuildUrl(vill, thisTask)
								if (b) {
									buildurl = "http://" + window.location.hostname + "/" + b;
									thislevel = 1;
									GM_log("start Require now");
									HttpRequire(buildurl, vill, thisTask, kind, thislevel)
									break;
								}
							}
				}
			break;
		}
	}
	
	
function startTrannow(vi, tranTask){
	GM_log("come into startTrannow()")
	var myower = window.clearInterval(myower)
	var turl = "http://" + window.location.hostname + "/build.php?newdid=" + vi + "&gid=17"
	var tarResource = GM_getValue(currentServer() + "_" + getuid() + "_" + tranTask[2] + "_ResourceNow", "false")
	var WareCap = GM_getValue(currentServer() + "_" + getuid() + "_" + tranTask[2] + "_WarehouseCap", "false");
	var GranCap = GM_getValue(currentServer() + "_" + getuid() + "_" + tranTask[2] + "_GranaryCap", "false");
	var userTranSetup = GM_getValue(currentServer() + "_" + getuid() + "_" + tranTask[2] + "_userTranSetup", "false")
	var WareCap = parseInt(WareCap)
	var GranCap = parseInt(GranCap)
	var resnow = tarResource.split("/");
	resnow[0] = parseInt(resnow[0])
	resnow[1] = parseInt(resnow[1])
	resnow[2] = parseInt(resnow[2])
	resnow[3] = parseInt(resnow[3])
	GM_xmlhttpRequest({
		method: 'GET',
		url: turl,
		headers: "",
		onload: function(responseDetails){
			GM_log("here is startTrannow callback function")		
			var ssDoc = document.implementation.createDocument("", "", null);
			var ssElem = document.createElement('DIV');
			ssElem.innerHTML = responseDetails.responseText;
			ssDoc.appendChild(ssElem);
			
			resource = [ssDoc.getElementById("l4").innerHTML.split("/")[0], ssDoc.getElementById("l3").innerHTML.split("/")[0], ssDoc.getElementById("l2").innerHTML.split("/")[0], ssDoc.getElementById("l1").innerHTML.split("/")[0]]
			GM_log("resource=" + resource)
			var transing = [0, 0, 0, 0]
			var reg111 = gametext[10] + gametext[7]//to
			var reg222 = gametext[12] + gametext[7]//back from
			var alltranTo = ssDoc.evaluate('//table//a[contains(@href,"php?d=' + tranTask[3] + '")]', ssElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
			if (alltranTo.snapshotLength > 0) {
				for (var i = 0; i < alltranTo.snapshotLength; i++) {
					if (alltranTo.snapshotItem(i).innerHTML.indexOf(reg111) != -1) {
						ress = alltranTo.snapshotItem(i).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/>\d{1,}(?![:(\d:)])/g)
						transing[0] += parseInt(ress[0].split(">")[1])
						transing[1] += parseInt(ress[1].split(">")[1])
						transing[2] += parseInt(ress[2].split(">")[1])
						transing[3] += parseInt(ress[3].split(">")[1])
						GM_log("in startTrannow(vi,tranTask), transing=" + transing)
					}
				}
			}
			
			var ids = ssDoc.evaluate('//div[@id="textmenu"]/a', ssElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			theid = ids.singleNodeValue.href.split("id=")[1]
			var ddg = new Date();
			comm = ["", ""]
			var pp = ssDoc.evaluate('//table[@id="send_select"]/descendant::td[@class="max"]/a', ssElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			comm[1] = pp.singleNodeValue.innerHTML.match(/\d{3,4}/)
			var qq = ssDoc.evaluate('//table[@id="target_select"]/descendant::td[@class="mer"]', ssElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			comm[0] = qq.singleNodeValue.innerHTML.split(" ")[1].split("/")[0]
			GM_log("now Merchants at home is " + comm[0] + ", and each Merchants can load " + comm[1])
			comm[0] = parseInt(comm[0])
			comm[1] = parseInt(comm[1])
			
			switch (tranTask[1]) {
				case "0"://building surport model.
					if (userTranSetup == "false") {
						if (WareCap < 18000 || GranCap < 18000) {//  80%warehouse remain
							var transtarget1 = WareCap * 0.8
							var transtarget2 = GranCap * 0.8
						}
						else {//15000 and 16000 remain
							var transtarget1 = 15000;
							var transtarget2 = 16000;
						}
					}
					else {//user setup
						var transtarget1 = parseInt(userTranSetup.split("/")[0]);
						var transtarget2 = parseInt(userTranSetup.split("/")[1]);
					}
					break;
					
				case "1":
					var transtarget1 = WareCap * 0.9
					var transtarget2 = GranCap * 0.9
					break;
			}
			
			if ((resnow[0] + transing[0]) < transtarget1 || (resnow[1] + transing[1]) < transtarget1 || (resnow[2] + transing[2]) < transtarget1 || (resnow[3] + transing[3]) < transtarget2) {
				if (comm[0] > 0) {
					balance = [0,0,0,0]
					balance[0] = ((transtarget1 - (resnow[0] + transing[0])) > 0) ? (transtarget1 - (resnow[0] + transing[0])) : 0
					balance[1] = ((transtarget1 - (resnow[1] + transing[1])) > 0) ? (transtarget1 - (resnow[1] + transing[1])) : 0
					balance[2] = ((transtarget1 - (resnow[2] + transing[2])) > 0) ? (transtarget1 - (resnow[2] + transing[2])) : 0
					balance[3] = ((transtarget2 - (resnow[3] + transing[3])) > 0) ? (transtarget2 - (resnow[3] + transing[3])) : 0
					
					baalaa = getTranAmount(balance, resource)
					autoTranRequire(tranTask, baalaa, vi, theid)
				}
				else {
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_autoTransTime")
					window.location.reload()
				}
			}
			else {
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_autoTransTime")
				window.location.reload()
			}
		}
	});
}

	
	function startDemonow(vi, demotask){//"7_" + theID +"_" + crtlevel + "_" + currentID() + "_" +theBuild
		GM_log("come into startDemonow at "+getvillagefromdid(vi) +", to demolish "+demotask[4])
		var myower = window.clearInterval(myower)
		var turl = "http://" + window.location.hostname + "/build.php?newdid=" + vi
		demodate = "&gid=15&a=" + vi + "&abriss=" + demotask[1]
		dataa = encodeURI(demodate)
		GM_xmlhttpRequest({
			method: 'POST',
			url: turl,
			headers: {
				'User-Agent': 'Mozilla/4.0 (compatible) Greasemonkey',
				'Accept': 'application/atom+xml,application/xml,text/xml',
				'Content-type': 'application/x-www-form-urlencoded'
			},
			data: dataa,
			onload: function(response){
				GM_log("startDemonow Require callback here")
				var auDoc = document.implementation.createDocument("", "", null);
				var auElem = document.createElement('div');
				auElem.innerHTML = response.responseText;
				auDoc.appendChild(auElem);
				
				var newdemoTask = new Array();
				if (parseInt(demotask[2]) > 1) {
					newdemoTask[0] = demotask[0]
					newdemoTask[1] = demotask[1]
					newdemoTask[2] = (parseInt(demotask[2])-1).toString()
					newdemoTask[3] = demotask[3]
					newdemoTask[4] = demotask[4]
					deleteTaskFromCookie(vi, demotask, newdemoTask)
					
					var ddg = new Date();
					gettime = auDoc.getElementById("demolish").innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
					demot = gettime.toString().split(":")
					endt = ddg.getTime() + Number(demot[0]) * 60 * 60 * 1000 + Number(demot[1]) * 60 * 1000 + Number(demot[2]) * 1000 + 10000;
					ddg.setTime(endt)
					GM_log("some demolish is doing, next demo start at " + ddg)
					GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_demolishTime", endt.toString());
				}
				else {
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_demolishTime");
					deleteTaskFromCookie(vi, demotask)
				}
				printMSG(TaskKind[7]+" "+demotask[4]+" "+ otherText[7]+"!")
				window.location.reload()
			},
		})
	}
	
	
	function getTranAmount(bala,resource){
		GM_log("come into getTranAmount(),bala=" + bala)
		resource[0] = parseInt(resource[0])
		resource[1] = parseInt(resource[1])
		resource[2] = parseInt(resource[2])
		resource[3] = parseInt(resource[3])
		bala[0] = (resource[0] >= bala[0]) ? bala[0] : resource[0]
		bala[1] = (resource[1] >= bala[1]) ? bala[1] : resource[1]
		bala[2] = (resource[2] >= bala[2]) ? bala[2] : resource[2]
		bala[3] = (resource[3] >= bala[3]) ? bala[3] : resource[3]
		all = bala[0] + bala[1] + bala[2] + bala[3]
		GM_log("after condident resource , baba =" + bala)
		

		if (all < comm[0] * comm[1]) {
			return bala
		}
		else {
			balaa = [0, 0, 0, 0]
			maxer = Math.max(bala[0], bala[1], bala[2], bala[3])//1st maxer
			if (maxer >= comm[0] * comm[1]) {
				for (i = 0; i < 4; i++) {
					if (bala[i] == maxer) {
						balaa[i] = comm[0] * comm[1];
						break;
					}
				}
				return balaa
			}
			else {
				for (i = 0; i < 4; i++) {
					if (bala[i] == maxer) {
						balaa[i] = bala[i];
						bala[i] = 0;
						remain = comm[0] * comm[1] - balaa[i]
						break;
					}
				}
				maxer = Math.max(bala[0], bala[1], bala[2], bala[3])//2th maxer
				if (maxer >= remain) {
					for (j = 0; j < 4; j++) {
						if (bala[j] == maxer) {
							balaa[j] = remain;
							break;
						}
					}
					return balaa
				}
				else {
					for (j = 0; j < 4; j++) {
						if (bala[j] = maxer) {
							balaa[j] = bala[j];
							bala[j] = 0;
							remain = remain - balaa[j]
							break;
						}
					}
					maxer = Math.max(bala[0], bala[1], bala[2], bala[3])//3th maxer
					if (maxer >= remain) {
						for (k = 0; k < 4; k++) {
							if (bala[k] == maxer) {
								balaa[k] = remain;
								break;
							}
						}
						return balaa
					}
					else {
						for (k = 0; k < 4; k++) {
							if (bala[k] == maxer) {
								balaa[k] = bala[k];
								bala[k] = 0;
								remain = remain - balaa[k];
								break;
							}
						}
						maxer = Math.max(bala[0], bala[1], bala[2], bala[3])
						for (l = 0; l < 4; l++) {
							if (bala[l] == maxer) {
								balaa[l] = remain;
								break;
							}
						}
						return balaa
					}
				}
			}
		}
	}
	
	
	function getRequireData(tranTask, resArray,vi,id){
		GM_log("come into getRequireData() " + resArray)
		var myower = window.clearInterval(myower)
		var param = "&id=" + id + "&r1=" + resArray[0] + "&r2=" + resArray[1] + "&r3=" + resArray[2] + "&r4=" + resArray[3] + "&dname=&x=" + getXfromCoord(tranTask[3]) + "&y=" + getYfromCoord(tranTask[3]);
		GM_log("param=   " + param)
		data = encodeURI(param);
		url = "http://" + window.location.hostname + "/build.php" + "?newdid=" + vi
		var getTranData = new XMLHttpRequest();
		getTranData.open('POST', url, false);
		getTranData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		getTranData.setRequestHeader("Content-length", data.length);
		getTranData.setRequestHeader("Connection", "close");
		getTranData.onreadystatechange = callback;
		getTranData.send(data);
		function callback(){
			if (getTranData.readyState == 4) {
				if (getTranData.status == 200) {
					GM_log("HTTPRequire No1 ok!")

					var abDoc = document.implementation.createDocument("", "", null);
					var abElem = document.createElement('DIV');
					abElem.innerHTML = getTranData.responseText;
					abDoc.appendChild(abElem);
				
					var aR = new Array()
					sid=""
					a=""
					sz=""
					kid=""
					
					var input = abDoc.getElementsByTagName("input")
					for (var m = 0; m < input.length; m++) {
						GM_log(input[m].value)
						if (input[m].getAttribute("name") == "id") {
							sid = input[m].getAttribute("value");
						}
						else 
							if (input[m].getAttribute("name") == "a") {
								a = input[m].getAttribute("value");
							}
							else 
								if (input[m].getAttribute("name") == "sz") {
									sz = input[m].getAttribute("value");
								}
								else 
									if (input[m].getAttribute("name") == "kid") {
										kid = input[m].getAttribute("value");
									}
									else 
										if (input[m].getAttribute("name") == "r1") {
											aR[0] = input[m].getAttribute("value");
										}
										else 
											if (input[m].getAttribute("name") == "r2") {
												aR[1] = input[m].getAttribute("value");
											}
											else 
												if (input[m].getAttribute("name") == "r3") {
													aR[2] = input[m].getAttribute("value");
												}
												else 
													if (input[m].getAttribute("name") == "r4") {
														aR[3] = input[m].getAttribute("value");
													}
					}
					var paramm = "id=" + sid + "&a=" + a + "&sz=" + sz + "&kid=" + kid + "&r1=" + aR[0] + "&r2=" + aR[1] + "&r3=" + aR[2] + "&r4=" + aR[3];
					GM_log("paramm=" + paramm)
					
					return paramm
				}
			}
		}
		return callback()
	}
	
	
	function autoTranRequire(tranTask, resArray,vi,id){
		GM_log("come into autoTranRequire(), the resArray=" + resArray)
		var myower = window.clearInterval(myower)
		url = "http://" + window.location.hostname + "/build.php" + "?newdid=" + vi
		dataa = encodeURI(getRequireData(tranTask, resArray,vi,id))
		GM_xmlhttpRequest({
			method: 'POST',
			url: url,
			headers: {
				'User-Agent': 'Mozilla/4.0 (compatible) Greasemonkey',
				'Accept': 'application/atom+xml,application/xml,text/xml',
				'Content-type': 'application/x-www-form-urlencoded'
			},
			data: dataa,
			onload: function(response){
				GM_log("autoTranRequire Require callback here")
				var auDoc = document.implementation.createDocument("", "", null);
				var auElem = document.createElement('div');
				auElem.innerHTML = response.responseText;
				auDoc.appendChild(auElem);
				
				var ma = "0"
				var transing = [0, 0, 0, 0]
				var Transtime = 1500000000000;
				var reg111=gametext[10]+gametext[7]//to
				var gugagaa = new Date()
				var alltranTo = auDoc.evaluate('//table//a[contains(@href,"php?d=' + tranTask[3] + '")]', auElem, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
				if (alltranTo.snapshotLength > 0) {
					for (var i = 0; i < alltranTo.snapshotLength; i++) {
						if (alltranTo.snapshotItem(i).innerHTML.indexOf(reg111) != -1) {
							var ma = "1"
							ress = alltranTo.snapshotItem(i).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/>\d{1,}(?![:(\d:)])/g)
							transing[0] += parseInt(ress[0].split(">")[1])
							transing[1] += parseInt(ress[1].split(">")[1])
							transing[2] += parseInt(ress[2].split(">")[1])
							transing[3] += parseInt(ress[3].split(">")[1])
							
							resttt = alltranTo.snapshotItem(i).parentNode.parentNode.parentNode.parentNode.innerHTML.match(/\d{1,2}:\d{2}:\d{2}/)
							restttttt = resttt.toString().split(":")
							gobacktime = gugagaa.getTime() + Number(restttttt[0])*60*60*1000 + Number(restttttt[1]) *60*1000 + Number(restttttt[2])*1000;
							Transtime = Math.min(Transtime, gobacktime)
						}
					}
					if (ma == "0") {
						GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_TraningTime", "1500000000000")
					}
					lastTrantime = (Transtime == 1500000000000) ? 1500000000000 : Transtime + 5000
					var yyyu = new Date()
					yyyu.setTime(lastTrantime)
					
					GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_TraningTime", lastTrantime.toString())
					GM_log("the traning will arrive after " + lastTrantime + ", at " + yyyu)
					GM_setValue(currentServer() + "_" + getuid() + "_" + tranTask[2] + "_ResourceTraning", transing.join("/"))
					GM_log("all resources on transporting are " + transing.join("/"))
				}
				else {
					GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_TraningTime", "1500000000000")
				}
				
				okk=taskoftext[8].big()+"<br /><br />"+gametext[12]+" "+getvillagefromdid(vi)+" "+gametext[6]+" "+getvillagefromdid(tranTask[2])+"<br /><br />"+taskoftext[11]+"!"
				printMSG(okk) 
				switch (tranTask[1]){
				
                  case "0":
                  	GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_autoTransTime")
                  break;
                  
                  case "1":
                    var saspa=new Date();
                    nextTime=saspa.getTime()+3600000;
                    GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_to_" + tranTask[3] + "_autoTransTime",nextTime.toString())
                  break;
                }
				window.location.replace(url)
			}
		})
	}


	function showTaskList(){
		GM_log("come into showTaskList()")
		tasks = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", "false")
		if (tasks != "false") {
			aTable = createTaskListTable()
			var tlWrapper = document.createElement("div");
			tlWrapper.id = "tasklisttable_wrapper";
			tlWrapper.appendChild(aTable);
			
			var formCoords = getOption("TASKLIST_POSITION", "200px_900px");
			formCoords = formCoords.split("_");
			tlWrapper.style.top = formCoords[0];
			tlWrapper.style.left = formCoords[1];
			
			document.body.appendChild(tlWrapper);
			makeDraggable($("tasklisttable"));
		}
	}

	
	function createTaskListTable(){
		taskss = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask", "false")
		if (taskss != "false") {
			tasks = taskss.split("|")
			var taskListTable = document.createElement("table");
			taskListTable.id = "tasklisttable";
			taskListTable.border = "0"
			taskListTable.innerHTML += "<caption>" + gametext[7].big() + ":  " + currentVillageName().big() + "&#160;&#160;&#160;" + taskoftext[12].big() + "</caption>"
			taskListTable.innerHTML += "<tr><th colspan='2'>" + addTaskText[12] + "</th><th>" + addTaskText[11] + "</th><th>" + addTaskText[10] + "</th></tr>"
			taskListTable.innerHTML += "<tr><td colspan='4'><hr /></td></tr>"
			for (i in tasks) {
				thisTask = tasks[i].split("_");
				aTr = document.createElement("tr");
				taskListTable.appendChild(aTr);
				
				aTd1 = document.createElement("td");
				aTd1.width = "18px"
				if (i == 0) {
					aTd1.innerHTML = "&#160;"
				}
				else 
					if (i > 0) {
						taskup = document.createElement("a");
						taskup.href = "#"
						taskup.title = addTaskText[8]
						nimg = document.createElement("img");
						nimg.setAttribute("src", moveupBtn);
						taskup.appendChild(nimg);
						aTd1.appendChild(taskup);
						taskup.addEventListener('click', moveTask(currentID(), i, -1), false);
					}
				aTr.appendChild(aTd1);
				
				aTd2 = document.createElement("td");
				aTd2.width = "28px"
				if (i < tasks.length - 1) {
					taskdown = document.createElement("a");
					taskdown.href = "#"
					taskdown.title = addTaskText[9] 
					mimg = document.createElement("img")
					mimg.setAttribute("src", movedownBtn);
					taskdown.appendChild(mimg);
					aTd2.appendChild(taskdown);
					taskdown.addEventListener('click', moveTask(currentID(), i, 1), false);
				}
				else 
					if (i == tasks.length - 1) {
						aTd2.innerHTML = "&#160;"
					}
				aTr.appendChild(aTd2);
				
				
				aTd3 = document.createElement("td");
				taskStr = "";
				switch (thisTask[0]) {
					case "0"://0_id_level_time_name
						if (thisTask[1] < 19) {
							taskStr = TaskKind[0] +"&#160;"+ thisTask[4] + "&#160;&#160;" + gametext[2] + ":" + thisTask[1] + "&#160;&#160;" + addTaskText[4] + ":" + gametext[0] + thisTask[2]
						}
						else 
							if (thisTask[1] > 18 && thisTask[1] < 42) {
								taskStr = TaskKind[0] +"&#160;"+ thisTask[4] + "&#160;&#160;" + gametext[2] + ":" + thisTask[1] + "&#160;&#160;" + addTaskText[4] + ":" + gametext[0] + thisTask[2]
							}
							else {
								taskStr = taskoftext[2]
							}
						break;
					case "1"://1_id_level_gid_time_name
						
						taskStr = TaskKind[1] +"&#160;" +allbuildwithid[parseInt(thisTask[3])] + "&#160;&#160;" + gametext[2] + ":" + thisTask[1] + "&#160;&#160;" + addTaskText[4] + ":" + gametext[0] + thisTask[2]
						break;
					case "5":
						model = (thisTask[1] == "0") ? addTaskText[6] : addTaskText[7];
						taskStr = taskoftext[8] + " " + gametext[6] + " " + getvillagefromdid(thisTask[2]) + "&#160;&#160;" + addTaskText[5] + ":" + model
						break;
					case "7":	//"7_" + theID +"_" + crtlevel + "_" + currentID() + "_" +theBuild
						taskStr=TaskKind[7]+" "+thisTask[4]+"&#160;&#160;&#160;&#160;"+gametext[12]+thisTask[2]+gametext[17]+"&#160;&#160;"+gametext[6]+"0"+gametext[17]
						break;
				}
				aTd3.innerHTML = taskStr
				aTr.appendChild(aTd3);
				
				aTd4 = document.createElement("td");
				aTd4.width = "28px"
				aTd4.align="right"
				
				deleteTaskk = document.createElement("a");
				deleteTaskk.setAttribute("title", addTaskText[10]);
				deleteTaskk.href = "#"
				limg = document.createElement("img")
				limg.setAttribute("src", deleteBtn);
				deleteTaskk.appendChild(limg);
				deleteTaskk.addEventListener("click", deleteTaskCookie(i), false);
				aTd4.appendChild(deleteTaskk);
				aTr.appendChild(aTd4);
			}
			aTr6 = document.createElement("tr");
			aTd6 = document.createElement("td");
			aTd6.setAttribute("colspan", "4");
			aTd6.innerHTML="<hr />"
			aTr6.appendChild(aTd6);
			taskListTable.appendChild(aTr6)

			aTr5 = document.createElement("tr");
			aTd5 = document.createElement("td");
			aTd5.setAttribute("colspan", "4");
			deleteAllTask = document.createElement("a");
			deleteAllTask.href = "#"
			deleteAllTask.title = addTaskText[13]
			deleteAllTask.innerHTML = addTaskText[13]
			aTd5.appendChild(deleteAllTask);
			aTr5.appendChild(aTd5);
			taskListTable.appendChild(aTr5)
			deleteAllTask.addEventListener('click', deleteAllTasks, true);
		}
		return taskListTable
	}
	
	function deleteTaskCookie(j){
		return function(){
			taskss = GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask");
			thisTask = taskss.split("|")[j].split("_")
			switch (thisTask[0]) {
				
				case "0":
					if (thisTask[1] < 42) {
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_ResourceUpdataTime")
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_BuildingUpdataTime")
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_UpdataTime")
					}
					else {//autoResource
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource");
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_CorpRemain");
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_minLevelId");
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_minLevelCropId");
					}
					break;
					
				case "1"://new build
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_BuildingUpdataTime")
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_UpdataTime")
					break;
					
				case "5"://auto transport
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_to_" + thisTask[3] + "_TraningTime")
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_to_" + thisTask[3] + "_autoTransTime")
					auTranTo=GM_getValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo")
					auTrans=auTranTo.split("|")
					if (auTrans.length > 1) {
						for (a in auTrans) {
							if (auTrans[a] == thisTask[2]) {
								auTrans.splice(a, 1)
								break;
							}
						}
						GM_setValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo",auTrans.join("|"))
					}
					else {
						GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo")
					}
					break;
					
				case "7"://demolish
					GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_demolishTime");
					break;
					
			}
			deleteTaskFromCookie(currentID(), thisTask)
		}
	}




	function deleteAllTasks(){
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_waitTask")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_BuildingUpdataTime")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_ResourceUpdataTime")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_UpdataTime")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTime")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_TraningTime")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoTransTo")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_autoResource")
		GM_deleteValue(currentServer() + "_" + getuid() + "_" + currentID() + "_demolishTime")
		document.body.removeChild($("tasklisttable_wrapper"))
	}
	
	function addtaskbefore(vi, gid, ki){
		//ki="0" is Romans autoResource, ki="2" is other race autoResource
		thebuildid = getbuildfromdorf2(vi, gid)
		addtask = "0_" + thebuildid + "_000000000"
		newTaskstring = addtask + "|" + GM_getValue(currentServer() + "_" + getuid() + "_" + vi + "_waitTask");
		GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_waitTask", newTaskstring);
		switch (ki) {
			case "0":
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_BuildingUpdataTime");
				break;
			case "2":
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + vi + "_UpdataTime");
				break;
		}
		window.location.reload();
	}
	
	
	function getbuildfromdorf2(vil, gid){
		var turl = "http://" + window.location.hostname + "/dorf2.php?newdid=" + vil
		var getsomeid = new XMLHttpRequest();
		getsomeid.open('GET', turl, false);
		getsomeid.onreadystatechange = callback;
		getsomeid.send(null);
		function callback(){
			if (getsomeid.readyState == 4) {
				if (getsomeid.status == 200) {
					GM_log("getbuildfromdorf2_callback is here")
					var aDoc = document.implementation.createDocument("", "", null);
					var aElem = document.createElement('DIV');
					aElem.innerHTML = getsomeid.responseText;
					aDoc.appendChild(aElem);
					
					var thebuild = aDoc.evaluate('id("map2")//area[contains(@title,"' + allbuildwithid[gid] + '")]', aElem, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
					level = parseInt(thebuild.singleNodeValue.title.split(" ")[2]) + 1
					return thebuild.singleNodeValue.href.split("id=")[1] + "_" + level.toString();
				}
			}
		}
		return callback()
	}
	
	
	
	function getAutoResourceId(vi){
		corpremain = GM_getValue(currentServer() + "_" + getuid() + "_" + vi + "_CorpRemain")
		minlevelid = GM_getValue(currentServer() + "_" + getuid() + "_" + vi + "_minLevelId")
		minlevelcropid = GM_getValue(currentServer() + "_" + getuid() + "_" + vi + "_minLevelCropId")
		GM_log("come into getAutoResourceId(vi) and corpremain=" + corpremain)
		if (corpremain < 20) {
			GM_log("because of corpremain<20, return id is " + minlevelcropid)
			return minlevelcropid
		}
		else {
			GM_log("because of corpremain>=20, return id is " + minlevelid)
			return minlevelid
		}
	}
	
	
	function deleteTaskFromCookie(Vii, Taa,newTa){
		GM_log("come into deleteTaskFromCookie(Vii, Taa)")
		taskcook = GM_getValue(currentServer() + "_" + getuid() + "_" + Vii + "_waitTask")
		tasks = taskcook.split("|")
		taaa = Taa.join("_")
		for (x in tasks) {
			if (tasks[x] == taaa) {
				if (newTa) {
					newTa=newTa.join("_")
					tasks.splice(x, 1, newTa)
					break;
				}
				else{
					tasks.splice(x, 1)
					break;					
				}
			}
		}
		if (tasks.length > 0) {
			newCook = tasks.join("|")
			GM_setValue(currentServer() + "_" + getuid() + "_" + Vii + "_waitTask", newCook)
			GM_log("ok,i delete a task")
			if ($("tasklisttable_wrapper")) {
				document.body.removeChild($("tasklisttable_wrapper"))
			}
			showTaskList()
		}
		else {
			GM_deleteValue(currentServer() + "_" + getuid() + "_" + Vii + "_waitTask")
			if (GM_getValue(currentServer() + "_" + getuid() + "_" + Vii + "_ResourceUpdataTime", "flase") != "false") 
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + Vii + "_ResourceUpdataTime")
			if (GM_getValue(currentServer() + "_" + getuid() + "_" + Vii + "_BuildingUpdataTime", "flase") != "false") 
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + Vii + "_BuildingUpdataTime")
			if (GM_getValue(currentServer() + "_" + getuid() + "_" + Vii + "_UpdataTime", "flase") != "false") 
				GM_deleteValue(currentServer() + "_" + getuid() + "_" + Vii + "_UpdataTime")
			GM_log("ok I delete the whole cookie")
			if ($("tasklisttable_wrapper")) {
				document.body.removeChild($("tasklisttable_wrapper"))
			}
			showTaskList()
		}
	}
	
	
	function moveTask(vi, i, updown){
		return function(){
			updown=parseInt(updown)
			i=parseInt(i)
			var ubC = GM_getValue(currentServer() + "_" + getuid() + "_" + vi + "_waitTask");
			var arrUbC = ubC.split("|");
			var tmpUb = arrUbC[i + updown];
			arrUbC[i + updown] = arrUbC[i];
			arrUbC[i] = tmpUb;
			ubC = arrUbC.join("|");
			GM_setValue(currentServer() + "_" + getuid() + "_" + vi + "_waitTask", ubC)
			document.body.removeChild($("tasklisttable_wrapper"))
			showTaskList()
		}
	}







	ccclock = 0;
	function eachTimedo(){
		ccclock = ccclock + 6000
		if (ccclock > 180000) {
			window.location.reload()
		}
		
		var now = new Date();
		nowmillse = now.getTime();
		
		for (v in getAllVillageNewdids()) {
			whatever = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_waitTask", "false")
			if (whatever != "false") {
				allTasks = whatever.split("|")
				allTran = new Array()
				TranT = new Array()
				TraningT = new Array()
				for (nnn in allTasks) {
					thisTask = allTasks[nnn].split("_")
					if (thisTask[0] == "5") {
						ll = allTran.push(thisTask)
					}
				}
				if (allTran.length > 0) {
					for (i in allTran) {
						TranT[i] = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_to_" + allTran[i][3] + "_autoTransTime", "1500000000000");
						TraningT[i] = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_to_" + allTran[i][3] + "_TraningTime", "1500000000000")
						
						if ((parseInt(TranT[i]) - nowmillse) < 1000) {
							startTrannow(getAllVillageNewdids()[v], allTran[i])
						}
						if ((parseInt(TraningT[i]) - nowmillse) < 1000) {
							ki = fleshTraning(getAllVillageNewdids()[v], allTran[i])
							GM_log("return from Fleshtraning is " + ki)
						}
					}
				}
				
				resT = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_ResourceUpdataTime", "false");
				buiT = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_BuildingUpdataTime", "false");
				upT = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_UpdataTime", "false");
				DemoT = GM_getValue(currentServer() + "_" + getuid() + "_" + getAllVillageNewdids()[v] + "_demolishTime", "false");
				if (resT != "false") {
					remainTime1 = parseInt(resT) - nowmillse
					if (remainTime1 < 1000) {
						startBuildnow(getAllVillageNewdids()[v], "0")
						break;
					}
				}
				if (buiT != "false") {
					remainTime2 = parseInt(buiT) - nowmillse
					if (remainTime2 < 1000) {
						startBuildnow(getAllVillageNewdids()[v], "1")
						break;
					}
				}
				if (upT != "false") {
					remainTime3 = parseInt(upT) - nowmillse
					if (remainTime3 < 1000) {
						startBuildnow(getAllVillageNewdids()[v], "2")
						break;
					}
				}
				if (DemoT != "false") {
					remainTime4 = parseInt(DemoT) - nowmillse;
					for (lk in allTasks) {
						mytask = allTasks[lk].split("_");
						if (mytask[0] == "7" && remainTime4 < 1000) {
							startDemonow(getAllVillageNewdids()[v], mytask);
							break;
						}
					}
				}
			}
		}
	}

	
	
	
	function cleartime(){
		ccclock = 0;
	}
	
	/****************************************main function start***********************************************/


	showTaskList()
	getMainVillageid()
	getResourceCap()
	
	if(document.getElementsByTagName("h1")[0].innerHTML.split(" ")[0]==allbuildwithid[15]&&document.getElementsByTagName("h1")[0].innerHTML.split(" ")[2]>9&&(!document.getElementById("demolish"))){
		createDemolishlnk()
	}
	
	if (window.location.href.indexOf("build") != -1 & window.location.href.match(/[^gd]id/) != null & document.getElementsByTagName("h1")[0].innerHTML.split(" ")[2] != null & window.location.href.indexOf("&t=") == -1) {
		createbuildlink()
	}
	
	if(document.getElementsByTagName("h1")[0].innerHTML==gametext[15]){
		createNewbuildLnk()
	}
	
	if (window.location.href.indexOf("dorf1") != -1) {
		createAutoResLink()
	}
	
	if (document.getElementsByTagName("h1")[0].innerHTML.split(" ")[0] == allbuildwithid[17] & window.location.href.indexOf("t=") == -1) {
		createAutoTransBtn()
	}
	
	window.addEventListener("keydown", cleartime, false)
	window.addEventListener("mousemove", cleartime, false)
	
	myower = setInterval(eachTimedo, 6000)   
	
//mybar.innerHTML=cropLimitOption()