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


function RandomizePriceSettings()
{
	var i, j;
	for (i=0; i<portArray.length; i++)
	{
		for (j=0; j<portArray[i].portPriceVariance.length;j++)
		{
			portArray[i].portPriceVariance[j] = (rnd() * .5) + .75
			portArray[i].portPriceStability[j] = 1 - (rnd() * portArray[i].routeSecurity);
			portArray[i].portMaxStock[j] += Math.floor((portArray[i].portmaxStock * rnd() * .25) * portArray[i].routeSecurity); 
			portArray[i].portProductionRate[j] += Math.floor((portArray[i].portProductionRate[j] * rnd() * .25) * portArray[i].routeSecurity); 
			
			if ((rnd() * portArray[i].routeSecurity) < (rnd()))
			{
				// let this good not be manufactured here.  Make production and stock very low, and boost the price
				portArray[i].portProductionRate[j] = Math.floor(portArray[i].portProductionRate[j] * .1);
				portArray[i].portStock[j] = Math.floor(portArray[i].portStock[j] * .1);
				portArray[i].portPriceVariance[j] *= 1.25 + rnd();				
			}
			
			if (rnd() > 0.95) {
				// there's a 1 in 20 chance that any given good at any given port will be
				// produced in large quantities.  This good will have lower prices and higher
				// stocks and regeneration rates.
				portArray[i].portProductionRate[j] = Math.floor(portArray[i].portProductionRate[j] * (1+(rnd()*3)));
				portArray[i].portStock[j] = Math.floor(portArray[i].portStock[j] * (1+(rnd()*3)));
				portArray[i].portPriceVariance[j] *= 0.8 - (rnd()*0.4);				
			}
			
			if (portArray[i].portPriceStability[j]<0)
			{
				portArray[i].portPriceStability[j] = 0;
			}
		}
		if (portArray[i].routeSecurity < (rnd() * .65))
		{
			portArray[i].portLegal = 0;
		} else {
			portArray[i].portLegal = 1;
			portArray[i].portStock[6] = 0;
			portArray[i].portStock[7] = 0;
			portArray[i].portProductionRate[6] = 0;
			portArray[i].portProductionRate[7] = 0;
			portArray[i].portPriceVariance[6] = portArray[i].portPriceVariance[6] + 3;
			portArray[i].portPriceVariance[7] = portArray[i].portPriceVariance[7] + 3;
		}
		
	}
}

function SetPrices()
{

	var i, j;
	
	
	for (i=0; i<portArray.length; i++)
	{
		for (j=0; j<goodsBaseValues.length; j++)
		{
			portArray[i].portCurrentPrice[j] = Math.floor(((goodsBaseValues[j] * portArray[i].portPriceVariance[j])) - ((rnd() * (portArray[i].portPriceStability[j] * 2)) - portArray[i].portPriceStability[j]));
			portArray[i].portStock[j] += Math.floor(rnd() * portArray[i].portProductionRate[j]);
		}
	}

}

