document.getElementById("loadingMessage").innerHTML = 'Loading windows...';


function SwitchWindows(srcWindow, dstWindow)
{
	clearOutCrewmen();
	document.getElementById(srcWindow).style.display = 'none';
	document.getElementById(dstWindow).style.display = 'inline';
	currentWindowShown = dstWindow;
	
	if (dstWindow == 'mapScreen') {
		document.getElementById('quickmapButton').style.display = "none";	
	} else if (dstWindow == 'portMainScreen') {
		document.getElementById('quickmapButton').style.display = "inline";	
		if (isCrippledFreeVersion == true) {
			document.getElementById("freeVersionText").innerHTML = fullVersionFacts[currentBuyMessageIndex];
			currentBuyMessageIndex = currentBuyMessageIndex + 1;
			if (currentBuyMessageIndex >= fullVersionFacts.length) {
				currentBuyMessageIndex = 10;
				showConfirmationWindow("Nag, Nag, Nag", "Arr, do ye not yet get it?  This is a free web version of an App Store game.  While yer more than welcome to keep playin' the free version te yer heart's content, ye'll be facin' these incredibly annoying interruptions from time te time.  That, and the full version o' the game has more goodies an' fewer restrictions on ye.  So go ahead and buy it, eh?", "That's an excellent idea!", "No.  I am stunningly cheap.", "buyGame", 0);
			}
		}
	}
//	SetPortsVisible();
	
}

function showAlertWindow(title, message, button)
{
	clearOutCrewmen();
	document.getElementById("alertTitle").innerHTML = title;
	document.getElementById("alertMessage").innerHTML = message;
	document.getElementById("alertButton").innerHTML = button;
	document.getElementById("alertScreen").style.display = "inline";
		
}

function closeAlertWindow()
{
	document.getElementById('alertScreen').style.display = 'none';
	drawCrewIfValid();
}

function drawCrewIfValid() {
	if (document.getElementById("crewManagementScreen").style.display != "none") {
		populateShipPartCrewmen();
	}
	if (document.getElementById("recruitmentScreen").style.display != "none") {
		drawBarCrewmen();
	}
	if (document.getElementById("crewmanActionScreen").style.display != "none") {
		document.getElementById("largeCrewmanSVG").style.left = '46px';
		document.getElementById("largeCrewmanSVG").style.top = '130px';
	}
	
}

function showConfirmationWindow(title, message, yesButton, noButton, action, index)
{
	if (index == null)
	{
		index = -1;
	}
	confirmationAction = action;
	confirmationIndex = index;
	ClearAllChildren("confirmMessage");
	document.getElementById("confirmTitle").innerHTML = title;
	switch (action)
	{
		case "hireCrewman":
			DrawCrewmanLarge(barCrewmen[index], "confirmMessage", message);			
			break;
		case "hireCrewmanVictory":
			DrawCrewmanLarge(encounterShip.crew[index], "confirmMessage", message);
			break;
		default:
			document.getElementById("confirmMessage").innerHTML = message;
			break;
	}
	
//	if (action == "battleVictory") {
//		alert("end combat here!");
//		document.getElementById('confirmNay').onClick = endCombat();
//	} else {
//		document.getElementById('confirmNay').onClick = closeConfirmWindow();
//	}

	document.getElementById("confirmAye").innerHTML = yesButton;
	document.getElementById("confirmNay").innerHTML = noButton;
	
	if (yesButton == "") {
	document.getElementById("confirmAye").style.display = "none";
	} else {
	document.getElementById("confirmAye").style.display = "inline";
	}

	if (noButton == "") {
	document.getElementById("confirmNay").style.display = "none";
	} else {
	document.getElementById("confirmNay").style.display = "inline";
	}

	document.getElementById("confirmScreen").style.display = "inline";
	
} 

