// ==UserScript==
// @name 			Erweiterte Dorfinfos
// @amespace		none
// @description	Zeigt Infos aus Berichten direkt im Infopopup auf der Karte.
// @version		2.0.1 (2009-06-15 22:43)
// @author 		Simon Hilz, realneode, Heinzelmaenchen, Peety
// @include 		http://*.*staemme.*/game.php?*village=*&screen=map*
// @include 		http://*.*staemme.*/game.php?*village=*&screen=report&mode=all&view=*
// @include 		http://*.*staemme.*/game.php?*village=*&screen=report&mode=attack&view=*
// @include 		http://*.*staemme.*/game.php?*screen=info_village&id=*
// ==/UserScript==

var server = document.location.host.split('.')[0];
var akt_map = "mapOld";
var watch_map = false; 
var watch_map_timer;
if(document.body.innerHTML.match(/Uslogge/))	{
	var rohstoffe = ["Houz","Lehm","Isä"];
	var names = ["Houzfäuer", "Lehmgruebe", "Isemine", "Spicher", "Vrsteck", "Wall"];
	var ausdruck =[/Agrifer:/,/vom Vrteidiger/,/Vrteidiger:/,/Beute:/,/Zuestimmig/,/Spionage/]
	var bonusliste = [/Houzprod/,/Lehmprod/,/Iseprod/,/Rohstoffprod/,/Spicherkap/,/Kasärne/,/Stau/,/Wärkstatt/,/Bevöukerig/,/notinuse/];
} else {
	var rohstoffe = ["Holz","Lehm","Eisen"];	
	var names = ["Holzfäller", "Lehmgrube", "Eisenmine", "Speicher", "Versteck", "Wall"];
	var ausdruck =[/Angreifer:/,/des Verteidigers/,/Verteidiger:/,/Beute:/,/Zustimmung/,/Spionage/]
	var bonusliste = [/Holzprod/,/Lehmprod/,/Eisenprod/,/Rohstoffprod/,/Speicherkap/,/Kaserne/,/Stall/,/Werkstatt/,/Bevölkerung/,/notinuse/];
}
var grafik = ["spear","sword","axe","light","marcher","heavy"];
/* settings: Truppen,Ressis,Speer,Schwert,Axt,LKav,BB,SKav,Gebäude,Speed,Spieler-ID,Info */
var sets = (GM_getValue(server+"_settings", "1,1,1,0,1,1,0,0,1,0,0,1")).split(",");
var settings = new Array(11);
for(var i=0; i<=10; i++) { settings[i] = parseInt(sets[i],10);}
if (settings[10] > 0) { var player_id = settings[10];}
else { var player_id = false;}
settings[11] = parseInt(sets[11],10);
var show_ressis = new Boolean(settings[1]);

