/*
 Javascript code for Global Skirmish -> gskirm
 Synopsis:
 Currently a player-only "Hot Seat" playable
 Things to do.
 p0
 Figure out a system to calculate energy loss.
 Tech phase do everythings!
 -Complete tutorial game with rules info
 Make a rules writeup. (can be p1 if tutorial covers everything)
 Start a database for "saving" and "loading" games.. what information is necessary to save?
 p1
 danger index - how much danger each region is in on being taken over
 power index - how much power partially based on friendly vs unfriendly neighbors
 Transfer energy is fine, what about transfer power?
 Reduce/remove usage of infoWindows (Highlight polylines of neighbors, highlight active continent, etc etc)
 Badge system for bonuses (instead of cards)
 p2
 Ownership info should be accessible. Maybe by clicking on turnorder?
 Display "working" icon...
 Better phase markers.
 Disable manual region selecting?
 
 p3
 Is changeoverlay ui?
 Future
 Use save/load databases to incorporate "real-time multiplayer" ping server for last update of game data, etc
 Write an API for AIs
 Write a very basic AI on the API (probably want danger and power index working first)
 */
if (!(GBrowserIsCompatible())) 
{
	alert("Your browser is not compatible. I'd recommend Firefox.");
}
else if (GBrowserIsCompatible()) 
{

	var logLevel = false;
	var IsTutorial;
	if (document.location.href.indexOf("tutorial.html") == -1) 
	{
		IsTutorial = false;
	}
	else 
	{
		IsTutorial = true;
	}
	
	
	function Gskirm()
	{
		//Constructor and variable definitionsS
		
		//Image arrays
		//this.border = new Array(4);
		
		// todo: change this to use the new dice system 0-6
		this.maxCombat = 6;
		this.maxEnergy = 6;
		this.energyPic = new Array(this.maxEnergy + 1);
		this.combatPic = new Array(this.maxCombat + 1);
		
		this.randum = new Array(6); // random divvy of color/turn order
		//Some useful variables
		this.captureFlag = 0;   // this isn't used right now since there's no card system. 
		this.activeregion = -1;
		this.maxPlace = 1;
		
		this.gskirmImage = "../images/gskirm-back.jpg";
		this.blackImage = "../images/guy-basic.gif";
		this.obelImage = "../images/obelisk.gif";
		
		this.gameTurn = 0;
		this.gamePhase = 0; // Phases - Gather:1(auto), Battle:2, Move:3, Tech:4
		this.gamePhaseImages = new Array(4);
		this.gameRound = 0; //Have some effect on reinforcements
		this.initialSetup = true;
		this.winningPlayer = -1;
		
		this.neutralPlayer = -1;
		this.powerSurge = false;
		this.playersAlive = 0;
		this.liveEnergy = -1;   // LiveEnergy is the amount of energy actively being used. Possible bloat
		this.manualOption = -1;
		this.claimedRegions = 0;
		this.allRegionsOwned = false;
		//this.blank = 1;
		this.obelCont = -1;
		
		var i = 0;
		
		for (i = 0; i <= this.maxCombat; i++) 
		{
			this.energyPic[i] = "../images/energy" + i + ".gif"; // energy in blue, white back
			this.combatPic[i] = "../images/battle" + i + ".gif"; // battle in red face, black back
		}
		
		this.mapStart(); // UI func
		//Some blue cleaning powder
		var request = new XMLHttpRequest();
		request.open("GET", "quickSkirm.xml", true);
		var _this = this; //needed for scoping this into anonymous function
		request.onreadystatechange = function()
		{
			if (request.readyState == 4) 
			{
				var xmlDoc = request.responseXML;
				var game = xmlDoc.documentElement.getElementsByTagName("game");

			    _this.numPlay = parseInt(game[0].getAttribute("players"));
			    _this.numCountry = parseInt(game[0].getAttribute("countries"));
			    _this.numCont = parseInt(game[0].getAttribute("continent"));
			    _this.numObelisks = parseInt(game[0].getAttribute("obelisks"));
		        _this.obelKill = new Array(_this.numObelisks); 
		        
				// Create arrays before consumption
		        _this.nations = new Array(_this.numCountry);
		        _this.cont = new Array(_this.numCont);
		        _this.players = new Array(_this.numPlay);
		        _this.randomizePlayerOrder();

				var plrs = xmlDoc.documentElement.getElementsByTagName("player");
				for (i = 0; i < _this.numPlay; i++) 
				{
				    _this.players[_this.randum[i]] = new Players();
					_this.players[_this.randum[i]].mark = plrs[i].getAttribute("image");
					_this.players[_this.randum[i]].obelMark = plrs[i].getAttribute("obelisk");
					_this.players[_this.randum[i]].color = plrs[i].getAttribute("color");
				}
				
				var cntData = xmlDoc.documentElement.getElementsByTagName("continent");
				for (i = 0; i < _this.numCont; i++) 
				{
				    _this.cont[i] = new Continents();	
					_this.cont[i].name = cntData[i].getAttribute("name");
					_this.cont[i].value = parseFloat(cntData[i].getAttribute("value"));
					_this.cont[i].color = cntData[i].getAttribute("color");
					_this.cont[i].beg = parseFloat(cntData[i].getAttribute("beg"));
					_this.cont[i].end = parseFloat(cntData[i].getAttribute("end"));
					if (_this.cont[i].name == "Obelisks")
					{
					    _this.obelCont = i;
					}
				}
				
				var countries = xmlDoc.documentElement.getElementsByTagName("country");
				for (i = 0; i < _this.numCountry; i++) 
				{
				    _this.nations[i] = new Nations();
					_this.nations[i].owned = -1;
					_this.nations[i].energy = 0;
					_this.nations[i].supply = 0;
					_this.nations[i].combat = Math.ceil(_this.maxCombat / 2.0);    // 3 is starting combat value, half of max value
					_this.nations[i].tech = 0;
					_this.nations[i].neighbors = new Array(6);
					_this.nations[i].name = countries[i].getAttribute("name");
					var lng = parseFloat(countries[i].getAttribute("lng")); 
					var lat = parseFloat(countries[i].getAttribute("lat"));
					_this.nations[i].latLng = new GLatLng(lat, lng);
					_this.nations[i].neighbors[0] = parseInt(countries[i].getAttribute("neighbor0"));
					_this.nations[i].neighbors[1] = parseInt(countries[i].getAttribute("neighbor1"));
					_this.nations[i].neighbors[2] = parseInt(countries[i].getAttribute("neighbor2"));
					_this.nations[i].neighbors[3] = parseInt(countries[i].getAttribute("neighbor3"));
					// todo: total of 4 neighbors in new board system
					_this.nations[i].neighbors[4] = parseInt(countries[i].getAttribute("neighbor4"));
					_this.nations[i].neighbors[5] = parseInt(countries[i].getAttribute("neighbor5"));
					_this.nations[i].homeCont = parseInt(countries[i].getAttribute("cont"));
				}
				
				_this.drawBorders();
				_this.preloadImages();
			}
		}
		request.send(null);
		
		//Code needed for the starting icon, and game start menu, including tabbed infowindow
		this.uiLoading();
		
		if (IsTutorial) 
		{
			TutorialGameSelection();
		}
	}
	
	Gskirm.prototype.randomizePlayerOrder = function()
	{
	    var i;
	    for (i = 0; i < this.numPlay; i++) 
		{
			this.randum[i] = -1; //Randum is the shuffle for player color
		}
		
		var tmp;
		for (i = 0; i < this.numPlay; i++) 
		{
			tmp = Math.floor(Math.random() * this.numPlay);
			while (this.randum[tmp] != -1) 
			{
				tmp = Math.floor(Math.random() * this.numPlay);
			}
			this.randum[tmp] = i;
		//Also change pieces down below
		}
	}
	
		/** 
	 * Receives player options from the game menu
	 * @param {}
	 * @return {}
	 */
		Gskirm.prototype.gameType = function() // called by UI when starting options are chosen
		{
			this.deletePreloaded(); // is preloading helping?
			// reuse Image names for portability
			this.gamePhaseImages[0] = this.getPhaseImages("BattleImage");
			this.gamePhaseImages[1] = this.getPhaseImages("TransferImage");
			this.gamePhaseImages[2] = this.getPhaseImages("TechImage");
			this.gamePhaseImages[3] = this.getPhaseImages("EndImage");
			
			var assignValue = this.getTypeAssignValue();
			var dropValue = this.getTypeDropValue();
			this.numPlay = this.getNumPlayers();
			this.powerSurge = this.getPowerSurge();

			if (this.getNeutralPlayer()) 
			{
				this.neutralPlayer = this.numPlay - 1;
				this.playersAlive = this.numPlay - 1;
				this.players[this.neutralPlayer].alive = 2;
			}
			
			this.virtualDice = false; // todo: remove all of virtual dice: this.getVirtualDice();
			
			this.closeInfoBubble();
			
			// todo: Display "working" icon...
			
			if (IsTutorial) 
			{
				this.sampleGame();
			}
			else if (assignValue == "auto") 
			{
				if (dropValue == "auto") 
				{
					this.fullGame(true);
				}
				else if (dropValue == "man") 
				{
					this.assign();
					this.boardColoring();
					this.makeMarkers();
				}
				else if (dropValue == "min") 
				{
					this.minGame(true);
				}
			}
			else 
			{
				if (dropValue == "auto") 
				{
					this.manualOption = 2;
				}
				else if (dropValue == "man") 
				{
					this.manualOption = 1;
				}
				else if (dropValue == "min") 
				{
					this.manualOption = 0;
				}
				this.manAssign();
			}
		}
		
		//A manual assign game. This draws all the countries on the map
		Gskirm.prototype.manAssign = function()
		{
			var i;
			this.gameTurn = 0;

			for (i = 0; i < this.numPlay; i++) 
			{
				this.players[i].place = (this.numCountry / this.numPlay) * 3;
			}
			//Display all the blank things
			this.boardColoring();
			for (i = 0; i < this.numCountry; i++) 
			{
				this.manMark(i);
			}
			this.allRegionsOwned = true;
			this.closeInfoBubble();
			this.clearStartIcon();

			this.gamePhase = 1;
		}
		
		//Simple helper check for assignment and troop placement during beginning stage of game
		Gskirm.prototype.manChoose = function(choice)
		{
			if (this.nations[choice].owned == -1) 
			{
				this.manClaim(choice);
			}
			else if (this.claimedRegions == this.numCountry) 
			{
				this.place1(choice);
			}
		}
		
		//Function that does the work by claiming all the nations during the manual grab phase
		Gskirm.prototype.manClaim = function(nat)
		{
			if (this.nations[nat].owned != -1) 
			{
				return;
			}
			this.players[this.gameTurn].place--;
			this.nations[nat].energy = 1;
			this.nations[nat].owned = this.gameTurn;
			//change Icon so its obvious	

			this.setClaimedRegionImage(nat);
			
			//this.nations[nat].region.setTooltip(this.nations[nat].name + "(Occupied)"); //working?
			this.unitCount(nat);
			this.gameTurn = (this.gameTurn + 1) % this.numPlay;
			this.boardColoring();
			
			this.claimedRegions++;
			if (this.claimedRegions != numCountry) 
			{
				return;
			}
			
			// all the countries are claimed, kick off game type
			if (this.manualOption == 0) //minimal game
			{
				this.minGame(false);
			}
			else if (this.manualOption == 2) //full game
			{
				this.fullGame(false);
			}
			else if (this.manualOption == 1) //man-man
			{
				this.makeMarkers();
			}
		}
		
		//The beginning assignment, randomnly chooses ownership
		Gskirm.prototype.assign = function()
		{
			var rnd;
			var i;
			this.gameTurn = 0;
			var loop;
			for (i = 0; i < this.numPlay; i++) 
			{
				this.players[i].place = (this.numCountry / this.numPlay) * 3;
			} // todo: 5 energy ok?
			this.claimedRegions = 0;
			while (this.claimedRegions < this.numCountry) 
			{
				loop = true;
				while (loop) 
				{
					rnd = Math.round(Math.random() * 1000) % this.numCountry;
					if (this.nations[rnd].owned == -1) 
					{
						this.nations[rnd].owned = this.gameTurn;
						loop = false;
					}
				}
				this.players[this.gameTurn].place--;
				this.nations[rnd].energy = 1;
				this.claimedRegions++;
				this.gameTurn = (this.gameTurn + 1) % this.numPlay;
			}
			this.defaultIconSize();
		}
		
		//Fully assigns all energy to players territories
		Gskirm.prototype.fullGame = function(needAssign)
		{
			if (needAssign) 
			{
				this.assign();
			}
			var rnd;
			var tot;
			var i;
			var loop = true;
			var lp2 = true;
			while (lp2) 
			{
				loop = true;
				while (loop) 
				{
					rnd = Math.round(Math.random() * 10000) % this.numCountry;
					if (this.nations[rnd].owned == this.gameTurn) 
					    loop = false;
				}
				this.players[this.gameTurn].place--;
				this.nations[rnd].energy++;
				this.gameTurn = (this.gameTurn + 1) % this.numPlay;
				tot = 0;
				for (i = 0; i < this.numPlay; i++) 
				{
					tot += this.players[i].place;
				}
				if (tot == 0) 
				{
					lp2 = false;
				}
			}
			this.run();
		}
		
		// Sample game for use in the tutorial
		Gskirm.prototype.sampleGame = function()
		{
			var rnd;
			var i = 0;
			this.gameTurn = 1;
			var loop;
			// the sample game looks like it was used for testing and not turned back	
			for (i = 0; i < 6; i++) 
			{
				this.nations[i].owned = this.gameTurn;
				this.nations[i].energy = 3;
			}
			this.gameTurn = 0;
			for (i = 6; i < this.numCountry; i++) 
			{
				this.nations[i].owned = this.gameTurn;
				this.nations[i].energy = 3;
			}

			 //for (i = 4; i < this.numCountry; i += 6)
			 //{
			 //this.nations[i].owned = 1;
			 //this.nations[i].energy = 3;
			 //}

			this.baseIcon.iconSize = new GSize(20, 35);
			//this.gamePhase = 1;
			
			for (i = 0; i < this.numPlay; i++) 
			{
				this.players[i].place = 0;
			} // prob not needed
			this.run();
			TutorialInterface1();
		}
		
		//A minimal extra energy, either pre-assigned, or manually assigned
		Gskirm.prototype.minGame = function(needAssign)
		{
			var i;
			if (needAssign) 
			{
				this.assign();
			}
			for (i = 0; i < this.numPlay; i++) 
			{
				this.players[i].place = 0;
			}
			for (i = 0; i < this.numCountry; i++) 
			{
				this.nations[i].energy = 3;
			}
			this.run();
		}
		
		//Places one singular energy on a certain location, should probably just have a place(spot, num)
		Gskirm.prototype.place1 = function(spot)
		{
			if (this.nations[spot].owned != this.gameTurn) 
			{
				return;
			}
			this.nations[spot].energy -= -1;
			this.players[this.gameTurn].place -= 1;
			this.gameTurn = (this.gameTurn + 1) % this.numPlay;
			var tot = 0;

			this.changeOverlay(spot, 20, 35);
			for (var i = 0; i < this.numPlay; i++) 
			{
				tot += this.players[i].place;
			}
			
			if (tot == 0) 
			{
				this.run();
			}
			else 
			{
				this.boardColoring();
			}
		}
		
		//A placement function from the troop add menu
		//troop placement isn't used anymore methinks
		Gskirm.prototype.troopPlacement = function(spot)
		{
			var num = this.getTroopPlaceValue();
			var tot;
			if (isNaN(num)) 
			{
				return;
			}
			//Changed a line here
			if (num > this.players[this.gameTurn].place || num < 0) 
			{
				return;
			}
			if (this.initialSetup && num > 1) 
			{
				return;
			}
			this.nations[spot].energy += num;
			//use this for testing 
			//if (num==83)
			//   this.players[this.gameTurn].place -= this.players[this.gameTurn].place;
			//else
			this.players[this.gameTurn].place += num;
			if (this.gamePhase == 1 && this.players[this.gameTurn].place < 1) 
			    this.gamePhase = 2;
			this.closeInfoBubble();
			if (this.initialSetup) 
			{
				tot = 0;
				for (i = 0; i < this.numPlay; i++) 
				{
					tot += this.players[i].place;
				}
				if (tot == 0) 
				{
					this.run();
				}
				else 
				{
					this.gameTurn = (this.gameTurn + 1) % this.numPlay;
					this.boardColoring();
				}
			}
			else
 			{
				this.triggerClick(spot);
			}
			this.changeOverlay(spot, 20, 35);
		}
		
		//This function runs a few things that are common to any new game
		Gskirm.prototype.run = function()
		{
			for (var i = this.numPlay; i < 6; i++) 
			{
				this.players[i].alive = 0;
			}
			this.initialSetup = false;
			this.uiRun();
			this.makeMarkers();
			this.beginTurn();
		}
		
		//Sees if whomever just lost a nation still has any left
		Gskirm.prototype.checkDead = function(dead)
		{
			var i;
			for (i = 0; i < this.numCountry; i++)
			{
				if (this.nations[i].owned == dead) 
				{
					return;
				} // i'm not dead yet
			}
			this.players[dead].place = "DEAD";
			this.players[dead].alive = 0;
			this.activeTurnColor('this'+dead, "crimson");

			for (i = 0; i < this.numPlay; i++) 
			{
				if (this.players[i].alive != 2) 
				{
					this.playersAlive += this.players[i].alive;
				}
				if (this.players[i].alive == 1) 
				{
					this.winningPlayer = i;
				}
			}
			
			if (this.playersAlive != 1) 
			{
				this.winningPlayer = -1;
			}
			
			if (this.winningPlayer != -1) 
			{
				this.gameOver();
			}
		}
		
		//The function for transferring energy
		Gskirm.prototype.energyTransfer = function(base, outlet)
		{
			var num = this.getAttackMovingValue(); 
			var i;
			var str;

			if (isNaN(num)) 
			{
				return;
			}
			if (num > this.nations[base].supply || num > this.nations[base].energy || num < 1) 
			{
				return;
			}
			if ((this.nations[base].homeCont != this.obelCont) && (num == this.nations[base].energy)) 
			{
				return;
			}
			
			this.nations[base].energy -= num;
			this.nations[base].supply -= num;
			this.nations[outlet].energy += num;
			if (this.nations[base].energy == 0) 
			{
				this.nations[base].owned = -1;
				this.nations[base].combat = 0;
			}

			this.changeOverlay(base, 20, 35);
			this.changeOverlay(outlet, 20, 35);
			this.closeInfoBubble();
			
			var tot = this.supplyTrain();
			
			if (tot == 1) 
			{
				this.triggerClick(this.nations[outlet].region);
			}
			else 
			{
				this.endturn();
			}
		}
		
		//Keeping track of the distance energy has moved in the turn
		Gskirm.prototype.supplyTrain = function()
		{
			var tot = 0;
			for (var i = 0; i < this.numCountry; i++) 
			{
				tot += this.nations[i].supply;
				if (this.nations[i].supply != 0 && this.nations[i].energy == 1 && this.nations[i].homeCont != this.obelCont) 
				{
					tot--;
				}
			}
			if (tot > 0) 
			{
				return 1;
			}
			else 
			{
				return 0;
			}
		}
		
		//Battle info placed in battle corner.
		Gskirm.prototype.battle = function(atk, def)
		{
			//todo: confirm that the battle efficiency working with real dice?
			
			//Change losses to atkLoss and defLoss for easier battle info placement
			var atkDice = this.getAttackAggroValue();
			if (isNaN(atkDice) || atkDice <= 0 || (this.nations[atk].energy < atkDice)) 
			{
			    // todo: Inform user what's wrong?
				return;
			}
			if ((this.nations[atk].homeCont != this.obelCont) && (this.nations[atk].energy == atkDice)) 
			{
				return;
			}
			
			var atkSides = this.nations[atk].combat;
			
			if ((this.nations[def].homeCont == this.obelCont) && (this.nations[def].energy == 0)) 
			{
				this.captureObel(atk, def, atkDice);
				return;
			}
			
			var defDice = this.nations[def].energy;
			var defSides = this.nations[def].combat;
			var atkScore = this.realDicing(atkDice, atkSides);
			var defScore = this.realDicing(defDice, defSides);

			// Whoever Score is greater wins. Loser loses all energy wagered in battle.
			// Winner should lose energy based on how well they won... somehow. 
			// Currently leaving in averaging system, but want to make something more concrete for physical version
			// Maybe a combat matrix?
			// todo: how to do combat losses
			
			// These scores need to be reported along with the losses from  battle
			// average is weird? Find out what i was trying to do
			var atkAvg = this.rollOverAverage(atkScore,atkDice,atkSides);
			var defAvg = this.rollOverAverage(defScore,defDice,defSides);
			var combPerc = (atkSides * 1.0) / (defSides * 1.0);
			var dicePerc = (atkAvg * 1.0) / (defAvg * 1.0);
			
			var losses;
			var atkLoss;
			var defLoss;

			//compare combat score with average score for efficiency rating
			//this value will be used to deduct appropriate energy from the winner on how efficient they are?
			if (defScore > atkScore) 
			{
				//Defender wins.. manage energy loss
				atkLoss = atkDice;
				defLoss = Math.round(atkDice * combPerc * dicePerc);
				if (defLoss >= this.nations[def].energy) 
				{
					defLoss = this.nations[def].energy - 1;
				}

				this.nations[def].energy = this.nations[def].energy - defLoss;
				this.nations[atk].energy = this.nations[atk].energy - atkLoss;
				//Also combat boost
				if (this.nations[def].combat < this.maxCombat) 
				{
					this.nations[def].combat++;
				}//Max combat level!
				if (this.nations[atk].energy == 0) 
				{
					var dying = this.nations[atk].owned;
					this.nations[atk].owned = -1;
					this.nations[atk].combat = 0;
					this.checkDead(dying); // if last units are from an obelisk
				}
				else if (this.nations[atk].combat > 1) 
				{
					this.nations[atk].combat--;
				} //Min combat level!
			}
			else 
			{
				//Attacker wins.. manage energy transfer
				//Combat differentials.
				atkLoss = Math.round(defDice / combPerc / dicePerc);
				if (atkLoss >= atkDice) 
				{
					atkLoss = atkDice - 1;
				}
				defLoss = this.nations[def].energy;

				this.nations[def].energy = 0;
				this.nations[atk].energy = this.nations[atk].energy - atkLoss;
				this.captureTerr(atk, def, atkDice - atkLoss); 
			}
			
			this.changeOverlay(def, 20, 35);
			this.changeOverlay(atk, 20, 35);
			this.closeInfoBubble();
			
			this.setAttackersDice(atkScore, atkSides, atkDice);
			this.setDefendersDice(defScore, defSides, defDice);
			this.setResultField(atkLoss,defLoss);
		}
		
		//Called when attacking an uncontrolled Obelisk before combat for simple takeover
		Gskirm.prototype.captureObel = function(atk, def, atkrs)
		{
			this.nations[def].owned = this.gameTurn;
			this.nations[def].energy = atkrs;
			this.nations[atk].energy -= atkrs;
			this.nations[def].combat = this.nations[atk].combat;
			
			this.changeOverlay(def, 20, 35);
			this.changeOverlay(atk, 20, 35);
			
			this.closeInfoBubble();
			this.triggerClick(this.nations[def].region);
		}
		
		//If defending country is knocked down to 0, attacker takes it over
		Gskirm.prototype.captureTerr = function(atk, def, atkrs)
		{
			var tmpAtk = def;
			var dying = this.nations[def].owned;
			this.captureFlag = 1;
			
			this.nations[def].energy += atkrs;
			this.nations[atk].energy -= atkrs;
			this.nations[def].combat = this.nations[atk].combat + 1; 
			//todo: have a formula to determine if combat improves
			this.nations[def].owned = this.gameTurn;
			if (this.nations[atk].energy == 0) 
			{
				this.nations[atk].owned = -1;
				this.nations[atk].combat = 0;
			}
			
			this.checkDead(dying);
			
			return tmpAtk;
		}
		
		Gskirm.prototype.dicing = function(dice, sides)
		{
			var tot = 0;
			for (var i = 0; i < dice; i++) 
			{
				tot += this.roll(sides);
			}
			return tot;
		}
		
		Gskirm.prototype.realDicing = function(dice, sides)
		{
			
			var tot = 0.0;
			var realSides = sides * 2;
			for (var i = 0; i < dice; i++) 
			{		
				tot += (this.roll(realSides));
			}
			return tot;
		}
		
		//That pesky random dice function everyone hates
		Gskirm.prototype.roll = function(side)
		{
			var die = (Math.floor(Math.random() * side) % side) + 1;
			if (die > side) 
			{
				die = side;
			}
			return die;
		}
		
		Gskirm.prototype.rollOverAverage = function(score, dice, sides)
		{
			var min = this.realDiceMin(dice*1.0,sides*1.0);
			var max = this.realDiceMax(dice*1.0,sides*1.0);
			var avg = dice * (min+max) / 2;
			return avg;
		}
		
		Gskirm.prototype.realDiceMax = function(dice, sides)
		{
			return sides * 2;	// double sides to make polyhedron		
		}
		
		Gskirm.prototype.realDiceMin = function(dice, sides)
		{
			return 1;
		}
		
		Gskirm.prototype.phaseMrk = function()
		{
		//Function for the phase marker and changing it's images and label etc???
		}
		
		//Restamping alters what appears in an infowindow
		Gskirm.prototype.restamp = function()
		{
			if (this.nations[this.land].owned != this.gameTurn) 
			{
				return;
			}
			if (this.gamePhase == 0 || this.gamePhase == 1) 
			{
				if (!this.initialSetup) 
				{
					this.maxPlace = this.players[this.gameTurn].place;
				}
				else 
				{
					this.maxPlace = 1;
				}
				this.setTroopPlaceValue(this.maxPlace);
			}
			if (this.gamePhase == 2) 
			{
				if (this.liveEnergy == -1 || this.liveEnergy >= this.nations[this.land].energy) 
				{
					if (this.nations[this.land].homeCont != this.obelCont) 
					{
						this.liveEnergy = this.nations[this.land].energy - 1;
					}
					else 
					{
						this.liveEnergy = this.nations[this.land].energy;
					}
				}
				this.setAttackAggroValue(this.liveEnergy);
			}
			if (this.gamePhase == 3) 
			{
                var mover;
				if (this.nations[this.land].energy - 1 > this.nations[this.land].supply) 
				{
					mover = this.nations[this.land].supply;
				}
				else 
				{
					mover = this.nations[this.land].energy - 1;
				}
				this.setAttackMovingValue(mover);
			}
		}
		
		Gskirm.prototype.nationOptions = function(land)
		{
			if (this.initialSetup) 
			{
				return this.place1(land);
			}
			
			var c = this.players[(this.nations[land].owned)].color;
			var bgColor;
			// possibly gskui
			if (c == "#FF0000" || c == "#0000FF" || c == "#009999" || c == "#990099") 
			{
				bgColor = "BBBBBB";
			}
			else 
			{
				bgColor = "555555";
			}
			//Maybe make this more dynamic? Convert to decimal and choose?
			var html = "<div style=white-space:nowrap;" + "background-color:#" + bgColor + "><font color=" +
			c +
			">(" +
			this.nations[land].energy +
			")" +
			this.nations[land].name +
			" -- BTL:" +
			this.nations[land].combat;
			
			//Disable the button if the user has no energy available
			if (land != this.activeregion) 
			{
				this.liveEnergy = -1;
			}
			this.activeregion = land;
			
			if (this.nations[land].owned == this.gameTurn) 
			{
				html += this.ownedOptions(land);
			}
			else 
			{
				html += this.enemyOptions(land);
			}
			html += "</form></div>";
			return html;
		}
		
		Gskirm.prototype.ownedOptions = function(land)
		{
			if (this.gamePhase == 1 && this.players[this.gameTurn].place < 1 && this.handsize < 5) 
			{
				this.gamePhase = 2;
			}
			
			var begHtml = "";
			
			if (this.gamePhase == 0 || this.gamePhase == 1) 
			{ //placement currently useless
				if (!this.initialSetup) 
				{
					this.maxPlace = this.players[this.gameTurn].place;
				}
				else 
				{
					this.maxPlace = 1;
				}
				
				// gskui
				begHtml += "<br /><form name=force action=javascript:GS.troopPlacement(" + land + ") >";
				begHtml += "<input class=button type=button value=Add onclick=GS.troopPlacement(" + land + ")>";
				begHtml += "<input type=text name=drop value=" + this.maxPlace + " size=3 />";
				begHtml += "(MAX:" + (this.maxPlace) + ") energy here<br />";
			}
			else if (this.gamePhase == 2) 
			{ //attack phase
				var maxPlay;
				if (this.nations[land].homeCont == this.obelCont) 
				{
					maxPlay = this.nations[land].energy;
				}
				else 
				{
					maxPlay = this.nations[land].energy - 1;
				}
				
				if (this.liveEnergy == -1 || this.liveEnergy > maxPlay) 
				{
					this.liveEnergy = maxPlay;
				}
				
				begHtml += "<br /><form name=attack action=javascript:none() >";
				begHtml += "<input type=text name=aggro value=" + this.liveEnergy + " size=3 />";
				begHtml += "(MAX:" + (maxPlay) + ") attacks: <br />";
			}
			else if (this.gamePhase == 3) 
			{ //energy transfer
				var mover;
				if (this.nations[land].homeCont == this.obelCont || this.nations[land].energy - 1 > this.nations[land].supply) 
				{
					mover = this.nations[land].supply;
				}
				else 
				{
					mover = this.nations[land].energy - 1;
				}
				
				begHtml += "<br /><form name=attack action=javascript:none() >";
				begHtml += "<input type=text name=movin value=" + mover + " size=3>";
				begHtml += "moving. (MAX:" + mover + ")<br />";
			}
			else if (this.gamePhase == 4)
			{
				begHtml += "<br/>";
				// todo do i need a tech menu here?
				
			}
			
			//After generating specific tops, build with basically generic bottom
			var sharedHtml = "";
			var def;
            var i;
			for (i = 0; i < 6; i++) 
			{
				def = this.nations[land].neighbors[i];
				if (def == -1) 
				{
					i = 6;
				}
				else 
				{
					if (i == 2 || i == 4) 
					{
						sharedHtml += "<br />";
					}
					sharedHtml += "<img width=20 height=35 src=";
					if (this.nations[def].owned != -1) 
					{
						if (this.nations[def].homeCont == this.obelCont) 
						{
							sharedHtml += this.players[this.nations[def].owned].obelMark + ">";
						}
						else 
						{
							sharedHtml += this.players[this.nations[def].owned].mark + ">";
						}
					}
					else 
					{
						sharedHtml += this.obelImage + ">";
					}
					sharedHtml += "<input class=button type=button value='" + "(" + this.nations[def].energy + ")";
					sharedHtml += this.nations[def].name + " |" + this.nations[def].combat + "|'";
					if (this.gamePhase == 2) 
					{
						sharedHtml += " onclick=GS.battle(" + land + "," + def + ")";
						
						if (this.nations[def].owned == this.gameTurn) 
						{
							sharedHtml += " disabled";
						}
					}
					else 
					{
					    // todo do I need more stuff for tech phase here?
						if (this.gamePhase == 3) 
						{
							sharedHtml += " onclick=GS.energyTransfer(" + land + "," + def + ")";
						}
						else if (this.gamePhase < 2) 
						{
							sharedHtml += " onclick=GS.troopPlacement(" + def + ")";
						}
						if (this.nations[def].owned != this.gameTurn) 
						{
							sharedHtml += " disabled";
						}
					}
					sharedHtml += ">";
				}
			}
			return (begHtml + sharedHtml);
		}
		
		Gskirm.prototype.enemyOptions = function(land)
		{
			var html = "<br />Not owned<form>";
			for (var i = 0; i < 6; i++) 
			{
				def = this.nations[land].neighbors[i];
				if (def == -1) 
				{
					i = 6;
				}
				else 
				{
					if (i == 2 || i == 4) 
					{
						html += "<br />";
					}
					html += "<img width=20 height=35 src=";
					if (this.nations[def].owned != -1) 
					{
					
						if (this.nations[def].homeCont == this.obelCont) 
						{
							html += this.players[this.nations[def].owned].obelMark + ">";
						}
						else 
						{
							html += this.players[this.nations[def].owned].mark + ">";
						}
					}
					else 
					{
						html += this.obelImage + ">";
					}
					html += "<input class=button type=button value='" + "(" + this.nations[def].energy + ")";
					html += this.nations[def].name + " |" + this.nations[def].combat + "|'";
					if (this.gamePhase == 0 || this.gamePhase == 1) 
					{
						html += " onclick=GS.troopPlacement(" + def + ")"; //gskui
					}
					else 
					{
						html += " onclick=GS.triggerClick(" + def + ")"; //gskui
					}
					if (this.nations[def].owned != this.gameTurn) 
					{
						html += " disabled";
					}
					html += ">";
				}
			}
			return html;
		}
		
		
		//Checks to see if current turn owns all of each continent
		Gskirm.prototype.contBonus = function(beg, end)
		{
			//beg is the number it starts on (inclusive)
			//end is where it ends on (exclusive)
			var i;
			for (i = beg; i < end; i++) 
			{
				if (this.nations[i].owned != this.gameTurn) 
				{
					return;
				}
			}
			this.contBoost(beg, end);
		}
		
		Gskirm.prototype.contBoost = function(beg, end)
		{
			// todo: different tribes may have different contBoost?
			var i;
			for (i = beg; i < end; i++) 
			{
				if (this.nations[i].energy < this.maxEnergy) 
				{
					this.nations[i].energy += 1;
				}
				if (this.nations[i].combat < this.maxCombat) 
				{
					this.nations[i].combat += 1;
				}
				this.changeOverlay(i, 20, 35);
			}
		}
		
		function none()
		{
		}
		
		//Bonuses for owning a whole continent
		Gskirm.prototype.ownedCont = function()
		{
			for (var i = 0; i < this.numCont; i++) 
			{
				this.contBonus(this.cont[i].beg, this.cont[i].end);
			}
		}
		
		Gskirm.prototype.techChoose = function()
		{
		    //todo: don't let this happen if the game isn't in progress.
		    if (this.gamePhase != 3 || this.gamePhase != 2) 
			{
				log("Can't enter tech, not in right phase");
				return;
			}
			this.gamePhase = 4;
			this.gamePhaseColoring();
		}
		
		// todo tech needs to be tweaked, with max 6 a two point downswing is huge. Maybe just +1 Energy for everyone a turn?
		// maybe add an energy at the end of each round for everyone, then at the beginning of the turn do tech
		Gskirm.prototype.checkTech = function()
		{
			//Check which Tech's are valid and assign appropriate changes
			// change tech, only positive?
			if (this.gameRound == 0) //No tech during first round
			{
				return;
			}
			var i;
			for (i = 0; i < this.numCountry; i++) 
			{
				if (this.nations[i].owned == this.gameTurn) // doodz need to be idle during last turn
				{
					var battle = this.nations[i].combat;
					var energy = this.nations[i].energy;
					if (energy > battle + 2) 
					{
						this.battleTech(i);
					}
					else if (battle > energy + 2) 
					{
						this.farmTech(i);
					}
					else 
					{
						this.genericTech(i);
					}
				}
			}
		}
		
		Gskirm.prototype.genericTech = function(num)
		{
			//TODO: Possibly create a danger index, based on neighbors
			var combatModifier = this.dicing(1, 3) - 2;
			//Move energy appropriately (-1 -> +1)
			var energyModifier = this.dicing(1, 3) - 2;
			//Move battle appropriately (-1 -> +1)
			
			this.nations[num].combat += combatModifier;
			this.nations[num].energy += energyModifier;
			
			if (this.nations[num].combat < 1) 
			{
				this.nations[num].combat = 1;
			}
			else if (this.nations[num].combat > this.maxCombat) 
			{
				this.nations[num].combat = this.maxCombat;
			}
			
			if (this.nations[num].energy < 1) 
			{
				this.nations[num].energy = 1;
			}
			else if (this.nations[num].energy > this.maxEnergy) 
			{
				this.nations[num].energy = this.maxEnergy;
			}
			//Change overlays
			this.changeOverlay(num, 20, 35);
		}
		
		Gskirm.prototype.farmTech = function(num)
		{
			//Can only reduce farm with lower battle numbers
			if (this.nations[num].combat != 1) 
				this.nations[num].combat -= 1;
				
			this.nations[num].energy += 2;
			
			if (this.nations[num].energy > this.maxEnergy) 
			{
				this.nations[num].energy = this.maxEnergy;
			}
			this.changeOverlay(num, 20, 35); //gskui?
		}
		
		Gskirm.prototype.battleTech = function(num)
		{
			//TODO: Reduce energy stored for battle prowess
			this.nations[num].combat += 2;
			if (this.nations[num].energy != 1)
			    this.nations[num].energy -= 1;

			if (this.nations[num].combat > this.maxCombat) 
			{
				this.nations[num].combat = this.maxCombat;
			}
			this.changeOverlay(num, 20, 35); //gskui?
		}
		
		Gskirm.prototype.quickAssignTech = function()
		{
			//A quick assignment for each region owned by the current player
			var i;
			for (i = 0; i < this.numCountry; i++) 
			{
			    // if nations.combat = 0? what does that mean?
				if (this.gameTurn == this.nations[i].owned && this.nations[i].tech == 0) 
				{
					if (this.nations[i].energy > this.nations[i].combat + 1) 
					{
						this.nations[i].tech = 3;
					}
					else if (this.nations[i].energy + 1 < this.nations[i].tech) 
					{
						this.nations[i].tech = 2;
					}
					else 
					{
						this.nations[i].tech = 1;
					}
				}
			}
			
		//todo: Moving or attacking guys should probably have a a tech of -1
		//Set this above somewhere.
		
		//defaultTech();
		}
		
		Gskirm.prototype.assignTech = function()
		{
		//After battle and movement are done, let Tech be choosen for a number of
		//nations
		//Should AssignTech be called from a balloon?
		//If so, we need to add another section to check() for possibilities
		//How much overhead is needed for this?
		
		
		}
		
		Gskirm.prototype.defaultTech = function()
		{
			//For the rest of the owned nations default them to the appropriate tech
			for (var i = 0; i < this.numCountry; i++) 
			{
				if (this.gameTurn == this.nations[i].owned && this.nations[i].combat == 0) 
				{
					this.nations[i].combat = 1;
				}
			}
		}
		
		//Things to do in the beginning of each turn, alter for techphase
		Gskirm.prototype.beginTurn = function()
		{
			var tot = 0;
			var i;
			this.captureFlag = 0;
			//Placement portion
			this.winningPlayer = -1;
			this.gamePhase = 2;
			// todo: phase coloring update
			this.gamePhaseColoring();
			
			this.checkTech();
			this.ownedCont();
			
			//var c = this.players[this.gameTurn].color;
			//Needs #ff0000, but getting <font color=#FF0000>
			//c = c.substr(12, 7);
			
			this.liveEnergy = -1;
			
			// todo: this should be more flexible. MaxCountry - NumObelisks
			var startObelisk = this.numCountry - this.numObelisks;
			//Calculate obelisk death threats. 
			for(i = 0; i < this.numObelisks; i++) 
			{
				if (this.nations[startObelisk + i].owned == this.gameTurn) 
				{
					this.obelKill[i] = 1;
				}
				else 
				{
					this.obelKill[i] = 0;
				}
			}
		}
		
		//Called at the end of the turn to switch everything over
		Gskirm.prototype.endturn = function()
		{
			var i;
			var lastTurn;
			var surgedObelisk = false;
			var startObelisk = this.numCountry - this.numObelisks;
			if (this.gamePhase < 2 && this.players[this.gameTurn].place != 0) 				
				return;
			//remove turnlong obelisk stays
			for (i = 0; i < this.numObelisks; i++) 
			{
				if ((this.obelKill[i] == 1) && (this.nations[startObelisk + i].owned == this.gameTurn)) 
				{
				    if (this.powerSurge)
				    {
				        // todo deal a bit of damage to neighboring units
				        // i like this, just have to figure out how much
				        // damages units no matter who owns them. can't wipe out a region
				        // allow power surge to be sometimes beneficial
				    }
					this.nations[startObelisk + i].owned = -1;
					this.nations[startObelisk + i].energy = 0;
					this.nations[startObelisk + i].combat = 0;
					//Reset image of spot
					this.changeOverlay(startObelisk + i, 20, 35); //gskui?
					surgedObelisk = true;
				}
				//else
				this.obelKill[i] = 0;
			}
			if (surgedObelisk) // if an obelisk surged, this player may have lost all units because of it
			{
				this.checkDead(this.gameTurn);
			}
			// todo: do something with tech?
			//Reset turn
			this.gamePhase = 2;
			this.activeTurnColor('turn' + this.gameTurn, "black");

			lastTurn = this.gameTurn;
			this.gameTurn = (this.gameTurn + 1) % this.numPlay;
			while (this.players[this.gameTurn].alive != 1) 
			{
				this.gameTurn = (this.gameTurn + 1) % this.numPlay;
			}
			
			if (lastTurn > this.gameTurn) 
			{
				this.gameRound++;
			}
			
			for (i = 0; i < this.numPlay; i++) 
			{
				this.playersAlive += this.players[i].alive;
				if (this.players[i].alive == 1) 
				{
					this.winningPlayer = i;
				}
			}
			this.activeregion = -1;

			this.closeInfoBubble(); //closedetail
			
			this.quickAssignTech();
			if (this.playersAlive == 1) 
			{
				this.gameOver();
			}
			else 
			{
				this.playersAlive = 0;
				this.beginTurn();
			}
		}
		
		//When starting a new game reset everything. I'm positive this is missing a few things
		Gskirm.prototype.newGame = function()
		{
		    var i;
			for (i = 0; i < this.numCountry; i++) 
			{
				this.nations[i].owned = -1;
				this.nations[i].energy = 0;
				this.nations[i].supply = 0;
			}
			
			this.numPlay = 6;
			
			for (i = 0; i < this.numPlay; i++) 
			{
				this.players[i].alive = 1;
				this.players[i].place = 0;
			}
			
			this.initialSetup = true;
			//this.num = 0;
			this.winningPlayer = -1;
			
			this.neutralPlayer = -1;
			this.powerSurge = false;
			this.liveEnergy = -1;
			this.gameTurn = 0;
			this.gamePhase = 0;
			this.claimedRegions = 0;
			//this.marker_num = 0;
			this.captureFlag = 0;
			
			this.activeregion = -1;
			this.maxPlace = 1;
			this.playersAlive = 6;

			this.uiNewGame();
		}
		
		//gameOver infowindow.. a few things can be brushed in for those curious
		Gskirm.prototype.gameOver = function()
		{
			//This should be called after the game is won
			// May be causing some errors?			
			this.players[this.winningPlayer].place = "Win";
			this.gamePhase = 2;
			this.uiGameOver();
		}
		
		//Function that controls energy transfer
		Gskirm.prototype.freeMove = function()
		{
			var i;
			var tot = 0;
			if (this.gamePhase != 2) 
			{
				log("leaving move");
				return;
			}
			//document.menu.endattk.disabled=true;
			
			this.gamePhase = 3;
			this.gamePhaseColoring();
			for (i = 0; i < this.numCountry; i++) 
			{
				if (this.nations[i].owned == this.gameTurn) 
					this.nations[i].supply = this.nations[i].energy;
				else 
					this.nations[i].supply = 0;
				tot += this.nations[i].supply;
				if (this.nations[i].supply != 0 && this.nations[i].energy == 1 && this.nations[i].homeCont != this.obelCont) 
					tot--;
			}
			
			if (tot > 0) 
			{
				this.triggerClick(this.activeregion);
			} 
			else 
			{
				this.endturn();
			}
		}
		
		// UnitCount also fixes the images of energy and combat
		Gskirm.prototype.unitCount = function(i)
		{
			var val;
			if (this.allRegionsOwned) 
			{
				if (this.nations[i].combat > this.maxCombat) 
				{
					val = this.maxCombat;
				}
				else 
				{
					val = this.nations[i].combat;
				}
				this.setCombatImage(i,val);

				//this.nations[i].regionCombat.N.title = "("+this.nations[i].energy+")"+this.nations[i].name+"|"+this.nations[i].combat+"|";
				if (this.nations[i].energy > this.maxEnergy) 
				{
					val = this.maxEnergy;
				}
				else 
				{
					val = this.nations[i].energy;
				}
				this.setEnergyImage(i,val);
				//this.nations[i].regionEnergy.N.title ="("+this.nations[i].energy+")"+this.nations[i].name+"|"+this.nations[i].combat+"|";
			}
			else 
			{
				this.makeCombatEnergyMarkers(i);
			}
		}
		
		// this is gskui
		Gskirm.prototype.centerTrigger = function(num)
		{
			this.panToFixed();
			this.triggerClick(GS.region[num]);
		}
		
		Gskirm.prototype.makeMarkers = function()
		{
			//Pre: Game type has been selected
			//Post: Draws markers all over board for UI
			
			var i;
			var temp = 0;
			
			this.closeInfoBubble();
			this.clearStartIcon();
			this.panToFixed();
			this.uiMakeMarkers();
			this.allRegionsOwned = true;
		}
		
		var GS;
		function afterLoad()
		{
			GS = new Gskirm();
		}
	}
	
	//The below objects and the variables that will be created for each one, since none of the variables are actually created with data here, assignment will happen during the XML grab
	function Nations()
	{
		//this.name;
		//this.latLng;
		//this.owned;
		//this.energy;
		//this.neighbors;
		//this.region;
		//this.regionCombat;
		//this.regionEnergy;
		//this.supply;
		//this.homeCont;
		//this.combat;
		//this.tech;
	}
	
	function Continents()
	{
		//this.name;
		//this.value;
		//this.color;
		//this.beg; //Inclusive beginning
		//this.end; //Exclusive ending 
	}
	
	function Players()
	{
		//this.place;
		this.alive = 1;
		//this.mark;
		//this.obelMark;
		//this.color;
	}