function clickedCancel()
{
	switch (confirmationAction)
	{
		case "battleVictory":
			document.getElementById('confirmScreen').style.display = 'none';
			lossesFromDamage(0);
//			addCrewmanFromVictory(0);
			break;
		case "hireCrewmanVictory":
			addCrewmanFromVictory(confirmationIndex+1);
			break;
			
		default:
			document.getElementById('confirmScreen').style.display = 'none';
	}
	clearOutCrewmen();
	drawCrewIfValid();
}

function clickedConfirm()
{
	var i, swappingShipPartIndex;
	
	document.getElementById('confirmScreen').style.display = 'none';
	clearOutCrewmen();
	switch (confirmationAction)
	{
		case "buyGame":
			buyGame();
			break;
		case "abandonMission":
			adjustReputation(currentMissions[selectedMission].failureSourceKarma, currentMissions[selectedMission].sourcePort)
			adjustReputation(currentMissions[selectedMission].failureTargetKarma, currentMissions[selectedMission].targetPort)
			AdjustCash(currentMissions[selectedMission].failureCash)
			currentMissions[selectedMission] = createNewMission();
			selectedMission = -1;
			drawAllMissions();
			break;
		case "purchaseShip":
			AdjustCash(getPurchasePrice(playerShip, availableShips[selectedShipyardPart]));
			playerShip = availableShips[selectedShipyardPart];
			availableShips[selectedShipyardPart] = createRandomBlankHull();
			drawShipPart(availableShips[selectedShipyardPart]);
			for (i=0; i<playerShip.attachments.length;i++) {
				playerShip.attachments[i] = createNullAttachment();
			}
			populateWithAutoPirate(playerShip);
			drawShipPart(playerShip);
			activateShipyardScreen();
			break;
		case "encounterPartVent":
			for (i = 0; i < playerShip.attachments[confirmationIndex].cargo.length; i++) {
				playerShip.attachments[confirmationIndex].cargo[i] = 0;
			}
			
			playerShip.attachments[confirmationIndex].curCargo = 0;

			playerShip.attachments[confirmationIndex].crew = new Array(playerShip.attachments[confirmationIndex].maxCrew);
			playerShip.attachments[confirmationIndex].curCrew = 0;
			populateWithAutoPirate(playerShip.attachments[confirmationIndex]);

			calculateAdjustedValues(playerShip);

			drawShipPart(playerShip);
			lossesFromDamage(confirmationIndex+1);			
			break;
		case "encounterPartLoss":
			playerShip.attachments[confirmationIndex] = createNullAttachment();


			calculateAdjustedValues(playerShip);

			drawShipPart(playerShip);
			lossesFromDamage(confirmationIndex+1);
			
			break;
		case "purchaseShipPart":
			swappingShipPartIndex = -1;
//			alert("currentlySelected: " + selectedShipPartID);
			for (i=0; i<playerShip.attachments.length; i++) {
//			alert("i = " + i + "; currentlySelected: " + selectedShipPartID + ", currentAttachmentID = " + playerShip.attachments[i].ID);
				if (playerShip.attachments[i].ID == selectedShipPartID) {
					swappingShipPartIndex = i;
				}
			}
			if (swappingShipPartIndex != -1) 
			{
				AdjustCash(getPurchasePrice(playerShip.attachments[swappingShipPartIndex], availableShipParts[selectedShipyardPart]));
				playerShip.attachments[swappingShipPartIndex] = availableShipParts[selectedShipyardPart];
				availableShipParts[selectedShipyardPart] = createRandomShipAttachment();
				drawShipPart(availableShipParts[selectedShipyardPart]);
				populateWithAutoPirate(playerShip.attachments[swappingShipPartIndex]);
				drawShipPart(playerShip);
				activateShipyardScreen();
			}
			break;
		case "battleVictory":
			if (victoryCargoType != -1) {
				TransferStocks(playerShip, victoryCargoType, victoryCargoAmount);
			}
			lossesFromDamage(0);
//			addCrewmanFromVictory(0);
			break;
		case "fireCrewman":
			RemoveCrewman(playerShip, currentlySelectedCrewman.ID);
			populateWithAutoPirate(playerShip);
			SwitchWindows('crewmanActionScreen', 'crewManagementScreen');
			UpdateShipPartSelectbox('crewManagementShipComponents');
			populateShipPartCrewmen();
			break;
		case "hireCrewman":
			AdjustCash(-(Math.floor(barCrewmen[confirmationIndex].cost)));
			dropFirstAutoPirate(playerShip);
			AddCrewman(barCrewmen[confirmationIndex], playerShip);
			barCrewmen[confirmationIndex] = CreateRandomCrewman();
			drawBarCrewmen();
			DrawCrewmanCard(confirmationIndex, barCrewmen[confirmationIndex], "recruitableCrewmen", "addCrewmanToCrew");
			break;
		case "hireCrewmanVictory":
			AdjustCash(-(Math.floor(encounterShip.crew[confirmationIndex].cost)));
			dropFirstAutoPirate(playerShip);
			AddCrewman(encounterShip.crew[confirmationIndex], playerShip);
			addCrewmanFromVictory(confirmationIndex+1)
//			barCrewmen[confirmationIndex] = CreateRandomCrewman();
//			DrawCrewmanCard(confirmationIndex, barCrewmen[confirmationIndex], "recruitableCrewmen", "addCrewmanToCrew");
			break;
		case "shipRepairs":
			var partToRepair;
			if (confirmationIndex == -1)
			{
				partToRepair = playerShip;
			} else {
				partToRepair = getShipPart(playerShip, confirmationIndex);
			}

			AdjustCash(-1 * GetRepairCost(partToRepair));
			restorePartArmor(partToRepair);
			calculateAdjustedValues(playerShip);	
			UpdatePartDetails(partToRepair, 'shipManagementImage', 'shipManagementHealthImage');
			drawShipPart(playerShip);
			drawShipPartToDiv(playerShip, "shipManagementImage", "shipManagementHealthImage");
			drawShipPartHealthToDiv(playerShip, "shipManagementHealthImage");
			break;
	}
}