if(document.body.innerHTML.match(/input name=\"sid_refresh_password/)) {
	return;
}
else if(document.location.href.match (/screen=map/)) {
	var koor_start = document.body.innerHTML.match(/\((\d+\|\d+)\)/);
	scan_map();
	var map_container = getElementsByClassName("map_container")[0];
	var tds = map_container.getElementsByTagName("td");
	tds[1].addEventListener("click",function() {check_map_move(akt_map);}, true);
	tds[3].addEventListener("click",function() {check_map_move(akt_map);}, true);
	tds[(tds.length - 4)].addEventListener("click",function() {check_map_move(akt_map);}, true);
	tds[(tds.length - 2)].addEventListener("click",function() {check_map_move(akt_map);}, true);
	var insertpos = getElementsByClassName("map_container")[1];
	insertpos = insertpos.parentNode.parentNode;
	var main = getElementsByClassName("main")[0];
	var div = document.createElement("div");
	div.setAttribute("style","text-align:left; margin: 0px auto;");

	var hr = document.createElement("hr");			
	div.appendChild(hr);
	
	var table = document.createElement("table");
	table.setAttribute("id",'extended_dorfinfo_settings');
	table.setAttribute("class","small");
	table.setAttribute("style","display:none;");
	var p = document.createElement("p");
	p.setAttribute("class","small");
	p.setAttribute("align","center");
	p.setAttribute("style","font-size:88%;");

	var a = document.createElement("a");
	a.setAttribute("href","javascript:void(0);");
	a.addEventListener("click",function() {show_settings();}, false);
	a.appendChild(document.createTextNode("» Dorfinfo Optionen «"));
	p.appendChild(a);
	div.appendChild(p);

	var row = document.createElement("tr");
	var td = document.createElement("td");
	var check = document.createElement("input");
	check.setAttribute("type","checkbox");
	check.setAttribute("name","showtroups_0");
	check.checked = settings[0];
	check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
	td.appendChild(check);
	td.appendChild(document.createTextNode("Truppen anzeigen"));
	row.appendChild(td);
	table.appendChild(row);
	
	row = document.createElement("tr");
	td = document.createElement("td");
	check = document.createElement("input");
	check.setAttribute("type","checkbox");
	check.setAttribute("name","showressis_1");
	check.checked = settings[1];
	check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
	td.appendChild(check);
	td.appendChild(document.createTextNode("Rohstoffe anzeigen"));
	row.appendChild(td);
	table.appendChild(row);
	
	row = document.createElement("tr");
	td = document.createElement("td");
	td.setAttribute("style","text-indent:20px;");
	td.appendChild(document.createTextNode("Farmeinheiten (max. 4): "));
	br = document.createElement("br");
	td.appendChild(br);
	for(i=2; i<8; i++) {
		var obj = grafik[i-2];
		img = document.createElement("img");
		img.setAttribute("alt", "");
		img.setAttribute("src", "graphic/unit/unit_"+obj+".png");
		check = document.createElement("input");
		check.setAttribute("type", "Checkbox");
		check.setAttribute("name", "showunits_"+i);
		check.checked = settings[i];
		check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
		td.appendChild(check);	
		td.appendChild(img);
	}
	row.appendChild(td);
	table.appendChild(row);

	row = document.createElement("tr");
	td = document.createElement("td");
	check = document.createElement("input");
	check.setAttribute("type","checkbox");
	check.setAttribute("name","showwall_8");
	check.checked = settings[8];
	check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
	td.appendChild(check);
	td.appendChild(document.createTextNode("Gebäude und Zustimmung anzeigen"));
	row.appendChild(td);
	table.appendChild(row);
	
	row = document.createElement("tr");
	td = document.createElement("td");
	check = document.createElement("input");
	check.setAttribute("type","checkbox");
	check.setAttribute("name","speed_9");
	check.checked = settings[9];
	check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
	td.appendChild(check);
	td.appendChild(document.createTextNode("Geschwindigkeit 1,6-fach?"));
	row.appendChild(td);
	table.appendChild(row);
	
	row = document.createElement("tr");
	td = document.createElement("td");
	check = document.createElement("input");
	check.setAttribute("type","checkbox");
	check.setAttribute("name","showinfo_11");
	check.checked = settings[11];
	check.addEventListener("change",function() {edit_setting(this.name, this.checked);}, false);
	td.appendChild(check);
	td.appendChild(document.createTextNode("Hinweis bei älteren Berichten"));
	row.appendChild(td);
	table.appendChild(row);
	
	div.appendChild(table);
	hr = document.createElement("hr");			
	div.appendChild(hr);
	insertpos.appendChild(div);
}
else if((document.location.href.search(/&screen=report&mode=all&view=/) > -1)||(document.location.href.search(/.+&screen=report&mode=attack/) > -1)) {
	var report = readReport();
	if (report) {	
		report = report.split(",");
/* report: Holz, Lehm, Eisen, Holzmine , Lehmmine, Eisenmine, Speicher, Versteck, Wall, Dorf-ID, Datum, neuste Bericht-ID, (Zustimmung) */
		var report_id = document.location.href.split('=');
		var rep_id = parseInt(report_id[report_id.length-1]);
		var vil_id = report[9];
		if (report[0] == -1) {			// eigenes Dorf
			var old = GM_getValue(server+"_"+vil_id, false);
			if (old) {
				del_village(vil_id);
				show_meldung("eigenes Dorf, Dorfinfos gelöscht");
			}
			else {
				show_meldung("eigenes Dorf");
			}
		} 
		else {	
			var old = GM_getValue(server+"_"+vil_id, false);
			if (old) {
				var old_report = old.split(",");
				var old_rep_id = old_report[11];
			}
			else {
				var old_rep_id = 0;
			}
			if(old && (old_rep_id > 0)) {
				if(rep_id > old_rep_id) {		// aktueller Bericht ist neuer
					var marker = false;
					for (i=3;i<9;i++) {
						if (report[i] == -1) {
						/* alte Gebäudestufen behalten */
							report[i] = old_report[i]; 
							marker = true;
						}
					}
					report[11] = rep_id;
					GM_setValue(server + "_" + vil_id, ""+report);
					GM_setValue(server + "_truppen_" + vil_id, getTroups());
					if (marker) show_meldung("Dorfinfos teilweise aktualisiert");
					else  show_meldung("Dorfinfos aktualisiert");
				}
				else {
					if (rep_id == old_rep_id) show_meldung("Diese Dorfinfos wurden bereits eingelesen");
					else show_meldung("Dorfinfos in diesem Bericht sind veraltet");
				}
			}
			else {
				report[11] = rep_id;
				GM_setValue(server + "_" + vil_id, ""+report);
				GM_setValue(server + "_truppen_" + vil_id, getTroups());
				show_meldung("Dorfinfos eingetragen");
			}
		}
	}
} 
else if(document.location.href.match (/village=\d+&screen=info_village&id=/)) {
	if(document.body.innerHTML.match(/» Dorfübersicht/)) {
		if (player_id == false) {
			player_id = document.body.innerHTML.match(/screen=info_player&amp;id=(\d+)/)[1];
			edit_setting("playerid_10", player_id);
		}
	}
	addNewRow() ;
}


function addNewRow() { 
/* Tabelle ermitteln, in der später die neue Zeile eingefügt wird */ 
	var tab = document.evaluate('//table[@class="main"]/tbody/tr/td/table[@class="vis left"]/tbody',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(0); 
   
/* Die neuen HTML-Elemente erstellen */ 
	var new_row_0 = document.createElement("tr"); 
	var new_row_1 = document.createElement("tr"); 
	var new_row_2 = document.createElement("tr");
	var new_row_3 = document.createElement("tr");
	var new_cell_0 = document.createElement("td"); 
	var new_cell_1 = document.createElement("td"); 
	var new_cell_2 = document.createElement("td");
	var new_cell_3 = document.createElement("td");
	var new_Link = document.createElement("a"); 
	var new_Link2 = document.createElement("a");
  
/* Die Attribute der neuen HTML-Elemente setzen */ 
	new_row_1.id = "message_field";
	new_row_1.style.display = "none";
	
	new_row_3.id = "message_field";
	new_row_3.style.display = "none";
  
	new_cell_0.setAttribute("colspan","2");
  
	new_cell_1.setAttribute("colspan","2");
	new_cell_1.id = "message";
	new_cell_1.style.textAlign = "center";
	new_cell_1.style.color = "red";
	new_cell_1.style.fontSize = "1.4em";
	new_cell_1.style.fontWeight = "bold";
	new_cell_1.style.padding = "7px";
	
	new_cell_2.setAttribute("colspan","2");
	
	new_cell_3.setAttribute("colspan","2");
	new_cell_3.id = "message";
	new_cell_3.style.textAlign = "center";
	new_cell_3.style.color = "red";
	new_cell_3.style.fontSize = "1.4em";
	new_cell_3.style.fontWeight = "bold";
	new_cell_3.style.padding = "7px";
  
	new_Link.innerHTML = "»  Dorfinformationen löschen";  
	new_Link.href = "javascript: //do nothing";
	
	new_Link2.innerHTML = "»  Alle Dorfinformationen löschen";  
	new_Link2.href = "javascript: //do nothing";
	
/* Die Funktion per Eventhandler an den Link koppeln */ 
	new_Link.addEventListener('click', function() { 
		var id = location.href.split("id=")[1].replace(/\&.+/,""); 
		if(GM_getValue(server + "_" + id, false)) { 
			del_village(id);
			new_Link.innerHTML = "»  Dorfinformationen gelöscht";
		} 
		else { 
			new_Link.innerHTML = "»  keine Dorfinformationen vorhanden";
		} 
	}, false); 
		
	new_Link2.addEventListener('click', function() { 
		var liste = [];
		liste = GM_listValues();
		var sicher;
		sicher = window.confirm("Möchtest du wirklich alle Dorfinformationen dieser Welt löschen ?");
		if (sicher){
			var counter = 0
			for (var i=0; i<liste.length; i++){
				if (liste[i].split("_")[0] == server) {
					GM_deleteValue(liste[i]);
					counter++;
				}
			}
			new_Link2.innerHTML = "» "+counter+" Dorfinformationen gelöscht";
		}
		else{
			new_Link2.innerHTML = "»  Dorfinformationen nicht gelöscht";
		}
	}, false); 
   
/* Die Elemente in die Seite intergrieren */ 
	new_cell_0.appendChild(new_Link);
	new_cell_2.appendChild(new_Link2);
	new_row_0.appendChild(new_cell_0);
	new_row_1.appendChild(new_cell_1);
	new_row_2.appendChild(new_cell_2);
	new_row_3.appendChild(new_cell_3);
	tab.appendChild(new_row_0);
	tab.appendChild(new_row_1);
	tab.appendChild(new_row_2);
	tab.appendChild(new_row_3);
}


function show_meldung(msg) {
	var row = document.createElement("tr");
	var td1 = document.createElement("td");
	var td2 = document.createElement("td");
	td1.innerHTML = "Dorfinfo Meldung";
	td2.innerHTML = msg;
	row.appendChild(td1);
	row.appendChild(td2);
	
	if(document.body.innerHTML.match(/DS Report/)) { var spoo = 1;}
	else	{ var spoo = 0;}
	var tab = getElementsByClassName("vis")[1 + spoo].getElementsByTagName("tbody")[0].getElementsByTagName("tr")[1];
	tab.parentNode.insertBefore(row, tab);
}


function show_settings() {
	$('extended_dorfinfo_settings').setAttribute("style", "");
	a.removeEventListener("click",function(){show_settings();}, false);
	a.addEventListener("click",function(){hide_settings();}, false)
	a.innerHTML = "« Optionen verstecken »"
}


function hide_settings() {
	$('extended_dorfinfo_settings').setAttribute("style", "display:none;");
	a.removeEventListener("click",function(){hide_settings();}, false);
	a.addEventListener("click",function(){show_settings();}, false)
	a.innerHTML = "» Dorfinfo Optionen «";
}

	
function edit_setting(set, new_value) {
	if (set == "playerid_10") {
		settings[10] = new_value;
	} else {
		var wert = 1;
		if ((new_value == false) || (new_value == "false")) wert = 0;
		settings[set.split("_")[1]] = wert;
	}
	GM_setValue(server+"_settings", ""+settings);
}

	
function check_map_move(akt_map_loc) {
	var groesse = $('map').getElementsByTagName("tr").length;
	if(!watch_map){watch_map_timer = window.setInterval(check_map_move,500,akt_map); watch_map=true; return false;}
	if($(akt_map_loc).style.left == (groesse * 53) * (-1) + "px" || $(akt_map_loc).style.left == (groesse * 53) + "px" || $(akt_map_loc).style.top == (groesse * 38) * (-1) + "px" || $(akt_map_loc).style.top == (groesse * 38) + "px")
	{
		switch(akt_map_loc)
		{
			case "mapOld":
				akt_map = "mapNew";
			break;
			case "mapNew":
				akt_map = "mapOld";
			break;
		}
		scan_map();
		window.clearInterval(watch_map_timer);
		watch_map = false;
	}
}

	
function readReport() {
	var player = [1,1,1];
	var bericht = false;
	var beute_x = 0;
	/* handelt es sich um einen Bericht?  */
	for(var x = 0, h4 = document.getElementsByTagName("th"); x < h4.length; x++) {
		if(h4[x].innerHTML.search(ausdruck[2]) >-1) { 
			bericht = true;
		}
	/* Spieler-ID auslesen */
		if(bericht && (h4[x].innerHTML.match(/screen=info_player&amp;id=\d+">\w+</))) {
			player = h4[x].innerHTML.match(/screen=info_player&amp;id=(\d+)">(\w+)</); 
		}
	/* Beute */
		if(h4[x].innerHTML.search(/Beute:/) > -1) { 
			beute_x = x;
		}
	}
	
/* Dorf-ID auslesen */
	var hit = document.body.innerHTML.match(/info_village&amp;id=(\d+)/g);
	if (!hit)	{ return false; }
	var vilId = hit[1].split("=")[1];

	if (player[1] == player_id) {				// Prüfen ob Spieler selbst
		output = "-1,-1,-1,-1,-1,-1,-1,-1,-1,"+vilId+",0,0";
		return output;
	}
/* Bericht-ID auslesen */
	if(document.location.href.search(/&screen=report&mode=all/) > -1) {
		var berId = document.location.href.match(/&screen=report&mode=all&view=(\d+)/)[1];
	}
	else { 
		var berId = document.location.href.match(/&screen=report&mode=attack&view=(\d+)/)[1];
	}
/* Das Bericht-Table-Element ermitteln */
	var tab = document.evaluate('//table[@class="main"]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table[@class="vis"]/tbody',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(0);
/* Datum + Zeit auslesen */ 
	var date = tab.getElementsByTagName("tr")[1].getElementsByTagName("td")[1].innerHTML;

/* handelt es sich um einen Spähbericht oder Adelsbericht?  */
	var adel = false;
	var xx = 0;
	for(var x = 0, h4 = document.getElementsByTagName("h4"), spy = false; x < h4.length; x++) {
		if(h4[x].innerHTML.match(ausdruck[5])) {				// Spionage-Bericht
			spy = true; 
			xx = x;
			break;
		}
		if(bericht && (h4[x].innerHTML.search(ausdruck[1]) > -1)) {
			adel = true;
		}
	}
	if (adel) {
		var bericht1 = false;
		for(var x = 0, h4 = document.getElementsByTagName("th"); x < h4.length; x++) {
			if(h4[x].innerHTML.search(ausdruck[0])>-1) {
				bericht1 = true;
			}
		/* Angreifer-ID auslesen */
			if(bericht1 && (h4[x].innerHTML.match(/screen=info_player&amp;id=\d+">\w+</))) {
				var player1 = h4[x].innerHTML.match(/screen=info_player&amp;id=(\d+)">(\w+)</); 
				if (player1[1] == player_id) { 
					output = "-1,-1,-1,-1,-1,-1,-1,-1,-1,"+vilId+",0,"+berId+",25";
					return output;  	

				}
			}
		}
		output = "0,0,0,-1,-1,-1,-1,-1,-1,"+vilId+","+date+","+berId+",25";	// fremder Adelsbericht
		return output;  	
	}

	if (spy) 	{
	/* Das Table-Element ermitteln, in dem die erspähten Daten stehen */	
		var tab1 = h4[xx].nextSibling.nextSibling;
	/* Rohstoffe auslesen */
		var res = [];
		var html = tab1.getElementsByTagName("td")[0].innerHTML.replace(/<span class="grey">\.<\/span>/g, "");
		res[0] = (html.match(/holz\.png/)) ? html.split("title=\""+rohstoffe[0]+"\" alt=\"\">")[1].split(" <img")[0] : 0;
		res[1] = (html.match(/lehm\.png/)) ? html.split("title=\""+rohstoffe[1]+"\" alt=\"\">")[1].split(" <img")[0] : 0;
		res[2] = (html.match(/eisen\.png/)) ? html.split("title=\""+rohstoffe[2]+"\" alt=\"\">")[1].replace(/ /, "") : 0;

		if (!tab1.getElementsByTagName("td")[1]) {
			var output = res[0]+","+res[1]+","+res[2]+",-1,-1,-1,-1,-1,-1,"+vilId+","+date+","+berId; //  -1  damit Gebäudestufen nicht gelöscht werden
			output = zustimmung(output);
			return output;
		}
	/* Gebäude auslesen */
		var code = tab1.getElementsByTagName("td")[1].innerHTML;
		var buildings = [0,0,0,0,0,0];
		var marker = 0;
		for(var x = 0; x < names.length; x++) {
			if(code.match(names[x]))	{
				buildings[x] = code.split(names[x] + " <b>(Stufe ")[1].split(")</b>")[0];
				marker += buildings[x];
			}
		}
		if (marker == 0) {
		/* Gebäude konnten nicht ausgelesen werden */
			for(var x = 0; x < names.length; x++){
				buildings[x] = -1;  // Gebäudestufen aus altem Bericht behalten
			}
		}
		var output = res+","+buildings+","+vilId+","+date+","+berId;
		output = zustimmung(output);
		return output;
	} 
	else { 	/* (keine Spionage) */
		if(bericht){
			var beute = "0";
			if (beute_x > 0) {
				var res_beute = new Array(3);
				for(var beute_x = 0, h4 = document.getElementsByTagName("th"); beute_x < h4.length; beute_x++) {
					if(h4[beute_x].innerHTML.search(ausdruck[3]) > -1) {
						res_beute = h4[beute_x].nextSibling.nextSibling.nextSibling.nextSibling.innerHTML.match(/(\d+)\/(\d+)/);
					}
				}
				if (parseInt(res_beute [1]) == parseInt(res_beute[2])) {  // Wenn (Beute==Tragfähigkeit)  Res sind nicht leer
					beute = "-1";
				}
			}
		 	var output = "0,"+beute+",0,-1,-1,-1,-1,-1,-1,"+vilId+","+date+","+berId; //  -1  damit Gebäudestufen nicht gelöscht werden
			output = zustimmung(output);
			return output;
		}
		return false;
	} 
}


function zustimmung(output) {
	for(var x = 0, th = document.getElementsByTagName("th"), zs = false; x < th.length; x++) {
		if(th[x].innerHTML.match(ausdruck[4])) { 
			zs = true;
			var ZS = th[x].nextSibling.nextSibling.getElementsByTagName("b")[1].innerHTML;
			break;
		}
	}
  	if(!zs) {
		return output;
	}
	var ZS = th[x].nextSibling.nextSibling.getElementsByTagName("b")[1].innerHTML;
	if (parseInt(ZS) <= 0) ZS = 25;
	output += "," + ZS; 
	return output;
}


function getTroups() {
/* Liest die Truppen aus einem Bericht aus */
	var units = [];
	var tab = document.evaluate('//table[@class="main"]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table[@class="vis"]/tbody/tr/td/table/tbody/tr/td/table[@class="vis"]/tbody',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(1);
		// inside troups
	var stand = [];
	if(tab) {
		stand = tab.getElementsByTagName("tr")[1].getElementsByTagName("td");
		var loose = tab.getElementsByTagName("tr")[2].getElementsByTagName("td");

		for(var x = 1; x < stand.length; x++) {
			var diff = stand[x].innerHTML-loose[x].innerHTML;
			units.push(diff);
		}
	}
		// outside troups
	var unitsa = [];
	var tab = document.evaluate('//table[@class="main"]/tbody/tr/td/table/tbody/tr/td/table/tbody/tr/td/table[@class="vis"]/tbody/tr/td/table/tbody/tr/td/table/tbody',document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null).snapshotItem(3); 
	if(tab) {
		var tds = tab.getElementsByTagName("td"); 
		for(var x = 0; x < tds.length; x++) 
			unitsa[x] = tds[x].innerHTML; 
	}
	return (units+";"+unitsa); 
}


function del_village(id) {
	GM_deleteValue(server + "_" + id); 
	GM_deleteValue(server + "_truppen_" + id); 
}


function trennzeichen(zahl) {
	zahl=Math.floor(zahl);
	var ausgabe = "";
	if (zahl>1000){
		ausgabe += Math.floor(zahl/1000);
		ausgabe += ".";
		if (zahl%1000<100) {
			if (zahl%1000<10) {
				ausgabe += "00" + zahl%1000;
			}
			else {
				ausgabe += "0" + zahl%1000;
			}
		}
		else {
			ausgabe += zahl%1000;
		}
	}
	else {
		ausgabe+=zahl;
	}
	return ausgabe;
}


function getElementsByClassName(classname, node) {
	if(!node) node = document.getElementsByTagName("body")[0];
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = node.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
	if(re.test(els[i].className))a.push(els[i]);
	return a;
}


function $(id) {
	var object = document.getElementById(id);
	return object;
}


function scan_map() {
	var cont_tb = $('info_content').getElementsByTagName("tbody")[0];
	remove_info(cont_tb);

	var doerfer = "";
	switch(getElementsByClassName("map").length) {
	case 1:
		map = getElementsByClassName("map")[0];
		break;
		
	case 2:
		map = getElementsByClassName("map")[1];
		break;
	}
	var tds = map.getElementsByTagName("td");
	for(var j = 0; j<tds.length;j++) {
		if(tds[j].getElementsByTagName('a').length == 1) {
			doerfer = doerfer + "_"+j+" - ";
			tds[j].getElementsByTagName("img")[0].setAttribute("id",j);
			tds[j].getElementsByTagName("img")[0].addEventListener("mouseover",function(e) {add_info_to_map(e.target.id,tds);}, false);	
		}	
	}
	doerfer = "";
}

	
function diffhour (last_att) {
	var att_time = last_att;
	var zeit_att = att_time.split(" ")[1];
	var h = zeit_att.split(":")[0];
	var i = zeit_att.split(":")[1];
	var d = att_time.split(".")[0];
	var m = att_time.split(".")[1];
	var j = att_time.split(".")[2];
	j = j.split(" ")[0];
	var att_date = new Date();
	
	att_date.setSeconds(0);
	att_date.setMinutes(i);
	att_date.setHours(h);
	att_date.setDate(d);   
	att_date.setMonth(m-1);
	att_date.setFullYear("20"+j);
	
	var now = new Date();
	var nd = "31";										
	nd = parseInt(now.getDate());							
	var att_h = att_date.getTime() / 1000 / 60 / 60;
	var now_h = now.getTime() / 1000 / 60 / 60;
	if ((d == 31) && (nd != "31")) att_h += (31-nd)*24 ;		
	var diff_h = now_h - att_h;
	return diff_h;
}


function remove_info(cont_tb) { 
	if($('last_att_units')) cont_tb.removeChild($('last_att_units'));
	if($('last_att_ressis')) cont_tb.removeChild($('last_att_ressis'));
	if($('next_att_units')) cont_tb.removeChild($('next_att_units'));
	if($('last_att_zustimmung')) cont_tb.removeChild($('last_att_zustimmung'));
	if($('last_att_wall')) cont_tb.removeChild($('last_att_wall'));
	if($('last_date')) cont_tb.removeChild($('last_date'));
}


function add_info_to_map(k,tds) {
	var cont_tb = $('info_content').getElementsByTagName("tbody")[0];
	remove_info(cont_tb);
	
	var trs = cont_tb.getElementsByTagName("tr");
	var hidden = 0;
	for(var j = 0; j < trs.length;j++) {
		if(trs[j].style.display == "none") hidden++;	
	}
	if ($('info_bonus_image')) {
		$('info_bonus_image').setAttribute("rowspan",(8 - (hidden -1)));
	}
	var map = getElementsByClassName("map")[0];
	var tds = map.getElementsByTagName("td");
	var link = tds[k].getElementsByTagName("a")[0];
	var akt_id = link.href.split("info_village&id=")[1];
	var koor_target = tds[k].innerHTML.match(/\((\d+\|\d+)\)/);
	var grau = tds[k].innerHTML.match(/, null, null, false,/);
	var report = GM_getValue(server+"_"+akt_id, false);
	if (report) {
/* report: Holz, Lehm, Eisen, Holzmine , Lehmmine, Eisenmine, Speicher, Versteck, Wall, Dorf-ID, Datum, neueste Bericht-ID, (Zustimmung) */
		var report = report.split(",");
		var ressis = [report[0], report[1], report[2]];
		var show_troups = Boolean(settings[0]);			
		show_ressis = Boolean(settings[1]);			
		var show_wall = Boolean(settings[8]);			
		var server_speed = Boolean(settings[9]);
		var show_info = Boolean(settings[11]);	
		var diff_h = diffhour(report[10]);
		var speed = 1.0; var speed2 = 1.0; 			//speed2 für Zustimmung
		if (server_speed) {
			speed = 1.6; speed2 = 1.6;
			if (server == "de30" || server == "de32") speed2 = 1.0;
		}

		var ResPerHour = [5,30,35,41,47,55,64,74,86,100,117,136,158,184,214,249,289,337,391,455,530,616,717,833,969,1127,1311,1525,1774,2063,2400];
		if (show_ressis) {
		/* Bonusdörfer ermitteln */
			var bonuswert = 0.0;
			var bonustyp = 9;
			var bonus = false;
			if (tds[k].innerHTML.match(/\/bonus\//)) {
				for (var i=0; i < bonusliste.length; i++) {
					if (tds[k].innerHTML.match(bonusliste[i])) {
						if (i < 5) {
							bonus = true;			// hat Einfluss auf die Ressi-Produktion
							bonustyp = i;
							bonuswert = tds[k].innerHTML.match(/(\w+)% [m,s][e,c]h/)[1];
							bonuswert = bonuswert/100;
						}
						break;
					}
				}
			}
		}

		/* Truppen */
		if (show_troups) {
			var truppen = ""+GM_getValue(server + "_truppen_" + akt_id, false);
			var truppenHeim = false;
			var truppenAus = false;
			if (truppen) 
			{
				truppen = truppen.split(";");
				truppenHeim = truppen[0];
				truppenAus = truppen[1];
			}
			if (truppenHeim) {
				truppenHeim = truppenHeim.split(",");
				row = document.createElement("tr");
				row.setAttribute("id",'last_att_units');
				td1 = document.createElement("td");
				td1.innerHTML = "Truppen: ";
				if (truppenAus) {
					truppenAus = truppenAus.split(",");
					td1.innerHTML = "<br>Truppen: <br><br>+ auswärts: ";
				}
				td2 = document.createElement("td");
				td2.setAttribute("valign","top");
				td2.setAttribute("colspan","2");

				if (truppenHeim.length == 12) {
					var einheiten = ["spear","sword","axe","archer","spy","light","marcher","heavy","ram","catapult","knight","snob"];
				}
				else if (truppenHeim.length == 11) {
					var einheiten = ["spear","sword","axe","archer","spy","light","marcher","heavy","ram","catapult","snob"];
				}
				else if (truppenHeim.length == 9) {
					var einheiten = ["spear","sword","axe","spy","light","heavy","ram","catapult","snob"];
				}

				var	code = "<tr class=\"center\">";
				var counter = 0;
				for (var i=0; i < truppenHeim.length; i++) {
					if ((truppenHeim[i] >0) || (truppenAus && (truppenAus[i] >0))) {
						counter++;
						code += "<td width=\"35\"><img src=\"/graphic/unit/unit_" + einheiten[i] + ".png\"></td>";
					}
				}
				
				if (counter >0) {
					code += "</tr><tr class=\"center\">";
				}
				for (var i=0; i < truppenHeim.length; i++) {
					if (parseInt(truppenHeim[i]) == 0) {
						if (truppenAus[i] >0) {
							code += "<td width=\"35\">" + ""+truppenHeim[i] + "</td>";
						}
					} else {
						code += "<td width=\"35\">" + ""+truppenHeim[i] + "</td>";
					}
				}
				if (counter == 0) {
					if (grau) code += "keine"
					else code += "keine bekannt"
				}
				code += "</tr>";
				if (truppenAus) {
					code += "<tr class=\"center\">";
					for (var i=0; i < truppenAus.length; i++)
					{
						if (parseInt(truppenAus[i]) == 0) {
							if (truppenHeim[i] >0) {
								code += "<td width=\"35\">" + ""+truppenAus[i] + "</td>";
							}
						} else {
							code += "<td width=\"35\">" + ""+truppenAus[i] + "</td>";
						}
					}
					code += "</tr>";
				}
				var table = document.createElement("table");
				table.setAttribute("class","vis");
				table.innerHTML = code;
				td2.appendChild(table);
				row.appendChild(td1);
				row.appendChild(td2);
				cont_tb.appendChild(row);
			}
		}
		
		
	/* Rohstoffe */
		var speicher = [0,1000,1229,1512,1859,2285,2810,3454,4247,5222,6420,7893,9705,11932,14670,18037,22177,27266,33523,41217,50675,62305,76604,94184,115798,142373,175047,215219,264611,325337,400000];
		var speicherstufe = parseInt(report[6]);
		var versteck = [0,150,200,267,356,474,632,843,1125,1500,2000];
		var versteckstufe = parseInt(report[7]);
		var maxres = speicher[speicherstufe] - versteck[versteckstufe] - (versteckstufe>0 && speicherstufe<30);
		if (bonustyp == 4) { 
			maxres += Math.floor(speicher[speicherstufe] * bonuswert);
		}
			
			var ressis1 = [1.0,1.0,1.0];  		// Res aus Bericht
			var graphic = ["holz","lehm","eisen"];  // angezeigte Res
			var tragen1 = [25,15,10,80,50,50]; 	// Beute tragen
			var duration1= [18,22,18,10,10,11]; 	// Dauer in min. pro Feld
			var ressis2 = [1.0,1.0,1.0];			// Res errechnet
			var graphicname = ["spear","axe","light","heavy"] // angezeigte Einheiten
			var tragen = [10,25,80,50];
			var duration = [18,18,10,11];

			var anzahl_werte = 0;
			for (var i=0; (i<6) && (anzahl_werte < 4); i++) {
				obj = grafik[i];
				if (settings[i+2] == 1) {
					duration[anzahl_werte] = duration1[i];
					tragen[anzahl_werte] = tragen1[i];
					graphicname[anzahl_werte] = grafik[i];
					anzahl_werte++;
				}
			}
		/*  Berechnen der Ressis zur aktuellen Zeit (mit Bonusdörfern) */
			var ausgabe = "";
			var unknown = (parseInt(ressis[1]) == -1);
			for (var i=0; i<=2; i++) {
				ressis1[i] = parseInt(ressis[i],10); 	//vorhandene Res
				if (maxres > 100) {					// Res-Berechnung ist möglich
						ressis2[i] += (diff_h * ResPerHour[report[i+3]] * speed); //berechnete Res
					if (bonus) {
						if ((bonustyp == i) || (bonustyp == 3)) {
							ressis2[i] += (ressis2[i] * bonuswert) // Bonus addieren
						}
					}
					ressis2[i] += ressis1[i];  		// vorhandene und berechnete addieren
					ausgabe += "<img src=\"/graphic/"+graphic[i]+".png\">";
					if (maxres <= ressis2[i]){		
						ausgabe += "<a style=\"color:#FF0000\">";
					}
					else if (0.8*maxres <=ressis2[i]) {
						ausgabe += "<a style=\"color:#EE8000\">";
					} 
					else if (bonus) {
						if ((bonustyp==i) || (bonustyp ==3)){
							ausgabe += "<a style=\"color:#005000\">";
						}
					}
					ressis2[i] = Math.min(maxres, Math.ceil(ressis2[i]));
					if (ressis2[i] >0) {
						ausgabe += trennzeichen(ressis2[i])+" ";
					}
					if ((0.8 * maxres <= ressis2[i]) || (bonustyp ==i) || (bonustyp ==3)) {
						ausgabe += "</a>";
					}
				}
				else {  							// keine Res-Berchnung möglich
					ausgabe += "<a style=\"color:#0000B0\"><img src=\"/graphic/"+graphic[i]+".png\" alt=\"\">";
					if (unknown) {
						ausgabe += "<b>?</b></a> ";
					}
					else{
						ausgabe += ressis1[i]+"</a> ";
					}
				}
			}
			
		if ((show_ressis)&&(speicherstufe!=0)) {   		// Rohstoffe anzeigen
			row = document.createElement("tr");
			row.setAttribute("id",'last_att_ressis');
			td1 = document.createElement("td");
			td1.innerHTML = "Rohstoffe: ";
			td2 = document.createElement("td");
			td2.setAttribute("colspan","2");
			td2.innerHTML = ausgabe;
			row.appendChild(td1);
			row.appendChild(td2);
			cont_tb.appendChild(row);
		}
		if(anzahl_werte > 0){						// Farmeinheiten anzeigen
			row = document.createElement("tr");
			row.setAttribute("id",'next_att_units');
			td1 = document.createElement("td");
			td1.innerHTML = "Farmeinheiten: ";
			td2 = document.createElement("td");
			td2.setAttribute("colspan","2");
			
		/* Berechnen der Ressis für die Laufzeit zum Zieldorf (mit Bonusdörfern) */
			var vstart = koor_start[1].split("|");		// Koordinaten Startdorf  und Zieldorf 
			var vtarget = koor_target[1].split("|");
			var fields  = laufzeitfaktor(vstart[0],vstart[1],vtarget[0],vtarget[1]);
			var bedarf  = [0,0,0,0]; 
			var bedarf1 = [0,0,0,0];
			var ressis3 = [1,1,1,1]; 				//Einheiten
			ausgabe = "" 
			for (var i=0; i < anzahl_werte; i++) {
				ressis3[i] = [0,0,0];				// Holz, Lehm, Eisen
				for (var j=0; j <=2; j++) {
					ressis3[i][j] = (fields * duration[i] * speed * ResPerHour[report[j+3]] /60.0);  // Felder mal Laufzeit/Feld mal Ressis/min
					if (bonus) { 
						if ((bonustyp == 3) || (bonuswert == j)) {		
							ressis3[i][j] =+ (ressis3[i][j] * bonuswert);
						}
					}
					bedarf[i] += Math.min(maxres,Math.ceil(ressis2[j]+ressis3[i][j]));
				}
				bedarf1[i]= Math.ceil(bedarf[i] / tragen[i]);
				ausgabe += " <img src=\"/graphic/unit/unit_"+graphicname[i]+".png\">";
				if (bedarf1[i] >0){
					ausgabe +=trennzeichen(bedarf1[i])+" ";
				}
				else {
					ausgabe += "<b>?</b> ";
				}

				}
			td2.innerHTML = ausgabe;
			row.appendChild(td1);
			row.appendChild(td2);
			cont_tb.appendChild(row);
		}
		
	/* Gebäude */
		if (show_wall) {
			row = document.createElement("tr");
			row.setAttribute("id",'last_att_wall');
			td1 = document.createElement("td");
			td1.innerHTML = "Gebäude: ";
			td2 = document.createElement("td");
			td2.setAttribute("colspan","2");
			var counter = 0;
			var ausgabe = "";
			if (speicherstufe > 0) {
				ausgabe = "<img src=\"/graphic/res.png\">";
				ausgabe += speicherstufe+" ";
				if (bonustyp == 4) {
					ausgabe += "<a style=\"color:#005000\">";
				}
				ausgabe += " ("+trennzeichen(maxres)+") ";
				if (bonustyp == 4) {
					ausgabe += "</a>";
				}
				if (versteckstufe > 0) {
					ausgabe += " <img src=\"/graphic/buildings/hide.png\">"+ versteckstufe;
				}
			} 
			else {
				for (var x=3; x<8; x++) {
					counter += parseInt(report[x]);
				}
			}
			if (counter == -5){
				ausgabe += "nicht bekannt";
			}
			if (report[8] != -1) {  
				ausgabe += " <img src=\"/graphic/buildings/wall.png\"> "+report[8];
			}
			if (report.length == 13) { 
				var zustimmung = parseInt(report[12]); 
				zustimmung += diff_h * speed2;					
				zustimmung = Math.min(Math.floor(zustimmung),100);
				ausgabe += " / Zustimmung " + zustimmung;  	
			}
			td2.innerHTML = ausgabe;
			row.appendChild(td1);
			row.appendChild(td2);
			cont_tb.appendChild(row);
		}
		if (show_info) {
			var alter = parseInt(diff_h/24);
			if (alter >= 2) {
				row = document.createElement("tr");
				row.setAttribute("id",'last_date');
				td1 = document.createElement("td");
				td1.innerHTML = "Info: ";
				td2 = document.createElement("td");
				td2.setAttribute("colspan","2");
				var ausgabe = "Bericht ist über";
				if (alter < 14)
					ausgabe += " <b>"+alter+"</b> Tage alt";
				else
					ausgabe += "<a style=\"color:#DD2200\"> <b>"+parseInt(alter/7)+" Wochen</b></a> alt!";
				td2.innerHTML = ausgabe;
				row.appendChild(td1);
				row.appendChild(td2);
				cont_tb.appendChild(row);
			}
		}
	}
}


function laufzeitfaktor(x1,y1,x2,y2) {
	var Ergebnis = (x1-x2)*(x1-x2);
	Ergebnis += (y1-y2)*(y1-y2);
	Ergebnis = Math.sqrt(Ergebnis);
	return Ergebnis;
}