function TransferStocks(curPart, goodsIndex, quantity)
{
	var i;
	var tmpReturn;
	var cargoSpaceAvailable;
	if (quantity < 0)
	{
		for (i=0; i<curPart.attachments.length; i++)
		{
			if (curPart.attachments[i] != null)
			{
				quantity = TransferStocks(curPart.attachments[i], goodsIndex, quantity);
			}
		}

//		if (curPart.cargo[goodsIndex] != 0) {
//			alert("quantity: " + quantity + ", quantity in hold: " + curPart.cargo[goodsIndex]);
//		}
		
//		quantity = -quantity
		if (-quantity < curPart.cargo[goodsIndex])
		{
			curPart.curCargo = Math.floor(curPart.curCargo + quantity);
			curPart.cargo[goodsIndex] = curPart.cargo[goodsIndex] + quantity;
			return 0;
		} else {
			quantity = Math.floor(quantity + curPart.cargo[goodsIndex]);
			curPart.curCargo = Math.floor(curPart.curCargo - curPart.cargo[goodsIndex]);
			curPart.cargo[goodsIndex] = 0;
			return quantity;
//			return 0;
		}
	
	} else if (quantity > 0) {
//		alert("quantity > 0");

		if (quantity > (GetAdjustedStatistic(curPart, "maxCargo", "none", true) - curPart.curCargo))
		{
//			alert("quantity (" + quantity + ") > max (" + GetAdjustedStatistic(curPart, "maxCargo", "none", true) + ") - cur (" + curPart.curCargo + ")");
			cargoSpaceAvailable = GetAdjustedStatistic(curPart, "maxCargo", "none", true) - curPart.curCargo;
			curPart.cargo[goodsIndex] = curPart.cargo[goodsIndex] + cargoSpaceAvailable;
			curPart.curCargo += cargoSpaceAvailable;
			quantity = quantity - cargoSpaceAvailable;
		} else {
//			alert("quantity (" + quantity + ") < max (" + GetAdjustedStatistic(curPart, "maxCargo", "none", true) + ") - cur (" + curPart.curCargo + ")");
			curPart.cargo[goodsIndex] = Math.floor(curPart.cargo[goodsIndex] + quantity);
			curPart.curCargo = Math.floor(curPart.curCargo + quantity);
			quantity = 0;
		}
	
		for (i=0; i<curPart.attachments.length; i++)
		{
			if (curPart.attachments[i] != null)
			{
				quantity = TransferStocks(curPart.attachments[i], goodsIndex, quantity);
			}
		}
		return quantity;
		
	}
	document.getElementById("tradeCurrentCargoAmount").innerHTML = GetAdjustedStatistic(playerShip, "curCargo");
	document.getElementById("tradeTotalCargoSpace").innerHTML = GetAdjustedStatistic(playerShip, "maxCargo");
	document.getElementById("tradeAvailableCargoSpace").innerHTML = GetAdjustedStatistic(playerShip, "maxCargo") - GetAdjustedStatistic(playerShip, "curCargo");

}


function AdjustCash(adjustmentAmount)
{
//	alert("adjust player cash: " + playerCash + " + " + adjustmentAmount + " = " + (playerCash + adjustmentAmount));
	playerCash = playerCash + adjustmentAmount;
	
	if (playerCash > 500000 && isCrippledFreeVersion) {
		playerCash = 500000;
	}
	
	if (playerShip.fuel < playerShip.adjMaxFuel) {
		if (playerCash > playerShip.fuel - playerShip.adjMaxFuel) {
			playerCash = playerCash - (playerShip.adjMaxFuel - playerShip.fuel);
			playerShip.fuel = playerShip.adjMaxFuel;
		} else if (playerCash > 0) {
			playerShip.fuel = playerShip.fuel + playerCash;
			playerCash = 0;
		}
	}

	
	SetText("displayCash", playerCash);
//	SetText("tradeCash", playerCash);
	
}