function buyGame() {
	// once we're up on the app store, this'll link to the game.  For now, it's just an alert.
//	alert("iAye is still being approved by the good folks over at Apple.  Until that happens, I'm afraid you can't buy the game just yet.  Sorry for the nag messages in the interim.");
	
	window.open("http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=308618883&mt=8");
}

function activateCrewManagementScreen()
{
	UpdateShipPartSelectbox('crewManagementShipComponents');
	SwitchWindows('crewmanActionScreen', 'crewManagementScreen');
	SwitchWindows('barScreen', 'crewManagementScreen');
	populateShipPartCrewmen();
	
	
}

function activateShipManagementScreen()
{
	setShipPartHighlight(playerShip, null);
//	drawShipPart(playerShip);
	UpdatePartDetails(playerShip, 'shipManagementImage', 'shipManagementHealthImage');

	document.getElementById("shipyardButton").style.display = "inline";
	document.getElementById("shipyardPartButton").style.display = "none";
	selectedShipPartID = -1;

	SwitchWindows('portShipyardScreen', 'shipManagementScreen');
	SwitchWindows('portMainScreen', 'shipManagementScreen');
	
}

function activateTradeScreen()
{
	SelectGoods(-1);
	document.getElementById("tradeCurrentCargoAmount").innerHTML = GetAdjustedStatistic(playerShip, "curCargo");
	document.getElementById("tradeTotalCargoSpace").innerHTML = GetAdjustedStatistic(playerShip, "maxCargo");
	document.getElementById("tradeAvailableCargoSpace").innerHTML = GetAdjustedStatistic(playerShip, "maxCargo") - GetAdjustedStatistic(playerShip, "curCargo");
	
	
	
	SwitchWindows('portMainScreen', 'portTradeScreen');
}

function activateMapScreen()
{
	dbSaveState();
	SetPortsVisible();
	SelectPortOnMap(currentPort);
	document.getElementById('closeQuickmapButton').style.display = "none";
	document.getElementById('mapInteractionButtons').style.display = "inline";
	SwitchWindows('portMainScreen', 'mapScreen');
	
}

