// runs at init 
// fill object function. runs updateResources() at end.

function runCity () {
	var numberspots = $('#cityholder').find('div');
	var i;
	for (i = 0; i < numberspots.length; i++) { 
		var thisdiv = numberspots[i];
		var theID = $(thisdiv).attr('ID');
		cityspots[theID] = {};
		if ( $( $(thisdiv).parent() ).hasClass("la") ) {
			cityspots[theID].la = true;
		} else {
			cityspots[theID].la = false;
		}
		if ( $( $(thisdiv).parent() ).hasClass("wa") ) {
			cityspots[theID].wa = true;
		} else {
			cityspots[theID].wa = false;
		}
		if ( $( $(thisdiv).parent() ).hasClass("ws") ) {
			cityspots[theID].ws = true;
		} else {
			cityspots[theID].ws = false;
		}
		if ( $(thisdiv).hasClass("maplock") ) {
			cityspots[theID].lck = true;
		} else {
			cityspots[theID].lck = false;
		}
		if ( $(thisdiv).hasClass("buildingmap") ) {
			var building = $(thisdiv).attr('data-building');
			cityspots[theID].buil = building;
			var neighbours = getEightNeighbours(theID);
      var j;
			if (cityspots[theID].buil == 'foresters') {
				for (j = 0; j < neighbours.length; j++) { 
					var current = neighbours[j];
				//	var building = cityspots[current].buil;
					if (building == 'sawmill') {
						cityspots[theID].proc = 1;
					}
					else {
						cityspots[theID].proc = 0;
					}
				}
			}
			else if (cityspots[theID].buil == 'stonemine') {
				for (j = 0; j < neighbours.length; j++) { 
					//var current = neighbours[j];
				//	var building = cityspots[current].buil;
					if (building == 'masons') {
						cityspots[theID].proc = 1;
					}
					else {
						cityspots[theID].proc = 0;
					}
				}
			}
			else if (cityspots[theID].buil == 'ironmine') {
				for (j = 0; j < neighbours.length; j++) { 
					//var current = neighbours[j];
					//var building = cityspots[current].buil;
					if (building == 'smelter') {
						cityspots[theID].proc = 1;
					}
					else {
						cityspots[theID].proc = 0;
					}
				}
			}
			else if (cityspots[theID].buil == 'farm') {
				for (j = 0; j < neighbours.length; j++) { 
				//	var current = neighbours[j];
				//	var building = cityspots[current].buil;
					if (building == 'grainmill') {
						cityspots[theID].proc = 1;
					}
					else {
						cityspots[theID].proc = 0;
					}
				}
			}
		} else {
			cityspots[theID].buil = "";
		}
	}
	updateResources();
}