function SelectGoods(goodsIndex)
{
	var i, j;
	var curBuyingPrice;
	var curSellingPrice;
	var curBuyingQuantity;
	var curSellingQuantity;
	var curCargoCapacity;
	var tmpOption;
	
	ClearAllChildren('buyGoods');
	ClearAllChildren('sellGoods');
/*	while (document.getElementById('buyGoods').childNodes[0]) {
document.getElementById('buyGoods').removeChild(document.getElementById('buyGoods').childNodes[0]);
	}	
	while (document.getElementById('sellGoods').childNodes[0]) {
document.getElementById('sellGoods').removeChild(document.getElementById('sellGoods').childNodes[0]);	
	}
*/	
	document.getElementById("buyGoods").style.setProperty("display", "none");
	document.getElementById("sellGoods").style.setProperty("display", "none");
	document.getElementById("tradeBuyButton").style.setProperty("display", "none");
	document.getElementById("tradeSellButton").style.setProperty("display", "none");
	
	for (i=0; i<goodsNames.length; i++)
	{
	
		curBuyingPrice = Math.floor(portArray[currentPort].portCurrentPrice[i] * (1 + GetAdjustedStatistic(playerShip, "profitMargin")));
		curSellingPrice = Math.floor(portArray[currentPort].portCurrentPrice[i] * (1 - GetAdjustedStatistic(playerShip, "profitMargin")));
		curBuyingQuantity = Coalesce(portArray[currentPort].portStock[i], "0");
		curSellingQuantity = Coalesce(GetPartStatistic(playerShip, "cargo["+i+"]"), "0")
		
		SetText("tradeBuy"+i, curBuyingQuantity + " @ " + curBuyingPrice + " cr");
		
		SetText("tradeSell"+i, curSellingQuantity + " @ " + curSellingPrice + " cr");


		


		if (i==goodsIndex)
		{
			document.getElementById("tradeBuy"+i).className = "tradeBarSelected";
			document.getElementById("tradeGood"+i).className = "tradeBarSelected";
			document.getElementById("tradeSell"+i).className = "tradeBarSelected";
			
			// highlight good/bad deals
			
			if (portArray[currentPort].portCurrentPrice[i]/goodsBaseValues[i] <0.8) {
			document.getElementById("tradeBuy"+i).style.color = "#99FF99";
			document.getElementById("tradeSell"+i).style.color = "#FF9999";
			} else if (portArray[currentPort].portCurrentPrice[i]/goodsBaseValues[i] > 1.2) {
			document.getElementById("tradeBuy"+i).style.color = "#FF9999";
			document.getElementById("tradeSell"+i).style.color = "#99FF99";
			} else {
			document.getElementById("tradeBuy"+i).style.color = "#FFFFFF";
			document.getElementById("tradeSell"+i).style.color = "#FFFFFF";
			}
			
			
			if (curBuyingQuantity > 0)
			{
//				curCargoCapacity = GetAdjustedStatistic(playerShip, "maxCargo", "none", true);
//				for (j=0; j<playerShip.attachments.length; j++) {
//					if (playerShip.attachments[j] != null) {
//						curCargoCapacity = curCargoCapacity + GetAdjustedStatistic(playerShip.attachments[j], "maxCargo", "none", true);
//					}
//				}
				curCargoCapacity = Coalesce(GetAdjustedStatistic(playerShip, "maxCargo"), "0");
//				alert("buying: " + curCargoCapacity + " - " + GetAdjustedStatistic(playerShip, "curCargo", "children", true));
                curCargoCapacity = curCargoCapacity - GetAdjustedStatistic(playerShip, "curCargo");
				
				
				document.getElementById("buyGoods").style.setProperty("display", "block");
				document.getElementById("tradeBuyButton").style.setProperty("display", "block");
				if (curCargoCapacity > curBuyingQuantity)
				{
					curCargoCapacity = curBuyingQuantity;
				}
				if ((curCargoCapacity * curBuyingPrice) > (playerCash))
				{
					curCargoCapacity = Math.floor(playerCash / curBuyingPrice);
				}
				
				if (curCargoCapacity > 0)
				{
					
				
					// add label
					tmpOption = document.createElement("option");
					tmpOption.setAttribute("value", 0);
					tmpOption.appendChild(document.createTextNode("Buy " + goodsNames[i] + "..."));
					document.getElementById('buyGoods').appendChild(tmpOption);

					// add max option
					tmpOption = document.createElement("option");
					tmpOption.setAttribute("value", curCargoCapacity);
					tmpOption.appendChild(document.createTextNode("Max (" + curCargoCapacity + " @ " + (curCargoCapacity * curBuyingPrice) + ")"));
					document.getElementById('buyGoods').appendChild(tmpOption);

					// add separator
					tmpOption = document.createElement("option");
					tmpOption.setAttribute("value", 0);
					tmpOption.appendChild(document.createTextNode("========="));
					document.getElementById('buyGoods').appendChild(tmpOption);

					for (j=1; j<=curCargoCapacity; j++)
					{
						tmpOption = document.createElement("option");
						tmpOption.setAttribute("value", j);
						tmpOption.appendChild(document.createTextNode("Buy " + j + " @ " + (j * curBuyingPrice)));
							document.getElementById('buyGoods').appendChild(tmpOption);
					}
//					alert("setting buyGoods onChange...");
					document.getElementById('buyGoods').setAttribute("onChange", "PurchaseGoods(" + i + ");");
				} else {
				document.getElementById("buyGoods").style.setProperty("display", "none");
				document.getElementById("tradeBuyButton").style.setProperty("display", "none");
				}
			} else {
				document.getElementById("buyGoods").style.setProperty("display", "none");
				document.getElementById("tradeBuyButton").style.setProperty("display", "none");
			}

			if (curSellingQuantity > 0)
			{
				document.getElementById("sellGoods").style.setProperty("display", "block");
				document.getElementById("tradeSellButton").style.setProperty("display", "block");
			
				// add label
				tmpOption = document.createElement("option");
				tmpOption.setAttribute("value", 0);
				tmpOption.appendChild(document.createTextNode("Sell " + goodsNames[i] + "..."));
				document.getElementById('sellGoods').appendChild(tmpOption);

				// add max option
				tmpOption = document.createElement("option");
				tmpOption.setAttribute("value", curSellingQuantity);
				tmpOption.appendChild(document.createTextNode("Max (" + curSellingQuantity + " @ " + (curSellingQuantity * curSellingPrice) + ")"));
				document.getElementById('sellGoods').appendChild(tmpOption);

				// add separator
				tmpOption = document.createElement("option");
				tmpOption.setAttribute("value", 0);
				tmpOption.appendChild(document.createTextNode("========="));
				document.getElementById('sellGoods').appendChild(tmpOption);

				for (j=1; j<=curSellingQuantity; j++)
				{
					tmpOption = document.createElement("option");
					tmpOption.setAttribute("value", j);
					tmpOption.appendChild(document.createTextNode("Sell " + j + " @ " + (j * curSellingPrice)));
						document.getElementById('sellGoods').appendChild(tmpOption);
				}
//				alert("setting sellGoods onChange...");
				document.getElementById('sellGoods').setAttribute("onChange", "SellGoods(" + i + ");");
			}
			
		} else {
			document.getElementById("tradeBuy"+i).className = "tradeBar";
			document.getElementById("tradeGood"+i).className = "tradeBar";
			document.getElementById("tradeSell"+i).className = "tradeBar";

			// highlight good/bad deals
			
			if (portArray[currentPort].portCurrentPrice[i]/goodsBaseValues[i] < 0.8) {
			document.getElementById("tradeBuy"+i).style.color = "#009900";
			document.getElementById("tradeSell"+i).style.color = "#990000";
			} else if (portArray[currentPort].portCurrentPrice[i]/goodsBaseValues[i] > 1.2) {
			document.getElementById("tradeBuy"+i).style.color = "#990000";
			document.getElementById("tradeSell"+i).style.color = "#009900";
			} else {
			document.getElementById("tradeBuy"+i).style.color = "#000000";
			document.getElementById("tradeSell"+i).style.color = "#000000";
			}
		}
	}
}

