// ==UserScript==
// @name           Alliance Hideout Check
// @namespace      http://www.hightekcafe.com/ikariam
// @description    Checks everyone's hideout
// @include        http://s*.ikariam.*
// ==/UserScript==

	var lversion = "0.1";
	var thechangingid = "AllyHideouts";
	var pname = "";

	function findformula(MissionBase,enemyhideout,defensivespies,hideout,townhall)
{
	var formula = MissionBase+5*defensivespies+2*hideout-2*townhall-2*enemyhideout;
	if (formula > 95) {formula = 95; }
	if (formula < 5) {formula = 5; }
	return (formula);
}
function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}
	function createSpan(idofspan)
{
var spanTag = document.createElement("span");
spanTag.id = idofspan;
spanTag.className ="dynamicSpan";
document.body.appendChild(spanTag);
}
	function toInt(string)
{
	var temp,result;
	temp = string.split(',');
	result = '';
	for(var i=0; i < temp.length; i++)
	{
		result += temp[i];
	}
	return parseInt(result);
}
function check_hideout(town, eachtownpost, playername)
{
// url needed index.php?view=sendSpy&destinationCityId=townid
var URL = gup();
var spycheck = "http://"+URL+"/index.php?view=sendSpy&destinationCityId="+town;
GM_xmlhttpRequest({
  method:"GET",
  url:spycheck,
  headers:{
    "User-Agent":"monkeyagent",
    "Accept":"text/monkey,text/xml",
    },
  onload:function(details) {
	var townhideout;
	if (details.readyState == 4) {
	var percentage = details.responseText.split('class="percentage">')[1];
	percentage = percentage.split('</div>')[0];
	var townlevel = details.responseText.split('size of ')[1];
	townlevel = townlevel.split('. It is easier')[0];
	townhideout = eachtownpost+" Town Hall:"+townlevel+" Percentage:"+percentage;
	//towns = replace(/eachtownpost/i, townhideout);
	//alert(townhideout);
	//return townhideout;
	var enemyhideout = document.getElementById('enemyspy').value;
	GM_setValue('enemyspy',enemyhideout);
	var formula = findformula(5,enemyhideout,townlevel,townlevel,townlevel);
	var newformula = percentage.replace(/%/i, "");
	newformula = toInt(newformula);
	var failed = "<font color=\"RED\">FAILED</font>";
	if (newformula >= formula) {
	failed = "<font color=\"GREEN\">PASSED</font>";
	}
		document.getElementById(thechangingid).innerHTML+="<div class=\"table-row\"><div class=\"left-container13\"><h5 class=\"colhdr\">"+playername+"</h5></div><div class=\"left-container23\"><h5 class=\"colhdr\">"+eachtownpost+"\("+townlevel+"\)</h5></div><div class=\"right-container13\"><h5 class=\"colhdr\">"+percentage+" / "+failed+"</h5></div><div class=\"space-line\"></div></div>";
	//document.getElementById(thechangingid).innerHTML+="<tr><td>"+playername+"</td><td>"+townlevel+"</td><td>"+percentage+"</td></tr>";
	} else {
	// this is what is inputted if an error occurs
	//document.getElementById(thechangingid).innerHTML+="<tr><td>"+playername+"</td><td>ERROR</td><td>ERROR</td></tr>";
	//return "";
	}

  }
});

}
	function gup()
{
var url = window.location.href;
var urlparts = url.split('//');
var urlparts2 = urlparts[1].split('/');
var results = urlparts2[0];
  if( results == null )
    return "";
  else
    return results;
}



	function get_all(pname)
	{
	if (pname == "all") {
	alert("Please wait while it grabs the information it needs. If your alliance has ALOT of towns this will take a long time, it will also freeze firefox while going through the process. Many towns take a long time, depends on internet connection and server load.");
	} else {
	alert("Please wait while it grabs the information it needs. Many towns take a long time, depends on internet connection and server load.");
	GM_setValue('pname',pname);
	}
	var alliance = document.getElementById('mainview').childNodes[5].childNodes[3].childNodes[1];
	
	document.getElementById(thechangingid).innerHTML+="<div class=\"table-row\"><div class=\"left-container13\"><h5 class=\"colhdr\"><b>Name</b></h5></div><div class=\"left-container23\"><h5 class=\"colhdr\"><b>Town name(Town Hall Level)</b></h5></div><div class=\"right-container13\"><h5 class=\"colhdr\"><b>Spy Percentage</b></h5></div><div class=\"space-line\"></div></div>";

	
	//<table border=5><tr><td>Player Name</td><td>Town Hall</td><td>Percentage</td></tr>";
			for (var jj = 1; jj < alliance.rows.length; jj++)
		{
			
			empty1 = alliance.rows[jj].cells[0].innerHTML;
			playername = alliance.rows[jj].cells[1].innerHTML;
			towns = alliance.rows[jj].cells[2].innerHTML;
			rank = alliance.rows[jj].cells[3].innerHTML;
			points = alliance.rows[jj].cells[4].innerHTML;
			action = alliance.rows[jj].cells[5].innerHTML;
			if (playername == pname || pname == "all") {
			var eachtown = towns.split('<li>');
			var num = 0;
			var eachtownget, eachtownpost, townlvl, hideper, townper;
			
				for (var ts = 0; ts < eachtown.length; ts++)
				{
					if (ts != 0) {
					eachtownget = eachtown[ts].split('ity=')[1];
					eachtownget = eachtownget.split('\" class')[0];
					eachtownpost = eachtown[ts].split('class="city">')[1];
					eachtownpost = eachtownpost.split('</a>')[0];
					//alert(eachtownget);
					check_hideout(eachtownget, eachtownpost, playername);
					//alert(get_return);
					}
				}
				
			}
		}
		self.setTimeout(window.scrollTo(0,9e9), 5000)
	}

	