// populate res tab, and add lockedspots and processing-building y/n to main object.
// runs at end of runCity(), and after a building is placed or removed.
function updateResources () {
	// init
	var woodtotalprod = 300;
	var stonetotalprod = 0;
	var irontotalprod = 0;
	var foodtotalprod = 0;
	var goldtotalprod = 0;

	var woodstorage = 175000;
	var stonestorage = 175000;
	var ironstorage = 175000;
	var foodstorage = 175000;
	var resprotected = 0;

	var numberbuildings = 0;
		
	var numbercarts = 0;
	var numbertrships = 0;
	var construcspeed = 100;
	
		
	var numberforest =0;
	var numberstone =0;
	var numberiron=0;
	var numberlake=0;
	var numberforesters=0;
	var numberstonemine=0;
	var numberironmine=0;
	var numberfarmestate=0;
	var numbersawmill=0;
	var numbermasonhut=0;
	var numbersmelter=0;
	var numbergrainmill=0;
	var numbervilla=0;
	var numberhideaway=0;
	var numbercabin=0;
	var numberstorehouse=0;
	var numberforum=0;
	var numberport=0;
	var numberguardhouse=0;
	var numbercastle=0;
	var numbertrainingarena=0;
	var numberstable=0;
	var numberacademy=0;
	var numbersorctower=0;
	var numberblacksmith =0;
	var numbershipyard	=0;
	var numberbarracks	=0;
	
	var mystictotalprod=0;
	var cavtotalprod=0;
	var sacredtotalprod=0;
	var navytotalprod=0;
	var guardtotalprod=0;
	var arttotalprod=0;
	var inftotalprod=0;
	var trooptotalprod=0;
	var castletrooptotal=4;
	
	var numberGuard=0;
	var numberBallista=0;
	var numberRanger=0;
	var numberTriari=0;
	var numberPriest=0;
	var numberVanq=0;
	var numberSorc=0;
	var numberScout=0;
	var numberArbalist=0;
	var numberPreator=0;
	var numberHorsemen=0;
	var numberDruid=0;
	var numberRam=0;
	var numberScorpion=0;
	var numberGalley=0;
	var numberStinger=0;
	var numberWarship=0;
	var numberSenator=0;
	
	
	var totalfoodGuard=0;
	var totalfoodBallista=0;
	var totalfoodRanger=0;
	var totalfoodTriari=0;
	var totalfoodPriest=0;
	var totalfoodVanq=0;
	var totalfoodSorc=0;
	var totalfoodScout=0;
	var totalfoodArbalist=0;
	var totalfoodPreator=0;
	var totalfoodHorsemen=0;
	var totalfoodDruid=0;
	var totalfoodRam=0;
	var totalfoodScorpion=0;
	var totalfoodGalley=0;
	var totalfoodStinger=0;
	var totalfoodWarship=0;
	var totalfoodSenator=0;
	
	var totaltimeGuard=0;
	var totaltimeBallista=0;
	var totaltimeRanger=0;
	var totaltimeTriari=0;
	var totaltimePriest=0;
	var totaltimeVanq=0;
	var totaltimeSorc=0;
	var totaltimeScout=0;
	var totaltimeArbalist=0;
	var totaltimePreator=0;
	var totaltimeHorsemen=0;
	var totaltimeDruid=0;
	var totaltimeRam=0;
	var totaltimeScorpion=0;
	var totaltimeGalley=0;
	var totaltimeStinger=0;
	var totaltimeWarship=0;
	var totaltimeSenator=0;
    

	$('.fields').removeClass('fields');


	for (var mapspot in cityspots) {

		cityspots[mapspot].curr = {};
		var building = cityspots[mapspot].buil;
		var thisdiv = $('#' + mapspot);
		var neighbours = getEightNeighbours(mapspot);

		if ( $(thisdiv).hasClass("maplock") ) {
			cityspots[mapspot].lck = true;
		} else {
			cityspots[mapspot].lck = false;
		}

		if  (building.length > 0) { // regular buildings
      var j;

			if (building == 'foresters') {
				numberbuildings += 1;
				numberforesters += 1;
				var wprod = woodProduction(mapspot);
				woodtotalprod += wprod;
				cityspots[mapspot].curr.w = wprod;
				cityspots[mapspot].proc = 0;

				
				for (j = 0; j < neighbours.length; j++) { 
					var current = neighbours[j];
					var tbuilding = cityspots[current].buil;

					if (tbuilding == 'sawmill') {
						cityspots[mapspot].proc = 1;
					}
				}
			}
			if (building == 'stonemine') {
				numberbuildings += 1;
				numberstonemine += 1;
				var sprod = stoneProduction(mapspot);
				stonetotalprod += sprod;
				cityspots[mapspot].curr.s = sprod;
				cityspots[mapspot].proc = 0;

				
				for (j = 0; j < neighbours.length; j++) { 
          var current5 = neighbours[j];
					var tbuilding5 = cityspots[current5].buil;
          
					if (tbuilding5 == 'masons') {
						cityspots[mapspot].proc = 1;
					}
				}
			}
			if (building == 'ironmine') {
				numberbuildings += 1;
				numberironmine += 1;
				var iprod = ironProduction(mapspot);
				irontotalprod += iprod;
				cityspots[mapspot].curr.i = iprod;
				cityspots[mapspot].proc = 0;

				
				for (j = 0; j < neighbours.length; j++) { 
					var current1 = neighbours[j];
					var tbuilding1 = cityspots[current1].buil;

					if (tbuilding1 == 'smelter') {
						cityspots[mapspot].proc = 1;
					}
				}
			}
			
			if (building == 'farm') {
				numberbuildings += 1;
				numberfarmestate += 1;
				var fprod = foodProduction(mapspot);
				foodtotalprod += fprod;
				cityspots[mapspot].curr.f = fprod;
				cityspots[mapspot].proc = 0;
				updateFields(mapspot);

				
				for (j = 0; j < neighbours.length; j++) { 
					var current2 = neighbours[j];
					var tbuilding2 = cityspots[current2].buil;

					if (tbuilding2 == 'grainmill') {
						cityspots[mapspot].proc = 1;
					}
				}
			}
			if (building == 'forest') {
				numberforest += 1;
				var wprod1 = runForestNode(mapspot);
				cityspots[mapspot].curr.w = wprod1;
			}
			if (building == 'stone') {
				numberstone += 1;
				var sprod1 = runStoneNode(mapspot);
				cityspots[mapspot].curr.s = sprod1;
			}
			if (building == 'iron') {
				numberiron += 1;
				var iprod1 = runIronNode(mapspot);
				cityspots[mapspot].curr.i = iprod1;
			}
			if (building == 'lake') {
				numberlake += 1;
				var fprod1 = runLakeNode(mapspot);
				cityspots[mapspot].curr.f = fprod1;
			}
			if (building == 'villa') {
				numberbuildings += 1;
				numbervilla += 1;
				var gprod1 = goldProduction(mapspot);
				goldtotalprod += gprod1;
				cityspots[mapspot].curr.g = gprod1;
			}
			if (building == 'storehouse') {
				numberbuildings += 1;
				numberstorehouse +=1;
				var wstor = woodstorage;
				var sstore = stonestorage;
				var istore = ironstorage;
				var fstore = foodstorage;
				var newamts = totalStorage(mapspot, wstor, sstore, istore, fstore);
				woodstorage = newamts[0];
				stonestorage = newamts[1];
				ironstorage = newamts[2];
				foodstorage = newamts[3];
			}
			if (building == 'hide') {
				numberbuildings += 1;
				numberhideaway += 1;
				resprotected += hideawayAmount(mapspot);
			}
			if (building == 'forum') {
				var gprod = runForum(mapspot);
				cityspots[mapspot].curr.g = gprod;
				numberbuildings += 1;
				numberforum += 1;
				numbercarts += buildingsobject.forum.stats.tradecarts;
			}
			if (building == 'port') {
				var gprod2 = runPort(mapspot);
				cityspots[mapspot].curr.g = gprod2;
				numberbuildings += 1;
				numberport +=1;
				numbertrships += buildingsobject.port.stats.tradeships;
			}
			if (building == 'cabin') {
				var cabinb = runCabinPseudo( getEightNeighbours(mapspot) );
				cityspots[mapspot].curr.w = cabinb[1];
				cityspots[mapspot].curr.s = cabinb[2];
				cityspots[mapspot].curr.i = cabinb[3];
				cityspots[mapspot].curr.f = cabinb[4];
				numberbuildings += 1;
				numbercabin +=1;
				construcspeed += 100;
			}
			if (building == 'sawmill') {
				var wprod2 = runSawmill(mapspot);
				cityspots[mapspot].curr.w = wprod2;
				numberbuildings += 1;
				numbersawmill +=1;
			}
			if (building == 'masons') {
				var sprod2 = runMasons(mapspot);
				cityspots[mapspot].curr.s = sprod2;
				numberbuildings += 1;
				numbermasonhut +=1;
			}
			if (building == 'smelter') {
				var iprod2 = runSmelter(mapspot);
				cityspots[mapspot].curr.i = iprod2;
				numberbuildings += 1;
				numbersmelter +=1;
			}
			if (building == 'grainmill') {
				var fprod2 = runGMill(mapspot);
				cityspots[mapspot].curr.f = fprod2;
				numberbuildings += 1;
				numbergrainmill += 1;
			}
			if (building == 'guardhouse'){
				numberbuildings += 1;
				numberguardhouse +=1;
				var guardprod = guardProduction(mapspot);
				guardtotalprod += guardprod;
			}
			if (building == 'castle') {
				numberbuildings += 1;
				numbercastle +=1;
			}
			if (building == 'arena') {
				numberbuildings += 1;
				numbertrainingarena +=1;
				var infprod = infProduction(mapspot);
				//var inftroop = troopTypeProduction(mapspot);
				inftotalprod += infprod;
			}
			if (building == 'stable') {
				numberbuildings += 1;
				numberstable +=1;
				var cavprod = cavProduction(mapspot);
				//var cavtroop = troopTypeProduction(mapspot);
				cavtotalprod += cavprod;
			}
			if (building == 'sorctower') {
				numberbuildings += 1;
				numbersorctower +=1;
				var mysticprod = mysticProduction(mapspot);
				//var mystictroop= troopTypeProduction(mapspot);
				mystictotalprod += mysticprod;
			}
			if (building == 'academy') {
				numberbuildings += 1;
				numberacademy +=1;
				var sacredprod = sacredProduction(mapspot);
			//	var sacredtroop= troopTypeProduction(mapspot);
				sacredtotalprod += sacredprod;
			}
			if (building == 'blacksmith') {
				numberbuildings += 1;
				numberblacksmith +=1;
				var artprod = artProduction(mapspot);
				//var artttoop = troopTypeProduction(mapspot);
				arttotalprod += artprod;
			}
			if (building == 'shipyard') {
				numberbuildings += 1;
				numbershipyard +=1;
				var navyprod = navyProduction(mapspot);
				//var navytroop = troopTypeProduction(mapspot);
				navytotalprod += navyprod;
			}
			if (building == 'barracks') {
				numberbuildings += 1;
				numberbarracks +=1;
				var troopprod=troopProduction(mapspot);
				trooptotalprod += troopprod;
			
			}
		}
	}
	if (document.querySelector('.castle') !== null) {
			trooptotalprod *=buildingsobject.castle.stats.armysizeexpon;


	}
	if (document.querySelector('.guardhouse') !== null) {
  	numberGuard =999999;
		totalfoodGuard=(trooptype.Guard.buildstats.Foodcost*numberGuard)/24;
		totaltimeGuard=((trooptype.Guard.militarystats.enlistmentspeed*numberGuard)/guardtotalprod);			
	
	}
		
	if (document.querySelector('.arena')!== null) {
						numberVanq= trooptotalprod/trooptype.Vanquisher.otherstats.unitslots;
						numberRanger= trooptotalprod/trooptype.Ranger.otherstats.unitslots;
						numberTriari= trooptotalprod/trooptype.Triari.otherstats.unitslots;
						totalfoodVanq=(trooptype.Vanquisher.buildstats.Foodcost*numberVanq)/24;
			  		totalfoodRanger=(trooptype.Ranger.buildstats.Foodcost*numberRanger)/24;
			  		totalfoodTriari=(trooptype.Triari.buildstats.Foodcost*numberTriari)/24;
			  		totaltimeVanq=((trooptype.Vanquisher.militarystats.enlistmentspeed*numberVanq)/inftotalprod);
			  		totaltimeRanger=((trooptype.Ranger.militarystats.enlistmentspeed*numberRanger)/inftotalprod);
		   			totaltimeTriari=((trooptype.Triari.militarystats.enlistmentspeed*numberTriari)/inftotalprod);
		
	}
	if (document.querySelector('.stable')!== null) {
				numberArbalist =trooptotalprod/trooptype.Arbalist.otherstats.unitslots;
						numberScout =trooptotalprod/trooptype.Scout.otherstats.unitslots;
						numberHorsemen =trooptotalprod/trooptype.Horseman.otherstats.unitslots;
						totalfoodArbalist=(trooptype.Arbalist.buildstats.Foodcost*numberArbalist)/24;
			  		totalfoodScout=(trooptype.Scout.buildstats.Foodcost*numberScout)/24;
			  		totalfoodHorsemen=(trooptype.Horseman.buildstats.Foodcost*numberHorsemen)/24;
			  		totaltimeArbalist=((trooptype.Arbalist.militarystats.enlistmentspeed*numberArbalist)/cavtotalprod);
			  		totaltimeScout=((trooptype.Scout.militarystats.enlistmentspeed*numberScout)/cavtotalprod);
			  		totaltimeHorsemen=((trooptype.Horseman.militarystats.enlistmentspeed*numberHorsemen)/cavtotalprod);
	
	}
	if (document.querySelector('.sorctower')!== null) {
				numberScorpion = trooptotalprod/trooptype.Scorpion.otherstats.unitslots;
			   	

			   		numberSorc =trooptotalprod/trooptype.Sorcerer.otherstats.unitslots;
				 		numberDruid =trooptotalprod/trooptype.Druid.otherstats.unitslots;
				 		totalfoodSorc=(trooptype.Sorcerer.buildstats.Foodcost*numberSorc)/24;
				 		totalfoodDruid=(trooptype.Druid.buildstats.Foodcost*numberDruid)/24;
				 	 	totaltimeSorc=((trooptype.Sorcerer.militarystats.enlistmentspeed*numberSorc)/mystictotalprod);
				 	 	totaltimeDruid=((trooptype.Druid.militarystats.enlistmentspeed*numberDruid)/mystictotalprod);
		
				
	}
	if (document.querySelector('.academy')!== null) {
						numberPriest =trooptotalprod/trooptype.Priestess.otherstats.unitslots;
			    	numberPreator =trooptotalprod/trooptype.Praetor.otherstats.unitslots;
			    	numberSenator=trooptotalprod/trooptype.Senator.otherstats.unitslots;
			    	totalfoodPriest=(trooptype.Priestess.buildstats.Foodcost*numberPriest)/24;
				  	totalfoodPreator=(trooptype.Praetor.buildstats.Foodcost*numberPreator)/24;
				  	totalfoodSenator=(trooptype.Senator.buildstats.Foodcost*numberSenator)/24;
				  	totaltimePriest=((trooptype.Priestess.militarystats.enlistmentspeed*numberPriest)/sacredtotalprod);
				  	totaltimePreator=((trooptype.Praetor.militarystats.enlistmentspeed*numberPreator)/sacredtotalprod);
		
	}
	if (document.querySelector('.blacksmith')!== null) {
						numberRam	=trooptotalprod/trooptype.Ram.otherstats.unitslots;
			   		numberBallista =trooptotalprod/trooptype.Ballista.otherstats.unitslots;
			   		totalfoodScorpion=(trooptype.Scorpion.buildstats.Foodcost*numberScorpion)/24;
			   		totalfoodRam=(trooptype.Ram.buildstats.Foodcost*numberRam)/24;
			   		totalfoodBallista=(trooptype.Ballista.buildstats.Foodcost*numberBallista)/24;
			   		totaltimeScorpion=((trooptype.Scorpion.militarystats.enlistmentspeed*numberScorpion)/arttotalprod);
			   		totaltimeRam=((trooptype.Ram.militarystats.enlistmentspeed*numberRam)/arttotalprod);
			   		totaltimeBallista=((trooptype.Ballista.militarystats.enlistmentspeed*numberBallista)/arttotalprod);
	
	}
	if (document.querySelector('.shipyard')!== null) {
				numberGalley =trooptotalprod/trooptype.Galley.otherstats.unitslots;
			    	numberStinger =trooptotalprod/trooptype.Stinger.otherstats.unitslots;
			    	numberWarship =trooptotalprod/trooptype.Warship.otherstats.unitslots;
			    	totalfoodGalley=(trooptype.Galley.buildstats.Foodcost*numberGalley)/24;
			   		totalfoodStinger=(trooptype.Stinger.buildstats.Foodcost*numberStinger)/24;
			   		totalfoodWarship=(trooptype.Warship.buildstats.Foodcost*numberWarship)/24;
			   		totaltimeGalley=((trooptype.Galley.militarystats.enlistmentspeed*numberGalley)/navytotalprod);
			   		totaltimeStinger=((trooptype.Stinger.militarystats.enlistmentspeed*numberStinger)/navytotalprod);
			   		totaltimeWarship=((trooptype.Warship.militarystats.enlistmentspeed*numberWarship)/navytotalprod);
	
				
	}

	function secondsToDhms(t) {
		t = Number(t);
		var d = Math.floor(t / 84600);
 		var h = Math.floor(t % 84600 / 3600);
 		var m = Math.floor(t % 84600 % 3600 / 60);
  	var s = Math.floor(t % 84600 % 3600 % 60);

    return d +"D " + ('0' + h).slice(-2) + "H " + ('0' + m).slice(-2) + "M ";
	}
		woodtotalprod = Math.round(woodtotalprod);
	stonetotalprod = Math.round(stonetotalprod);
	irontotalprod = Math.round(irontotalprod);
	foodtotalprod = Math.round(foodtotalprod);
	goldtotalprod = Math.round(goldtotalprod);
	woodstorage = Math.round(woodstorage);
	stonestorage = Math.round(stonestorage);
	ironstorage = Math.round(ironstorage);
	foodstorage = Math.round(foodstorage);
	trooptotalprod= Math.round(trooptotalprod);

	$('#woodproductiontd').text(numberWithCommas(woodtotalprod));
	$('#stoneproductiontd').text(numberWithCommas(stonetotalprod));
	$('#ironproductiontd').text(numberWithCommas(irontotalprod));
	$('#foodproductiontd').text(numberWithCommas(foodtotalprod));
	$('#goldproductiontd').text(numberWithCommas(goldtotalprod));
	$('#totalproductiontd').text( numberWithCommas((woodtotalprod + stonetotalprod + irontotalprod + foodtotalprod + goldtotalprod)) );
	$('#woodprotectedtd, #stoneprotectedtd, #ironprotectedtd, #foodprotectedtd').text(numberWithCommas(resprotected));

	$('#woodstoragetd').text(numberWithCommas(woodstorage));
	$('#stonestoragetd').text(numberWithCommas(stonestorage));
	$('#ironstoragetd').text(numberWithCommas(ironstorage));
	$('#foodstoragetd').text(numberWithCommas(foodstorage));

	$('#armysize').text(numberWithCommas(trooptotalprod));
	$('#constrspeedp').text( (numberWithCommas(construcspeed) + '%') );
	$('#numberbuildings').text(numberbuildings);
	$('#numbercarts').text(numberWithCommas(numbercarts));
	$('#numbertradeships').text(numberWithCommas(numbertrships));
	
	$('#numberforest').text(numberforest);
	$('#numberiron').text(numberiron);
	$('#numberstone').text(numberstone);
	$('#numberlake').text(numberlake);
	$('#numberforester').text(numberforesters);
	$('#numberironmine').text(numberironmine);
	$('#numberstonemine').text(numberstonemine);
	$('#numberfarmestate').text(numberfarmestate);
	$('#numbervilla').text(numbervilla);
	$('#numberhideaway').text(numberhideaway);
	$('#numbercabin').text(numbercabin);
	$('#numberstorehouse').text(numberstorehouse);
	$('#numberforum').text(numberforum);
	$('#numberport').text(numberport);
	$('#numberguardhouse').text(numberguardhouse);
	$('#numbercastle').text(numbercastle);
	$('#numbertrainingarena').text(numbertrainingarena);
	$('#numberstable').text(numberstable);
	$('#numbersorctower').text(numbersorctower);
	$('#numberacademy').text(numberacademy);
	$('#numberblacksmith').text(numberblacksmith);
	$('#numbershipyard').text(numbershipyard);
	$('#numberbarracks').text(numberbarracks);
	$('#numbersawmill').text(numbersawmill);
	$('#numbermasonhut').text(numbermasonhut);
	$('#numbersmelter').text(numbersmelter);
	$('#numbergrainmill').text(numbergrainmill);
	
	
	$('#miltabarmysize').text(numberWithCommas(trooptotalprod));
	
	
	$('#guardlistbonus').text(numberWithCommas(guardtotalprod+100)+ '%');
	$('#inflistbonus').text(numberWithCommas(inftotalprod+100)+ '%');
	$('#cavlistbonus').text(numberWithCommas(cavtotalprod+100)+ '%');
	$('#sacredlistbonus').text(numberWithCommas(sacredtotalprod+100)+ '%');
	$('#mysticlistbonus').text(numberWithCommas(mystictotalprod+100)+ '%');
	$('#artlistbonus').text(numberWithCommas(arttotalprod+100)+ '%');
	$('#navylistbonus').text(numberWithCommas(navytotalprod+100)+ '%');
	

$('#numberBallista').text(numberWithCommas(numberBallista));
	$('#numberRanger').text(numberWithCommas(numberRanger));
	$('#numberTriari').text(numberWithCommas(numberTriari));
	$('#numberPriest').text(numberWithCommas(numberPriest));
	$('#numberVanq').text(numberWithCommas(numberVanq));
	$('#numberSorc').text(numberWithCommas(numberSorc));
	$('#numberScout').text(numberWithCommas(numberScout));
	$('#numberArbalist').text(numberWithCommas(numberArbalist));
	$('#numberPreator').text(numberWithCommas(numberPreator));
	$('#numberHorsemen').text(numberWithCommas(numberHorsemen));
	$('#numberDruid').text(numberWithCommas(numberDruid));
	$('#numberRam').text(numberWithCommas(numberRam));
	$('#numberScorpion').text(numberWithCommas(numberScorpion));
	$('#numberGalley').text(numberWithCommas(numberGalley));
	$('#numberStinger').text(numberWithCommas(numberStinger));
	$('#numberWarship').text(numberWithCommas(numberWarship));
	$('#numberSenator').text(numberWithCommas(numberSenator));

$('#timeGuard').text((trooptype.Guard.militarystats.enlistmentspeed / (guardtotalprod + 100)).toFixed(2));
$('#timeBallista').text((trooptype.Ballista.militarystats.enlistmentspeed / (arttotalprod + 100)).toFixed(2));
$('#timeRanger').text((trooptype.Ranger.militarystats.enlistmentspeed / (inftotalprod + 100)).toFixed(2));
$('#timeTriari').text((trooptype.Triari.militarystats.enlistmentspeed / (inftotalprod + 100)).toFixed(2));
$('#timePriest').text((trooptype.Priestess.militarystats.enlistmentspeed / (sacredtotalprod + 100)).toFixed(2));
$('#timeVanq').text((trooptype.Vanquisher.militarystats.enlistmentspeed / (inftotalprod + 100)).toFixed(2));
$('#timeSorc').text((trooptype.Sorcerer.militarystats.enlistmentspeed / (mystictotalprod + 100)).toFixed(2));
$('#timeScout').text((trooptype.Scout.militarystats.enlistmentspeed / (cavtotalprod + 100)).toFixed(2));
$('#timeArbalist').text((trooptype.Arbalist.militarystats.enlistmentspeed / (cavtotalprod + 100)).toFixed(2));
$('#timePreator').text((trooptype.Praetor.militarystats.enlistmentspeed / (sacredtotalprod + 100)).toFixed(2));
$('#timeHorsemen').text((trooptype.Horseman.militarystats.enlistmentspeed / (cavtotalprod + 100)).toFixed(2));
$('#timeDruid').text((trooptype.Druid.militarystats.enlistmentspeed / (mystictotalprod + 100)).toFixed(2));
$('#timeRam').text((trooptype.Ram.militarystats.enlistmentspeed / (arttotalprod + 100)).toFixed(2));
$('#timeScorpion').text((trooptype.Scorpion.militarystats.enlistmentspeed / (arttotalprod + 100)).toFixed(2));
$('#timeGalley').text((trooptype.Galley.militarystats.enlistmentspeed / (navytotalprod + 100)).toFixed(2));
$('#timeStinger').text((trooptype.Stinger.militarystats.enlistmentspeed / (navytotalprod + 100)).toFixed(2));
$('#timeWarship').text((trooptype.Warship.militarystats.enlistmentspeed / (navytotalprod + 100)).toFixed(2));
$('#timeSenator').text((trooptype.Senator.militarystats.enlistmentspeed / (sacredtotalprod + 100)).toFixed(2));




	$('#totaltimeGuard').text(secondsToDhms(totaltimeGuard));
	$('#totaltimeBallista').text(secondsToDhms(totaltimeBallista));
	$('#totaltimeRanger').text(secondsToDhms(totaltimeRanger));
	$('#totaltimeTriari').text(secondsToDhms(totaltimeTriari));
	$('#totaltimePriest').text(secondsToDhms(totaltimePriest));
	$('#totaltimeVanq').text(secondsToDhms(totaltimeVanq));
	$('#totaltimeSorc').text(secondsToDhms(totaltimeSorc));
	$('#totaltimeScout').text(secondsToDhms(totaltimeScout));
	$('#totaltimeArbalist').text(secondsToDhms(totaltimeArbalist));
	$('#totaltimePreator').text(secondsToDhms(totaltimePreator));
	$('#totaltimeHorsemen').text(secondsToDhms(totaltimeHorsemen));
	$('#totaltimeDruid').text(secondsToDhms(totaltimeDruid));
	$('#totaltimeRam').text(secondsToDhms(totaltimeRam));
	$('#totaltimeScorpion').text(secondsToDhms(totaltimeScorpion));
	$('#totaltimeGalley').text(secondsToDhms(totaltimeGalley));
	$('#totaltimeStinger').text(secondsToDhms(totaltimeStinger));
	$('#totaltimeWarship').text(secondsToDhms(totaltimeWarship));
	$('#totaltimeSenator').text(secondsToDhms(totaltimeSenator));

	$('#totalfoodGuard').text(Math.round(totalfoodGuard));
	$('#totalfoodBallista').text(Math.round(totalfoodBallista));
	$('#totalfoodRanger').text(Math.round(totalfoodRanger));
	$('#totalfoodTriari').text(Math.round(totalfoodTriari));
	$('#totalfoodPriest').text(Math.round(totalfoodPriest));
	$('#totalfoodVanq').text(Math.round(totalfoodVanq));
	$('#totalfoodSorc').text(Math.round(totalfoodSorc));
	$('#totalfoodScout').text(Math.round(totalfoodScout));
	$('#totalfoodArbalist').text(Math.round(totalfoodArbalist));
	$('#totalfoodPreator').text(Math.round(totalfoodPreator));
	$('#totalfoodHorsemen').text(Math.round(totalfoodHorsemen));
	$('#totalfoodDruid').text(Math.round(totalfoodDruid));
	$('#totalfoodRam').text(Math.round(totalfoodRam));
	$('#totalfoodScorpion').text(Math.round(totalfoodScorpion));
	$('#totalfoodGalley').text(Math.round(totalfoodGalley));
	$('#totalfoodStinger').text(Math.round(totalfoodStinger));
	$('#totalfoodWarship').text(Math.round(totalfoodWarship));
	$('#totalfoodSenator').text(Math.round(totalfoodSenator));

}

	function troopProduction(thisdiv){
		var finalcount = buildingsobject.barracks.stats.armysize;
		
		return finalcount;	
			
	}



	//enlistment bonus' functions 

	function mysticProduction(thisdiv){
		var toadd =buildingsobject.sorctower.stats.mysticenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function cavProduction(thisdiv){
		var toadd =buildingsobject.stable.stats.cavenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function sacredProduction(thisdiv){
		var toadd =buildingsobject.academy.stats.sacredenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function infProduction(thisdiv){
		var toadd =buildingsobject.arena.stats.infenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function navyProduction(thisdiv){
		var toadd =buildingsobject.shipyard.stats.navyenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function guardProduction(thisdiv){
		var toadd =buildingsobject.guardhouse.stats.guardenlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	function artProduction(thisdiv){
		var toadd =buildingsobject.blacksmith.stats.artienlistmentspeed;
		var neighbours = getEightNeighbours(thisdiv);
		
		var nodebarrack=0;
		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;
			if (building.length > 0) {
				if (building == 'barracks') {
					nodebarrack += 1;
				}
			}
		}
		var finalcount = toadd + (buildingsobject.barracks.stats.enlistmentspeedbonus*nodebarrack);
		return finalcount;	
			
			
	}
	// 7 offshoot updateResources functions
	function woodProduction (thisdiv) {

		var toadd = buildingsobject.foresters.stats.woodproduction;
		var neighbours = getEightNeighbours(thisdiv);

		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'forest') {
					nodes += 1;
				}
				else if (building == 'sawmill') {
					processorbuilding = 1;
				}
				else if (building == 'cabin') {
					cabins += 1;
				}
			}
		}
		var addnodes = toadd + ((toadd * (buildingsobject.forest.stats.woodresnodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject.sawmill.stats.woodprocessingbonus / 100)) * processorbuilding);
		return finalcount;
	}

	function stoneProduction (thisdiv) {

		var toadd = buildingsobject.stonemine.stats.stoneproduction;
		var neighbours = getEightNeighbours(thisdiv);

		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'stone') {
					nodes += 1;
				}
				else if (building == 'masons') {
					processorbuilding = 1;
				}
				else if (building == 'cabin') {
					cabins += 1;
				}
			}
		}
		var addnodes = toadd + ((toadd * (buildingsobject.stone.stats.stoneresnodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject.masons.stats.stoneprocessingbonus / 100)) * processorbuilding);
		return finalcount;
	}

	function ironProduction (thisdiv) {

		var toadd = buildingsobject.ironmine.stats.ironproduction;
		var neighbours = getEightNeighbours(thisdiv);

		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'iron') {
					nodes += 1;
				}
				else if (building == 'smelter') {
					processorbuilding = 1;
				}
				else if (building == 'cabin') {
					cabins += 1;
				}
			}
		}
		var addnodes = toadd + ((toadd * (buildingsobject.iron.stats.ironresnodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject.smelter.stats.ironprocessingbonus / 100)) * processorbuilding);
		return finalcount;
	}

	function foodProduction (thisdiv) {

		var toadd = buildingsobject.farm.stats.foodproduction;
		var neighbours = getEightNeighbours(thisdiv);

		var firstfield = 0;
		var subseqfields = 0;
		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if ( building.length == 0 && cityspots[current].la && $('#cityholder').hasClass('landlocked') ) {

				if (firstfield == 0) {
					firstfield = 1;
				} else {
					subseqfields += 1;
				}
				$('#' + current).addClass('fields');

			}
			else if ( building.length == 0 && cityspots[current].wa && !cityspots[current].ws && $('#cityholder').hasClass('waterside') ) {

				if (firstfield == 0) {
					firstfield = 1;
				} else {
					subseqfields += 1;
				}
				$('#' + current).addClass('fields');

			}
			else if (building == 'lake') {
				nodes += 1;
			}
			else if (building == 'grainmill') {
				processorbuilding = 1;
			}
			else if (building == 'cabin') {
				cabins += 1;
			}
		}
		var addfields = toadd + ((toadd * 0.5) * firstfield) + ((toadd * 0.4) * subseqfields);
		var addnodes = addfields + ((addfields * (buildingsobject.lake.stats.foodresnodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject.grainmill.stats.foodprocessingbonus / 100)) * processorbuilding);
		return finalcount;
	}

	function goldProduction(thisdiv, goldtotalprod) {

		var toadd = buildingsobject.villa.stats.goldproduction;
		var neighbours = getEightNeighbours(thisdiv);

		var forumbuildings = 0;
		var portbuildings = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'forum') {
					forumbuildings += 1;
				}
				else if (building == 'port') {
					portbuildings += 1;
				}
			}
		}
		var addforums = ( toadd * ( buildingsobject.forum.stats.goldtaxbonus / 100 ) ) * forumbuildings;
		var addports = ( toadd * ( buildingsobject.port.stats.goldtaxbonus / 100 ) ) * portbuildings;
		var plusboth = toadd + addforums + addports;
		return plusboth;
	}

	function hideawayAmount(thisdiv, resprotected) {

		var toadd = buildingsobject.hide.stats.reshidden;
		var neighbours = getEightNeighbours(thisdiv);

		var forestnodes = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'forest') {
					forestnodes += 1;
				}
			}
		}
		var addnodes = ( toadd * ( buildingsobject.forest.stats.woodresnodebonus / 100 ) ) * forestnodes;
		var plusnodes = toadd + addnodes;
		return plusnodes;
	}

	function totalStorage(thisdiv, woodstorage, stonestorage, ironstorage, foodstorage) {

		var toadd = buildingsobject.storehouse.stats.storage;
		var neighbours = getEightNeighbours(thisdiv);
		var sawmillsno = 0;
		var masonsno = 0;
		var smelterssno = 0;
		var grainmillsno = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var building = cityspots[current].buil;

			if (building.length > 0) {
				if (building == 'sawmill') {
					sawmillsno += 1;
				}
				else if (building == 'masons') {
					masonsno += 1;
				}
				else if (building == 'smelter') {
					smelterssno += 1;
				}
				else if (building == 'grainmill') {
					grainmillsno += 1;
				}
			}
		}
		var woodtot = ( toadd * ( buildingsobject.sawmill.stats.woodstoragebonus / 100 ) ) * sawmillsno;
		var finalwoodtot = woodstorage + toadd + woodtot;
		var stonetot = ( toadd * ( buildingsobject.masons.stats.stonestoragebonus / 100 ) ) * masonsno;
		var finalstonetot = stonestorage + toadd + stonetot;
		var irontot = ( toadd * ( buildingsobject.smelter.stats.ironstoragebonus / 100 ) ) * smelterssno;
		var finalirontot = ironstorage + toadd + irontot;
		var foodtot = ( toadd * ( buildingsobject.grainmill.stats.foodstoragebonus / 100 ) ) * grainmillsno;
		var finalfoodtot = foodstorage + toadd + foodtot;

		var storageamts = [finalwoodtot, finalstonetot, finalirontot, finalfoodtot];
		return storageamts;
	}

	// get 8 adjacent tiles
	function getEightNeighbours(thisdiv) {

		var dash = thisdiv.search("-");
		var heightpos = parseInt( thisdiv.substring(1,dash) );
		var widthpos = parseInt( thisdiv.substring( (dash+1) ) );

		var neighbour1 = "b" + (heightpos - 1) + "-" + (widthpos - 1);
		var neighbour2 = "b" + (heightpos - 1) + "-" + (widthpos);
		var neighbour3 = "b" + (heightpos - 1) + "-" + (widthpos + 1);
		var neighbour4 = "b" + (heightpos) + "-" + (widthpos - 1);
		var neighbour5 = "b" + (heightpos) + "-" + (widthpos + 1);
		var neighbour6 = "b" + (heightpos + 1) + "-" + (widthpos - 1);
		var neighbour7 = "b" + (heightpos + 1) + "-" + (widthpos);
		var neighbour8 = "b" + (heightpos + 1) + "-" + (widthpos + 1);

		var neighbours = [neighbour1, neighbour2, neighbour3, neighbour4, neighbour5, neighbour6, neighbour7, neighbour8];
		var finalneighbours = [];

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var n = neighbours[j];
			if ( $('#' + n).length > 0 ) {
				if ( (cityspots[n].la && $('#cityholder').hasClass('landlocked')) || (cityspots[n].wa && $('#cityholder').hasClass('waterside')) ) {
					finalneighbours.push(n); 
				}
			}
		}
		return finalneighbours;
	}

	// update farm fields
	function updateFields (thediv) {

		var neighbours = getEightNeighbours(thediv);

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
			var spot = cityspots[current].buil;

			if ( spot.length == 0 && cityspots[current].la && $('#cityholder').hasClass('landlocked') ) {
				$('#' + current).addClass('fields');
			}
			else if ( spot.length == 0 && cityspots[current].wa && !cityspots[current].ws && $('#cityholder').hasClass('waterside') ) {
				$('#' + current).addClass('fields');
			}
		}
	}

	function showOptimization (hovspot) {

		if ( $('#selectabuildingmenu').css('display') == 'none' ) {

			var topvalue = 0;
			var bestbuil = '';
			var currentbuilding = cityspots[hovspot].buil;

			for (var q in cityspots[hovspot].optim) {
				if (cityspots[hovspot].optim[q] > topvalue) {
					topvalue = Math.round(cityspots[hovspot].optim[q]);
					bestbuil = q;
				}
			}

			var bbestbuild;
			var woodcurrent;
			var woodoptimal;
			var stonecurrent;
			var stoneoptimal;
			var ironcurrent;
			var ironoptimal;
			var foodcurrent;
			var foodoptimal;
			var goldcurrent;
			var goldoptimal;

			if (bestbuil == 'if-f') {
				bbestbuild = 'foresters';
				woodoptimal = Math.round(cityspots[hovspot].optim['if-f']);
				$('#optimbuilwood').text(woodoptimal).addClass('white');
			}
			else if (bestbuil == 'if-s') {
				bbestbuild = 'stonemine';
				stoneoptimal = Math.round(cityspots[hovspot].optim['if-s']);
				$('#optimbuilstone').text(stoneoptimal).addClass('white');
			}
			else if (bestbuil == 'if-i') {
				bbestbuild = 'ironmine';
				ironoptimal = Math.round(cityspots[hovspot].optim['if-i']);
				$('#optimbuiliron').text(ironoptimal).addClass('white');
			}
			else if (bestbuil == 'if-a') {
				bbestbuild = 'farm';
				foodoptimal = Math.round(cityspots[hovspot].optim['if-a']);
				$('#optimbuilfood').text(foodoptimal).addClass('white');
			}
			else if (bestbuil == 'if-l') {
				bbestbuild = 'sawmill';
				woodoptimal = Math.round(cityspots[hovspot].optim['if-l']);
				$('#optimbuilwood').text(woodoptimal).addClass('white');
			}
			else if (bestbuil == 'if-h') {
				bbestbuild = 'masons';
				stoneoptimal = Math.round(cityspots[hovspot].optim['if-h']);
				$('#optimbuilstone').text(stoneoptimal).addClass('white');
			}
			else if (bestbuil == 'if-z') {
				bbestbuild = 'smelter';
				ironoptimal = Math.round(cityspots[hovspot].optim['if-z']);
				$('#optimbuiliron').text(ironoptimal).addClass('white');
			}
			else if (bestbuil == 'if-g') {
				bbestbuild = 'grainmill';
				foodoptimal = Math.round(cityspots[hovspot].optim['if-g']);
				$('#optimbuilfood').text(foodoptimal).addClass('white');
			}
			else if (bestbuil == 'if-v') {
				bbestbuild = 'villa';
				goldoptimal = Math.round(cityspots[hovspot].optim['if-v']);
				$('#optimbuilgold').text(goldoptimal).addClass('white');
			}
			else if (bestbuil == 'if-m') {
				bbestbuild = 'forum';
				goldoptimal = Math.round(cityspots[hovspot].optim['if-m']);
				$('#optimbuilgold').text(goldoptimal).addClass('white');
			}
			else if (bestbuil == 'if-o') {
				bbestbuild = 'port';
				goldoptimal = Math.round(cityspots[hovspot].optim['if-o']);
				$('#optimbuilgold').text(goldoptimal).addClass('white');
			}
			else if (bestbuil == 'if-c') {
				bbestbuild = 'cabin';
				woodoptimal = Math.round(cityspots[hovspot].optim['if-c'].w);
				stoneoptimal = Math.round(cityspots[hovspot].optim['if-c'].s);
				ironoptimal = Math.round(cityspots[hovspot].optim['if-c'].i);
				foodoptimal = Math.round(cityspots[hovspot].optim['if-c'].f);
				$('#optimbuilwood').text(woodoptimal).addClass('white');
				$('#optimbuilstone').text(stoneoptimal).addClass('white');
				$('#optimbuiliron').text(ironoptimal).addClass('white');
				$('#optimbuilfood').text(foodoptimal).addClass('white');
			}

			if (!woodoptimal) {
				woodoptimal = 0;
				$('#optimbuilwood').text('-').removeClass('white');
			}
			if (!stoneoptimal) {
				stoneoptimal = 0;
				$('#optimbuilstone').text('-').removeClass('white');
			}
			if (!ironoptimal) {
				ironoptimal = 0;
				$('#optimbuiliron').text('-').removeClass('white');
			}
			if (!foodoptimal) {
				foodoptimal = 0;
				$('#optimbuilfood').text('-').removeClass('white');
			}
			if (!goldoptimal) {
				goldoptimal = 0;
				$('#optimbuilgold').text('-').removeClass('white');
			}

			var finalopttot = woodoptimal + stoneoptimal + ironoptimal + foodoptimal + goldoptimal;
			$('#optimbuiltotal').text(finalopttot).addClass('white');

			$('#optimalbuilname').text(buildingsobject[bbestbuild].name) ;
			$('#optimalbuillarge').css('background', buildingsobject[bbestbuild].medbackground);
			$('#optimbuilimg div').css('background', buildingsobject[bbestbuild].background);


			if (currentbuilding.length > 0) {
				$('#currbuilimg div').css('background', buildingsobject[currentbuilding].background);

				if (currentbuilding == 'foresters' || currentbuilding == 'sawmill' || currentbuilding == 'forest') {
					woodcurrent = Math.round(cityspots[hovspot].curr.w);
					$('#currbuilwood').text(woodcurrent).addClass('white');
				}
				else if (currentbuilding == 'stonemine' || currentbuilding == 'masons' || currentbuilding == 'stone') {
					stonecurrent = Math.round(cityspots[hovspot].curr.s);
					$('#currbuilstone').text(stonecurrent).addClass('white');
				}
				else if (currentbuilding == 'ironmine' || currentbuilding == 'smelter' || currentbuilding == 'iron') {
					ironcurrent = Math.round(cityspots[hovspot].curr.i);
					$('#currbuiliron').text(ironcurrent).addClass('white');
				}
				else if (currentbuilding == 'farm' || currentbuilding == 'grainmill' || currentbuilding == 'lake') {
					foodcurrent = Math.round(cityspots[hovspot].curr.f);
					$('#currbuilfood').text(foodcurrent).addClass('white');
				}
				else if (currentbuilding == 'villa' || currentbuilding == 'forum' || currentbuilding == 'port') {
					goldcurrent = Math.round(cityspots[hovspot].curr.g);
					$('#currbuilgold').text(goldcurrent).addClass('white');
				}
				else if (currentbuilding == 'cabin') {
					woodcurrent = Math.round(cityspots[hovspot].curr.w);
					stonecurrent = Math.round(cityspots[hovspot].curr.s);
					ironcurrent = Math.round(cityspots[hovspot].curr.i);
					foodcurrent = Math.round(cityspots[hovspot].curr.f);
					$('#currbuilwood').text(woodcurrent).addClass('white');
					$('#currbuilstone').text(stonecurrent).addClass('white');
					$('#currbuiliron').text(ironcurrent).addClass('white');
					$('#currbuilfood').text(foodcurrent).addClass('white');
				}

				if (!woodcurrent) {
					woodcurrent = 0;
					$('#currbuilwood').text('-').removeClass('white');
				}
				if (!stonecurrent) {
					stonecurrent = 0;
					$('#currbuilstone').text('-').removeClass('white');
				}
				if (!ironcurrent) {
					ironcurrent = 0;
					$('#currbuiliron').text('-').removeClass('white');
				}
				if (!foodcurrent) {
					foodcurrent = 0;
					$('#currbuilfood').text('-').removeClass('white');
				}
				if (!goldcurrent) {
					goldcurrent = 0;
					$('#currbuilgold').text('-').removeClass('white');
				}

				var finalcurrtot = woodcurrent + stonecurrent + ironcurrent + foodcurrent + goldcurrent;
				if (finalcurrtot > 0) {
					$('#currbuiltotal').text(finalcurrtot).addClass('white');
				} else {
					$('#currbuiltotal').text('-');
				}

			} else {
				$('#currbuilwood').text('-');
				$('#currbuilstone').text('-');
				$('#currbuiliron').text('-');
				$('#currbuilfood').text('-');
				$('#currbuilgold').text('-');
				$('#currbuiltotal').text('-');
				$('#currbuilimg div').css('background', '');			
			}


			$('#spothovermenu').show();

		}
	}

	function hideOptimization () {
		$('#spothovermenu').hide();
		$('.white').removeClass('white');
	}

	// Helper function