function activateQuickmap() 
{
	var tmpScreen = currentWindowShown;
	SetPortsVisible();
	SelectPortOnMap(currentPort);
	SwitchWindows(tmpScreen, 'mapScreen');
	document.getElementById('mapInteractionButtons').style.display = "none";
	document.getElementById('closeQuickmapButton').style.display = "inline";
	document.getElementById('quickmapButton').style.display = "none";
	
	currentWindowShown = tmpScreen;
}

function closeQuickmap() {
	document.getElementById('quickmapButton').style.display = "inline";
	SwitchWindows('mapScreen', currentWindowShown);
}

function activateEncounterScreen()
{
	SwitchWindows('transitScreen', 'encounterScreen');
}

function activateMainScreen()
{
	SwitchWindows('introScreen', 'portMainScreen');
	document.getElementById("playerStatusBar").style.display = "inline";
}

function closeTransitScreen() {
	// swap windows, then check mission status.
	SwitchWindows('transitScreen', 'portMainScreen');
	testMissionDeadlines();
}

function activateRecruitmentScreen() {
	SwitchWindows('barScreen', 'recruitmentScreen');
	drawBarCrewmen();
}

function activateShipyardScreen() {

	// TODO: Add code to display appropriate div: hulls or parts
	if (document.getElementById("shipyardButton").style.display == "inline")
	{
		document.getElementById("shipPartsAvailable").style.display = "none";
		document.getElementById("shipHullsAvailable").style.display = "inline";
	} else {
		document.getElementById("shipPartsAvailable").style.display = "inline";
		document.getElementById("shipHullsAvailable").style.display = "none";
	}
	selectedShipyardPart = -1;
	drawAllShipyardParts();
	SwitchWindows('shipManagementScreen', 'portShipyardScreen');
}

function openStrategyGuide() {
	document.getElementById("fullHelpScreen").style.display = "inline";
}

function closeStrategyGuide() {
	document.getElementById("fullHelpScreen").style.display = "none";
}

