/* Poached from Fluffy88
	http://www.fluffy88.com/TW/op_gen.js
*/

function fnExecuteScript(){
try{
	/* ##############################################
	 Thanks to mods not getting off their asses,
	 I have implemented a block on players that
	 cheat, play dirty, take issues beyond the game,
	 attempt to maliciously ruin legitimate
	 Premium Accounts or knowingly let this happen.
	 ############################################## */
	function fnBlockUnAuthorizedScriptAccess(){
		if(typeof(window.game_data)=="undefined"){
			return;
		}
		
		var block_list = {
			"en49":[
				8493345,	// -Rawr-
				8509737,	// Rasmala
				8516841,	// civilized11
				8549690,	// GameOn29
				314479		// jackel148
			]
		};
		
		if(typeof(block_list[window.game_data.world])!="undefined"){
			if((block_list[window.game_data.world].indexOf(parseInt(window.game_data.player.id,10))>=0) ||
		   	(block_list[window.game_data.world].indexOf(parseInt(window.game_data.player.sitter_id,10))>=0)){
				throw("This Script is hosted on a private server.\nPlease locate the owner for discussion\nif you want access granted.");
			}
		}
	}
	fnBlockUnAuthorizedScriptAccess();
	/* ############################################## */


	var strScriptName="Op Planner";
	var strVersion="v1.4";
	
	var eleDoc = (window.frames.length > 0)?window.main.document:document;
	if(!eleDoc.URL.match(/screen\=info_player/i)){
	    throw('This script must be run from\nPlayer Profile Screen!');
	}

	function fnGenerateSequentialFakeScript(villas,trainSize){
		var scriptSource = "";
		scriptSource += "javascript:";
		scriptSource += "var config={victim:'miscellaneous',trainSize:"+trainSize+",units:{spy:1,ram:1},cookieID:'fake'};";
		scriptSource += "var targets='" + villas.join(" ") + "';";
		scriptSource += "if(targets.replace(/^\\s\\s*/,'').replace(/\\s\\s*$/,'')===''){throw('There are no Targets');}";
		scriptSource += "var coords=targets.split(' ');";
		scriptSource += "function escapeStr(text){var specials=['/','.',',','~','`','@','#','%','-','_','*','+','?','|','$','=',':','!','^','<','>','(',')','[',']','{','}','\\\\'];var sRE=new RegExp('(\\\\'+specials.join('|\\\\')+')','g');return text.replace(sRE,'\\\\$1');}";
		scriptSource += "function zeroPad(number,length){var n=number.toString();while(n.length<length){n='0'+n;}return n;}";
		scriptSource += "function fnWriteCookie(index){var cookie_date=new Date(2099,11,11);eleDoc.cookie=vWorld+'$'+config.victim+'$'+config.cookieID+'='+(index+1)+';expires='+cookie_date.toGMTString();}";
		scriptSource += "function fnAssignUnits(index,isManualReset){";
		scriptSource += "if((index<0)||(index>=coords.length)){index=0;if(eleDoc.fakeSequence==1){alert('cycle restarted');}}";
		scriptSource += "eleDoc.getElementById('fake_combo').selectedIndex=index;";
		scriptSource += "var villa=coords[index].split('|');";
		scriptSource += "if(!isManualReset&&(eleDoc.fakeSequence<config.trainSize)){eleDoc.fakeSequence++;}else{eleDoc.fakeSequence=(isManualReset?2:1);fnWriteCookie(isManualReset?index-1:index);}";
		scriptSource += "var eleForm=eleDoc.getElementById('units_form');";
		scriptSource += "eleForm.x.value=villa[0];";
		scriptSource += "eleForm.y.value=villa[1];";
		scriptSource += "var count;";
		scriptSource += "for(var unit in config.units){";
		scriptSource += "if(config.units.hasOwnProperty(unit)){";
		scriptSource += "if(typeof(eleForm[unit])!='undefined'){";
		scriptSource += "count=parseInt(eleForm[unit].nextSibling.nextSibling.innerHTML.match(/\\d+/),10);";
		scriptSource += "eleForm[unit].value=Math.min(config.units[unit],count);}}}}";
		scriptSource += "try{var eleDoc=(window.frames.length>0)?window.main.document:document;";
		scriptSource += "if(typeof(eleDoc.fakeSequence)=='undefined'){eleDoc.fakeSequence=1;}";
		scriptSource += "var scrape,vScreen=(scrape=eleDoc.URL.match(/\\&screen=(\\w+)/i))?scrape[1]:null;";
		scriptSource += "var vWorld=(scrape=eleDoc.URL.match(/\\/\\/(\\w+)\\./i))?scrape[1]:null;";
		scriptSource += "var village=eleDoc.getElementsByTagName('title')[0].innerHTML.match(/\\(\\d+\\|\\d+\\)/);";
		scriptSource += "if(vScreen=='place'){";
		scriptSource += "var index=0;";
		scriptSource += "var twCookie=eleDoc.cookie.match('[^|;]\s?'+escapeStr(vWorld+'$'+config.victim+'$'+config.cookieID+'=')+'([^;]*)[;|$]');";
		scriptSource += "if(twCookie){index=parseInt(twCookie[1],10);}";
		scriptSource += "if(!eleDoc.getElementById('fake_combo')){";
		scriptSource += "var eleInputs=eleDoc.getElementsByTagName('input');";
		scriptSource += "if(eleInputs){for(var ii=0;ii<eleInputs.length;ii++){";
		scriptSource += "if(eleInputs[ii].name=='support'){";
		scriptSource += "var optionList='';";
		scriptSource += "for(var jj=0;jj<coords.length;jj++){optionList+='<option>'+zeroPad(jj+1,4)+':'+coords[jj]+'</option>';}";
		scriptSource += "eleInputs[ii].parentNode.parentNode.innerHTML+='<TD rowspan=\"2\"><div id=\"fakes\"><table class=\"main\">";
		scriptSource += "<tr><td id=\"fake_content_value\"><span style=\"font-weight:bold\">Current Target:</span>";
		scriptSource += "<select id=\"fake_combo\" name=\"fake_combo\" size=\"1\" onchange=\"fnAssignUnits(this.selectedIndex,true);\">'+optionList+'</select>";
		scriptSource += "<span style=\"font-weight:100;font-style:italic;text-decoration:none;font-size:x-small;\">";
		scriptSource += "<a href=\"http://www.crosstrigger.com\" target=\"_blank\"> by dalesmckay</a></span></td></tr></table></div></TD>';break;}}}}";
		scriptSource += "fnAssignUnits(index,false);}else{throw('Run from the Rally point');}void(0);}catch(objErr){alert(objErr);}";

		return scriptSource;
	}

	function fnGetText(ele){return(typeof(ele.innerText)=="undefined"?ele.textContent:ele.innerText);}
	function zeroPad(number,length){var n=number.toString();while(n.length<length){n='0'+n;}return n;}

	function fnExtractContinent(str){
		var coords = str.split("|");
		var xx = zeroPad(coords[0], 3);
		var yy = zeroPad(coords[1], 3);

		return yy[0] + xx[0];
	}
	
	function fnGenerateOp() {
		var output = "";
		var coords = [];
		var villageTable = $("th:contains('Villages')").parent().parent();
		var playerTable = villageTable.parent().parent();
	
		var k = [];
		for ( var x = 0; x < 100; x++) {
			k[zeroPad(x, 2)] = [];
		}

		var server = eleDoc.URL.match(/\/\/([a-z0-9]{1,5})\./i)[1];
		var thePlayer = playerTable.find("th:first").text();
		var playerId = eleDoc.URL.match(/id\=(\d+)/i)[1];
		var theTribeTd = playerTable.find("td:contains('Tribe:')").next("td");

		var tribeId = 0;
		var theTribe = theTribeTd.html().match(/.*>(.*)<\/a>/i);
		if(theTribe){
			theTribe = theTribe[1];
			tribeId = parseInt(theTribeTd.html().match(/id\=(\d+)/i)[1],10);
		}

		var thePoints = playerTable.find("td:contains('Points:')").next("td").text();
		var OD = playerTable.find("td:contains('defeated:')").next("td").text();
	
		var as = villageTable.find("a"); //villageTable.getElementsByTagName("a");
		var rows = villageTable.find("tr");
		for (i = 1; i < rows.length; i++) {
			var currentName = as[i - 1].innerHTML;
			var cod = fnGetText(rows[i].cells[1]);
			var pint = fnGetText(rows[i].cells[2]);
			coords[i - 1] = cod;
			k[fnExtractContinent(cod)].push([cod,pint,currentName]);
		}
	
		var index = 1;
		for(var idx = 0; idx < k.length; idx++) {
			var curK = zeroPad(idx, 2);
			if (k[curK][0]) {
				output += "[b]K" + curK + " - " + k[curK].length + " villages;[/b]\n";
				
				for ( var kdx = 0; kdx < k[curK].length; kdx++) {
					var villageLine = k[curK][kdx][0] + " ";
				
					output += villageLine;
					index++;
				}
			
				output += "\n";
			}
		}

		var docSource = "";
		docSource += "<h3>Detailed info:</h3>\n";
		docSource += "<textarea cols='80' rows='9' onFocus='this.select()'>\n";
		docSource += "Claim the village(s) you are going to noble by posting the red bolded number next to the village(s).\n";
		docSource += "------------------------------------------------------------------------------------------------------\n\n";
		docSource += "[color=#ff0000][i][b]Landing Time:[/b][/i][/color]\n";
		docSource += "\n\n";
		docSource += "[color=#ff0eff][i][b]Goal/Mission:[/b][/i][/color]\n";
		docSource += "\n\n";
		docSource += "[color=#4b004b][i][b]Notes:[/b][/i][/color]\n";
		docSource += "\n\n";
		docSource += "[color=#00a500][i][b]Miscellaneous:[/b][/i][/color]\n";
		docSource += "[img]http://www.twstats.com/image.php?type=playerssgraph&graph=points&id=" + playerId + "&s=" + server + "[/img]\n";
		docSource += "[img]http://www.twstats.com/image.php?type=playerssgraph&graph=villages&id=" + playerId + "&s=" + server + "[/img]\n\n";
		docSource += "Name: [player]" + thePlayer + "[/player]\n";
		docSource += "Points: " + thePoints + "\n";
		docSource += "OD: " + OD + "\n";
		docSource += "Tribe: " + ((tribeId > 0)?("[ally]" + theTribe + "[/ally]"):"[color=silver]None[/color]") + "\n";
		docSource += "[url=http://www.twstats.com/" + server + "/index.php?page=player&fi=1&id=" + playerId + "]TWStats[/url]\n";
	
		if(tribeId > 0){
			docSource += "[url=http://www.twstats.com/" + server + "/index.php?page=map&tribe_0_id=" + tribeId + "&tribe_0_colour=ff00ff&player_0_id=" + playerId + "&player_0_colour=00aeff&zoom=100&centrex=500&centrey=500&nocache=1&fill=000000&grid=1]Map[/url]\n";
		}

		docSource += "\n\n";
		docSource += output;
		docSource += "</textarea><br/>\n";
	
		if (!server.match(/uk/i)) {
			docSource += "<h3>Random fake script for all villages:</h3>\n";
			docSource += "<textarea cols='80' rows='9' onFocus='this.select()'>\n";
			docSource += "javascript:var coords = '"+ coords.join(" ") + "';";
			docSource += "var eleDoc=(window.frames.length>0)?window.main.document:document;function fnFillRallyPoint(){var coord=coords.split(' ');var coordSplit=coord[Math.floor(Math.random()*coord.length)].split('|');eleDoc.forms[0].x.value=coordSplit[0];eleDoc.forms[0].y.value=coordSplit[1];var scouts=parseInt(eleDoc.forms[0].spy.nextSibling.nextSibling.innerHTML.match(/\\d+/),10);if(scouts>0){eleDoc.forms[0].spy.value=1;}var rams=parseInt(eleDoc.forms[0].ram.nextSibling.nextSibling.innerHTML.match(/\\d+/),10);if(rams>0){eleDoc.forms[0].ram.value=1;}else{var cats=parseInt(eleDoc.forms[0].catapult.nextSibling.nextSibling.innerHTML.match(/\\d+/),10);if(cats>0){eleDoc.forms[0].catapult.value=1;}}}fnFillRallyPoint();";
			docSource += "</textarea><br/>\n";

			docSource += "<h3>Sequential fake script for all villages:</h3>\n";
			docSource += "<textarea cols='80' rows='9' onFocus='this.select()'>\n";
			docSource += fnGenerateSequentialFakeScript(coords,1);
			docSource += "</textarea><br/>\n";

			docSource += "<h3>Sequential fake train script for all villages:</h3>\n";
			docSource += "<textarea cols='80' rows='9' onFocus='this.select()'>\n";
			docSource += fnGenerateSequentialFakeScript(coords,5);
			docSource += "</textarea><br/>\n";
		}
	
		var outputWin = window.open();
		outputWin.document.open('text/html', 'replace');
		outputWin.document.write(docSource);
		outputWin.document.close();
	}
	
	fnGenerateOp();
	void(0);
}
catch(objError){
	var dbgMsg="Error: " + String(objError.message||objError);
/*
	fnDebugMessage(dbgMsg);
*/
	alert(dbgMsg);
}}


fnExecuteScript();