function removeLeastProductiveBuilding(resourceType, buildingTypes) {
    var lowres = 1000000;
    var lowestbuild = '';

    for (var divID in cityspots) {
        if (buildingTypes.includes(cityspots[divID].buil) && cityspots[divID].lck == false) {
            if (cityspots[divID].curr[resourceType] < lowres) {
                lowres = cityspots[divID].curr[resourceType];
                lowestbuild = divID;
            }
        }
    }

    if (lowestbuild.length > 0) {
        $("#" + lowestbuild).removeClass().removeAttr('data-building');
        cityspots[lowestbuild].buil = '';
        updateResources();
        //updateMilitary();
        runOptimizer();
    }
}

// Original functions rewritten to use helper function
function removeABuilding() {
    removeLeastProductiveBuilding(null, ['cabin', 'foresters', 'stonemine', 'ironmine', 'farm']);
}

function removeACabin() {
    removeLeastProductiveBuilding(null, ['cabin']);
}

function remoAWoodProd() {
    removeLeastProductiveBuilding('w', ['foresters', 'sawmill', 'cabin']);
}

function remoAStoneProd() {
    removeLeastProductiveBuilding('s', ['stonemine', 'masons', 'cabin']);
}

function remoAIronProd() {
    removeLeastProductiveBuilding('i', ['ironmine', 'smelter', 'cabin']);
}