window.addEventListener('load',  function() 
{ 
try
{
	var page = document.getElementsByTagName('body')[0].id;
	if (page == 'embassy') 
	{
	addGlobalStyle('DIV.base-layer {background: none #cc9966; border: solid #333333 1px; color: #000000;margin: 0.5em 12px 0.5em 12px; padding: 0; text-align: center; width: auto;}');
	addGlobalStyle('DIV.table-row {background: none #ffffcc; border: solid #000000 1px; color: #000000;margin-top: 0; margin-right: auto; margin-bottom: 0; margin-left: auto;padding: 0; text-align: center; width: 800px;}');
	addGlobalStyle('DIV.left-container2 {border: none; float: left; margin: 0; padding: 0; width: 50%;}');
	addGlobalStyle('DIV.right-container2 {border: none; float: right; margin: 0; padding: 0; width: 50%;}');
	addGlobalStyle('DIV.left-container13 {border: none; float: left; margin: 0; padding: 0; width: 35%;}');
	addGlobalStyle('DIV.left-container23 {border: none; float: left; margin: 0; padding: 0; width: 35%;}');
	addGlobalStyle('DIV.right-container13 {border: none; float: right; margin: 0; padding: 0; width: 30%;}');
	addGlobalStyle('DIV.left-layer11 {border: none; float: left; margin: 0; padding: 0; width: 9%;}');
	addGlobalStyle('DIV.right-layer11 {border: none; float: right; margin: 0; padding: 0; width: 10%;}');
	addGlobalStyle('DIV.space-line {clear: both; margin: 0; padding: 0; width: auto;}');
	addGlobalStyle('H4.table-caption {background: transparent; color: #3333cc; font-family: sans-serif;font-size: 1em; font-style: italic; font-weight: bold; margin: 0;padding: 0.3em; text-align: center; width: auto;}');
	addGlobalStyle('H5.colhdr {background: none #ffffcc; border: solid #3333cc 1px; color: #993333;font-family: sans-serif; font-size: 1em; font-style: italic;font-weight: normal; margin: 0; padding: 0.3em 0.3em 0 0.3em;text-align: center; width: auto;}');
	addGlobalStyle('P.text {border: solid #3333cc 1px; margin: 0; padding: 0.3em 0.3em 0 0.3em;font-style: normal; font-size: 1em; text-align: center; text-indent: 0;width: auto;}');
	

	
	var alliance = document.getElementById('mainview').childNodes[5].childNodes[3].childNodes[1];
	var test = alliance.innerHTML;
		var footer_update = document.getElementById('embassyMenu');
			footer_update.innerHTML += "<div class='content'><h3 class='header'>Hideout Check</h3>";
/*	
		for (var jj = 1; jj < alliance.rows.length; jj++)
		{
			empty1 = alliance.rows[jj].cells[0].innerHTML;
			playername = alliance.rows[jj].cells[1].innerHTML;
			towns = alliance.rows[jj].cells[2].innerHTML;
			rank = alliance.rows[jj].cells[3].innerHTML;
			points = alliance.rows[jj].cells[4].innerHTML;
			action = alliance.rows[jj].cells[5].innerHTML;
			footer_update.innerHTML += "<div style='padding-left: 10px;' id='"+playername+">\n "+playername+"</div>";
			
		}
*/
	var enemyspy = GM_getValue('enemyspy', 32);
	var Playername = GM_getValue('pname', 'Playername');

			footer_update.innerHTML += "<center>Your Hideout(In this town)<br /><input id=\"enemyspy\" type='textfield' class='textfield' name='enemyspy' size='10' value='"+enemyspy+"' /><br />Player to Check(Case Sensitive)<br /><input id=\"pname2\" type='textfield' class='textfield' name='pname2' size='10' value='"+Playername+"' /><br /><a href=\"javascript:return false;\" id='get_one'>Check Players Hideouts</a><br /><br /><div id='get_all2'><a href=\"javascript:return false;\" id='get_all'>Check ALL Hideouts</a><br /><font color='red'>Not Recommended</font></div><br />Check bottom of page when done.</center>";
			footer_update.innerHTML += "</div>";

	createSpan(thechangingid);
	
	document.getElementById('get_one').addEventListener('click',function(event){var pname2 = document.getElementById('pname2').value;get_all(pname2);event.preventDefault();},true);
	document.getElementById('get_all').addEventListener('click',function(event){document.getElementById('get_all2').innerHTML="";get_all("all");event.preventDefault();},true);
	}
	// Add options menu
	if (page == 'options')
	{
		var allElements = document.getElementsByTagName('form');

		for (var i = 0; i < allElements.length; i++)
		{
		    var thisElement = allElements[i];
			if (thisElement.elements[0].value == 'Options')
			{
				var debug_mode_on,debug_mode_off,sort_on,sort_on2,sort_off;
				var debug_mode 	= GM_getValue('debug_mode','0');

				if (debug_mode == 0)
					debug_mode_off =  "checked='checked'";
				if (debug_mode == 1)
					debug_mode_on =  "checked='checked'";
				var div;
				div = document.createElement('div');
				div.innerHTML = 
					"<div id='allyhideoutcheck'>"+
						"<h3>Alliance Hideout Check V "+lversion+" Options</h3>"+
						"<table cellpadding='0' cellspacing='0'>"+
							"<tr>"+
								"<th>Debug Mode:</th>"+
								"<td>On<input id='radio_debugally1' type='radio' class='radio' name='debug_mode' value='1' "+debug_mode_on+"/> Off<input id='radio_debugally2' type='radio' class='radio' name='debug_mode' value='0' "+debug_mode_off+"/></td>"+
							"</tr>"+
				        "</table>"+
				    "</div>";
				
				thisElement.insertBefore(div, document.getElementById('options_debug'));
	            
	            document.getElementById('radio_debugally1').addEventListener('change',function(event){GM_setValue('debug_mode','1')},true);
	            document.getElementById('radio_debugally2').addEventListener('change',function(event){GM_setValue('debug_mode','0')},true);
			}
		}
	}
}
catch(er)
				{
				var debug_mode 	= GM_getValue('debug_mode','0');
				if (debug_mode == 1) {
				alert("Alliance Hideout Check v"+lversion+"\n If you think this is a critical error, post it in the ikariamlibrary.com forums.\n\n\n" + er)
				}
				}
},
    true);