function PurchaseGoods(goodsIndex)
{
	var i;
	
	
	adjustReputation((document.getElementById("buyGoods").value * goodsKarma[goodsIndex]), currentPort);	
	TransferStocks(playerShip, goodsIndex, Math.floor(document.getElementById("buyGoods").value));
	portArray[currentPort].portStock[goodsIndex] -= Math.floor(document.getElementById("buyGoods").value);
	AdjustCash(-document.getElementById("buyGoods").value * (Math.floor(portArray[currentPort].portCurrentPrice[goodsIndex] * (1 + GetAdjustedStatistic(playerShip, "profitMargin")))));
	document.getElementById("currentItemCargo").innerHTML = GetAdjustedStatistic(playerShip, "curCargo");
//	alert("blurring buyGoods selectbox...");
	document.getElementById("buyGoods").blur();
	SelectGoods(goodsIndex);
	
}

function SellGoods(goodsIndex)
{
	var i;
	
	adjustReputation((document.getElementById("sellGoods").value * goodsKarma[goodsIndex]), currentPort);
	TransferStocks(playerShip, goodsIndex, -document.getElementById("sellGoods").value);
	portArray[currentPort].portStock[goodsIndex] += Math.floor((document.getElementById("sellGoods").value) * 2 / 3);
	AdjustCash(document.getElementById("sellGoods").value * (Math.floor(portArray[currentPort].portCurrentPrice[goodsIndex] * (1 - GetAdjustedStatistic(playerShip, "profitMargin")))));
//	alert("blurring sellGoods selectbox...");
	document.getElementById("sellGoods").blur();
	SelectGoods(goodsIndex);
	
}


jsFilesLoaded = jsFilesLoaded + 1;