function remoAFoodProd() {
    removeLeastProductiveBuilding('f', ['farm', 'grainmill', 'cabin']);
}

function remoAGoldProd() {
    removeLeastProductiveBuilding('g', ['villa', 'forum', 'port']);
}

// Helper function
function handleBuildingPlacement(clickedspot, buildtype) {
    $("#" + clickedspot)
        .removeClass()
        .removeAttr('data-building')
        .addClass(buildtype)
        .addClass('buildingmap')
        .attr('data-building', buildtype);
    cityspots[clickedspot].buil = buildtype;
    addToActions(clickedspot, buildtype, 'add');
    updateResources();
    runOptimizer();
}

// Modified placeBuilding function
function placeBuilding(clickedspot, buildtype)
{
    const spot = cityspots[clickedspot];
    const isLandlocked = $('#cityholder').hasClass('landlocked');
    const isWaterside = $('#cityholder').hasClass('waterside');

    if (isLandlocked && spot.la) {
        handleBuildingPlacement(clickedspot, buildtype);
    } else if (isWaterside && spot.wa && spot.ws) { // bay spot in water city
        if (['port', 'shipyard'].includes(buildtype)) {
            handleBuildingPlacement(clickedspot, buildtype);
        }
    } else if (isWaterside && spot.wa && !spot.ws) { // regular spot in water city
        if (!['port', 'shipyard'].includes(buildtype)) {
            handleBuildingPlacement(clickedspot, buildtype);
        }
    } else {
        // Error handling, you can modify as per your application's requirement
        console.error(`Building placement failed: Invalid spot or incompatible building type.`);
    }
}