function openHelp(specifyHelpScreen) {
	var helpMessage = "";
	
	if (specifyHelpScreen == null) {
		specifyHelpScreen = currentWindowShown;
	}
	
	switch (specifyHelpScreen) {
		case "loadWindow":
			helpMessage = "This is the loading screen.  If you find you're looking at it for a good long time, you may want to consider refreshing the display, as it's possible that not everything loaded properly; that said, it can take up to a minute or more for iAye to load over a slow or spotty connection.";
			break;
		case "mainMenu":
			helpMessage = "From this screen, you can start a new game.  If you have a game in progress, you may also choose to continue that game.";
			break;
		case "setupScreen":
			helpMessage = "This one's pretty self-explanatory.  Enter yer name in the first field, then enter the name of yer ship.";
			break;
		case "introScreen":
			helpMessage = "This screen doesn't really do anything but throw words at you.  All you need to do is read it and click the button at the bottom of the page.";
			break;
		case "portMainScreen":
			helpMessage = "This is the main screen for the system you're currently visiting.  From this screen, you have four options:<br /> <b>Trade</b>, which lets you buy and sell goods and manage missions;<br /><b>Manage Ship</b>, which lets you review your ship's stats, repair your ship, and purchase upgrades;<br /><b>Bar</b>, which lets you hire crewmen, manage your crew, and drink heavily;<br />and <b>Take Off</b>, which lets you navigate to other systems.";
			break;
		case "portTradeScreen":
			helpMessage = "On this screen you can buy and sell various goods.  The Buy column lists the total quantity available for purchase and the price per unit, in credits.  The Sell column lists the same information for selling goods you possess.  Green text indicates a good deal; red text, a bad deal.  Click on the name of a good to select that good for buying or selling.  Note that <b>Herb</b> and <b>Weapons</b> are contraband, and can cause trouble with the law.  Press the <b>Missions</b> button to view available missions.";
			break;
		case "portMissionScreen":
			helpMessage = "From here, you can accept and manage missions.  Click on a mission to select that mission, then click <b>Accept</b> to start that mission.  Any missions highlighted green are missions currently assigned to you.  If you fail to complete a mission in time, you'll often lose standing for it.";
			break;
		case "portShipyardScreen":
			helpMessage = "From this screen, you can repair any damage done to your ship, purchase a new ship, upgrade ship parts, and view the statistics for each part of your ship.  Most ships have one or more upgradable sections; to select a ship section, tap along the top or bottom section of the ship.  The currently selected section will become highlighted.  To select the entire ship, tap the leftmost portion of the main hull.";
			break;
		case "mapScreen":
			helpMessage = "From here, you can view and navigate to discovered systems.  Grey circles represent systems you haven't visited yet.  A government's airspace is represented by a shaded background.  To jump to a system, tap that system to select the system, then tap the \"Go!\" button.  If a system is beyond your ship's maximum jump range, the \"Go!\" button will not appear.";
			break;
		case "barScreen":
			helpMessage = "On this screen you can recruit new crewmen, manage your existing crewmen, and get hammered.  Getting hammered produces random results, and is generally an entertaining way to spend the night.  Recruiting crewmen allows you to augment the performance of your ship, and managing crewmen allows you to view and relocate your crew to maximize their efficacy.";
			break;
		case "recruitmentScreen":
			helpMessage = "Here you may hire new crewmen by clicking on their icons.  <b>NAV</b> affects the maximum range and speed of your ship; <b>GUN</b> affects the overall firepower and accuracy of your ship's guns; <b>ENG</b> affects your maximum armor and in-flight repairs; and <b>MKT</b> affects how much things end up costing you.  Positive numbers improve your stats; negative numbers detract.";
			break;
			case "crewManagementScreen":
			helpMessage = "Here you can view your current crew's stats and move crewmen from one part of the ship to another.  Crewmen in the main hull are well protected but do not influence the performance of your ship's attachments; crewmen in attachments enhance the performance of your main hull <i>and</i> the attachment they're in, but are vulnerable to loss in battle.";
			break;
			case "transitScreen":
			helpMessage = "This screen charts the progress of your travel from one system to the next.  When the red bar fills, you've arrived at your destination.";
			break;
			case "encounterScreen":
			helpMessage = "This screen gives the details of an encounter.  The enemy ship is shown, giving you some idea of that ship's strengths and weaknesses.  You may <b>attack</b> a ship, <b>flee</b> from a ship (if, say, it's a pirate, or an unfriendly naval ship,), or simply ignore the ship and continue on your way.";
			break;
			case "combatScreen":
			helpMessage = "Here you may select how to position your ship for the upcoming battle.  Each section of your ship may be given its own orders to more effectively dispatch your enemy.  If a section produces thrust, it may help <b>evade</b> incoming attacks; if a section has weaponry, it may <b>attack</b> any section of the enemy ship; if a section has crewwmen with engineering strength, it may engage in <b>damage control</b> for real-time repairs.";
			break;
			case "deadMessage":
			helpMessage = "This screen tells you that you've died, and the game is over.  Tough break.";
			break;
			case "shipManagementScreen":
			helpMessage = "Here, you can get a general overview of your ship's current stats and status, purchase new ships and parts, and repair your ship.  Click each individual ship part to view its stats; to view your entire ship, click the stern (back) of the ship.  Be sure to buy parts to upgrade your ship; also be aware that the stats you see reflect any bonuses gained from your crew.";
			break;
			case "":
			helpMessage = "";
			break;
	
	}
	if (helpMessage == "") {
		showAlertWindow("Help", "Sorry, but there is no help available for this screen.", "Close Help");
	} else {
		showAlertWindow("Help", helpMessage, "Close Help");
	}
	closeStrategyGuide();
}

jsFilesLoaded = jsFilesLoaded + 1;