// Original functions rewritten to use helper function
function addABuilding() {
    const topOptimization = Object.values(topoptimizations).reduce((a, b) => a.val > b.val ? a : b);
    placeBuilding(topOptimization.pos, topOptimization.buil);
}

function addSpecificBuilding(resource) {
    placeBuilding(topoptimizations[resource].pos, topoptimizations[resource].buil);
}

// Using the new helper function
function addACabin() {
    addSpecificBuilding('cabin');
}

function addAWoodProd() {
    addSpecificBuilding('wood');
}

function addAStoneProd() {
    addSpecificBuilding('stone');
}

function addAIronProd() {
    addSpecificBuilding('iron');
}

function addAFoodProd() {
    addSpecificBuilding('food');
}

function addAGoldProd() {
    addSpecificBuilding('gold');
}


	

	// update the optimization recommendation in an object
	// runs on init
	function runOptimizer() {
		const topoptimizations = {
			'wood': { 'val': 0, 'buil': '', 'pos': '' },
			'stone': { 'val': 0, 'buil': '', 'pos': '' },
			'iron': { 'val': 0, 'buil': '', 'pos': '' },
			'food': { 'val': 0, 'buil': '', 'pos': '' },
			'gold': { 'val': 0, 'buil': '', 'pos': '' },
			'cabin': { 'val': 0, 'pos': '' }
		};
	
		const runPseudos = ['f', 's', 'i', 'a', 'l', 'h', 'z', 'g', 'v', 'm'];
	
		Object.keys(cityspots).forEach(mapspot => {
			const spot = cityspots[mapspot];
			if ((spot.la && $('#cityholder').hasClass('landlocked')) || (spot.wa && $('#cityholder').hasClass('waterside'))) {
				const neighbours = getEightNeighbours(mapspot);
				spot.optim = {};
	
				runPseudos.forEach(pseudo => {
					spot.optim[`if-${pseudo}`] = window[`run${pseudo.toUpperCase()}Pseudo`](neighbours);
				});
	
				if ($('#cityholder').hasClass('waterside') && spot.ws === true) {
					spot.optim['if-o'] = runPortPseudo(neighbours);
				}
	
				const cabinbonuses = runCabinPseudo(neighbours);
				const [cabVal, cabWood, cabStone, cabIron, cabFood] = cabinbonuses;
				spot.optim['if-c'] = { val: cabVal, w: cabWood, s: cabStone, i: cabIron, f: cabFood };
	
				if (!spot.lck) {
					const optimizations = [...runPseudos, 'c'];
					optimizations.forEach(optim => {
						let building = '';
						switch (optim) {
							case 'f': building = 'foresters'; break;
							case 'l': building = 'sawmill'; break;
							case 's': building = 'stonemine'; break;
							case 'h': building = 'masons'; break;
							case 'i': building = 'ironmine'; break;
							case 'z': building = 'smelter'; break;
							case 'a': building = 'farm'; break;
							case 'g': building = 'grainmill'; break;
							case 'v': building = 'villa'; break;
							case 'm': building = 'forum'; break;
							case 'c': building = 'cabin'; break;
							default: building = '';
						}
	
						const { val, curr } = spot.optim[`if-${optim}`];
						const topOptim = topoptimizations[building];
						if (val > topOptim.val && (val > curr || !curr) && spot.buil != building) {
							topOptim.val = val;
							topOptim.buil = building;
							topOptim.pos = mapspot;
						}
					});
				}
			}
		});
	}
	

	function runPseudo(neighbours, stats, buildingTypes) {
		var toadd = stats.production;
		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == buildingTypes.node) {
					nodes += 1;
				}
				else if (tbuilding == buildingTypes.processor) {
					processorbuilding = 1;
				}
				else if (tbuilding == 'cabin') {
					cabins += 1;
				}
			}
		}
	
		var addnodes = toadd + ((toadd * (buildingsobject[buildingTypes.node].stats.nodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject[buildingTypes.processor].stats.processingbonus / 100)) * processorbuilding);
		
		return finalcount;
	}
	
	function runForestersPseudo(neighbours) {
		return runPseudo(neighbours, buildingsobject.foresters.stats, { node: 'forest', processor: 'sawmill' });
	}
	
	function runStoneMinePseudo(neighbours) {
		return runPseudo(neighbours, buildingsobject.stonemine.stats, { node: 'stone', processor: 'masons' });
	}
	
	function runIronMinePseudo(neighbours) {
		return runPseudo(neighbours, buildingsobject.ironmine.stats, { node: 'iron', processor: 'smelter' });
	}
	
	function runFarmPseudo(neighbours) {
		// Custom logic for FarmPseudo
		var toadd = buildingsobject.farm.stats.foodproduction;
		var firstfield = 0;
		var subseqfields = 0;
		var nodes = 0;
		var processorbuilding = 0;
		var cabins = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];

			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;

				if ( tbuilding.length == 0 && cityspots[current].la && $('#cityholder').hasClass('landlocked') ) {
					if (firstfield == 0) {
						firstfield = 1;
					} else {
						subseqfields += 1;
					}
				}
				else if ( tbuilding.length == 0 && cityspots[current].wa && !cityspots[current].ws && $('#cityholder').hasClass('waterside') ) {
					if (firstfield == 0) {
						firstfield = 1;
					} else {
						subseqfields += 1;
					}
				}
				else if (tbuilding == 'lake') {
					nodes += 1;
				}
				else if (tbuilding == 'grainmill') {
					processorbuilding = 1;
				}
				else if (tbuilding == 'cabin') {
					cabins += 1;
				}
			}
		}
		var addfields = toadd + ((toadd * 0.5) * firstfield) + ((toadd * 0.4) * subseqfields);
		var addnodes = addfields + ((addfields * (buildingsobject.lake.stats.foodresnodebonus / 100)) * nodes);
		var addcabins = addnodes + ((addnodes * (buildingsobject.cabin.stats.cabinproductionbonus / 100)) * cabins);
		var finalcount = addcabins + ((addcabins * (buildingsobject.grainmill.stats.foodprocessingbonus / 100)) * processorbuilding);
		return finalcount;
	}

	function runProcessorPseudo(neighbours, processorStats, sourceStats, sourceBuilding) {
		var noprocessor = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == sourceBuilding) {
					if (cityspots[current].proc == 0) {
						noprocessor += 1;
					}
				}
			}
		}
	
		var toadd = sourceStats.production;
		var procbonus = ( toadd * ( processorStats.processingbonus / 100 ) ) * noprocessor;
		if (noprocessor > 0) {
			procbonus += toadd;
		}
		return procbonus;
	}
	
	function runSawmillPseudo(neighbours) {
		return runProcessorPseudo(neighbours, buildingsobject.sawmill.stats, buildingsobject.foresters.stats, 'foresters');
	}
	
	function runMasonsPseudo(neighbours) {
		return runProcessorPseudo(neighbours, buildingsobject.masons.stats, buildingsobject.stonemine.stats, 'stonemine');
	}
	
	function runSmelterPseudo(neighbours) {
		return runProcessorPseudo(neighbours, buildingsobject.smelter.stats, buildingsobject.ironmine.stats, 'ironmine');
	}
	
	function runGMillPseudo(neighbours) {
		return runProcessorPseudo(neighbours, buildingsobject.grainmill.stats, buildingsobject.farm.stats, 'farm');
	}
	
	function runVillaPseudo (neighbours) {

		var toadd = buildingsobject.villa.stats.goldproduction;
		var forumbuildings = 0;
		var portbuildings = 0;

		var j;
		for (j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];

			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;

				if (tbuilding == 'forum') {
					forumbuildings += 1;
				}
				else if (tbuilding == 'port') {
					portbuildings += 1;
				}
			}
		}
		var addforums = ( toadd * ( buildingsobject.forum.stats.goldtaxbonus / 100 ) ) * forumbuildings;
		var addports = ( toadd * ( buildingsobject.port.stats.goldtaxbonus / 100 ) ) * portbuildings;
		var plusboth = toadd + addforums + addports;
		return plusboth;
	}

	function runCabinPseudo(neighbours) {

		var prodforester = 0;
		var prodstonemine = 0;
		var prodironmine = 0;
		var prodfarm = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == 'foresters') {
					prodforester += 1;
				}
				else if (tbuilding == 'stonemine') {
					prodstonemine += 1;
				}
				else if (tbuilding == 'ironmine') {
					prodironmine += 1;
				}
				else if (tbuilding == 'farm') {
					prodfarm += 1;
				}
			}
		}
	
		var cabinBonus = buildingsobject.cabin.stats.cabinproductionbonus / 100;
	
		var foresterbonus = prodforester > 0 ? (buildingsobject.foresters.stats.woodproduction * cabinBonus) * prodforester + buildingsobject.foresters.stats.woodproduction : 0;
		var stonebonus = prodstonemine > 0 ? (buildingsobject.stonemine.stats.stoneproduction * cabinBonus) * prodstonemine + buildingsobject.stonemine.stats.stoneproduction : 0;
		var ironbonus = prodironmine > 0 ? (buildingsobject.ironmine.stats.ironproduction * cabinBonus) * prodironmine + buildingsobject.ironmine.stats.ironproduction : 0;
		var foodbonus = prodfarm > 0 ? (buildingsobject.farm.stats.foodproduction * cabinBonus) * prodfarm + buildingsobject.farm.stats.foodproduction : 0;
	
		var tots = foresterbonus + stonebonus + ironbonus + foodbonus;
	
		return [tots, foresterbonus, stonebonus, ironbonus, foodbonus];
	}
	
	function runTaxBuildingPseudo(neighbours, taxBuildingStats) {
		var prodbuils = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == 'villa') {
					prodbuils += 1;
				}
			}
		}
	
		var toadd = buildingsobject.villa.stats.goldproduction;
		var bonus = ( toadd * ( taxBuildingStats.goldtaxbonus / 100 ) ) * prodbuils;
		if (bonus > 0) {
			bonus += toadd;
		}
		return bonus;
	}
	
	function runForumPseudo(neighbours) {
		return runTaxBuildingPseudo(neighbours, buildingsobject.forum.stats);
	}
	
	function runPortPseudo(neighbours) {
		return runTaxBuildingPseudo(neighbours, buildingsobject.port.stats);
	}
	

	function runResourceNode(thisdiv, tbuilding, resourceBuildingStats, resourceStats) {

		var neighbours = getEightNeighbours(thisdiv);
		var prodb = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var currentBuilding = cityspots[current].buil;
	
				if (currentBuilding == tbuilding) {
					prodb += 1;
				}
			}
		}
	
		var toadd = resourceBuildingStats.production;
		var nodebonus = ( toadd * ( resourceStats.resnodebonus / 100 ) ) * prodb;
		if (nodebonus > 0) {
			nodebonus += toadd;
		}
		return nodebonus;
	}
	
	function runForestNode(thisdiv) {
		return runResourceNode(thisdiv, 'foresters', buildingsobject.foresters.stats, buildingsobject.forest.stats);
	}
	
	function runStoneNode(thisdiv) {
		return runResourceNode(thisdiv, 'stonemine', buildingsobject.stonemine.stats, buildingsobject.stone.stats);
	}
	
	function runIronNode(thisdiv) {
		return runResourceNode(thisdiv, 'ironmine', buildingsobject.ironmine.stats, buildingsobject.iron.stats);
	}
	
	function runLakeNode(thisdiv) {
		return runResourceNode(thisdiv, 'farm', buildingsobject.farm.stats, buildingsobject.lake.stats);
	}
	function runProcessorBuilding(thisdiv, targetBuildingName, processorBuildingStats, productionBuildingStats) {

		var neighbours = getEightNeighbours(thisdiv);
		var processor = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == targetBuildingName) {
					processor += 1;
				}
			}
		}
	
		var toadd = productionBuildingStats.production;
		var procbonus = ( toadd * (processorBuildingStats.processingbonus / 100) ) * processor;
		if (procbonus > 0) {
			procbonus += toadd;
		}
		return procbonus;
	}
	
	function runSawmill(thisdiv) {
		return runProcessorBuilding(thisdiv, 'foresters', buildingsobject.sawmill.stats, buildingsobject.foresters.stats);
	}
	
	function runMasons(thisdiv) {
		return runProcessorBuilding(thisdiv, 'stonemine', buildingsobject.masons.stats, buildingsobject.stonemine.stats);
	}
	
	function runSmelter(thisdiv) {
		return runProcessorBuilding(thisdiv, 'ironmine', buildingsobject.smelter.stats, buildingsobject.ironmine.stats);
	}
	
	function runGMill(thisdiv) {
		return runProcessorBuilding(thisdiv, 'farm', buildingsobject.grainmill.stats, buildingsobject.farm.stats);
	}
	
	function runBuilding(thisdiv, buildingStats, targetBuildingName, productionBuildingStats) {

		var neighbours = getEightNeighbours(thisdiv);
		var prodbuils = 0;
	
		for (var j = 0; j < neighbours.length; j++) { 
			var current = neighbours[j];
	
			if ($('#' + current).length > 0) {
				var tbuilding = cityspots[current].buil;
	
				if (tbuilding == targetBuildingName) {
					prodbuils += 1;
				}
			}
		}
	
		var toadd = productionBuildingStats.goldproduction;
		var bonus = ( toadd * (buildingStats.goldtaxbonus / 100 ) ) * prodbuils;
		if (bonus > 0) {
			bonus += toadd;
		}
		return bonus;
	}
	
	function runForum(thisdiv) {
		return runBuilding(thisdiv, buildingsobject.forum.stats, 'villa', buildingsobject.villa.stats);
	}
	
	function runPort(thisdiv) {
		return runBuilding(thisdiv, buildingsobject.port.stats, 'villa', buildingsobject.villa.stats);
	}
	
	